commit 094fd76a7277375e0ca2f1a13e6d406d6312df07 Author: caocong Date: Mon Jan 5 09:40:42 2026 +0800 新增:首次提交 首次提交,上传Launcher工程 diff --git a/.cproject b/.cproject new file mode 100644 index 0000000..ffd59b1 --- /dev/null +++ b/.cproject @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbfa0fd --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +obj diff --git a/.project b/.project new file mode 100644 index 0000000..764350e --- /dev/null +++ b/.project @@ -0,0 +1,37 @@ + + + BLV_C1P_Bootload + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + 1692846627047 + + 22 + + org.eclipse.ui.ide.multiFilter + 1.0-name-matches-false-false-*.wvproj + + + + diff --git a/.settings/language.settings.xml b/.settings/language.settings.xml new file mode 100644 index 0000000..c0c7c82 --- /dev/null +++ b/.settings/language.settings.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/.settings/org.eclipse.cdt.managedbuilder.core.prefs b/.settings/org.eclipse.cdt.managedbuilder.core.prefs new file mode 100644 index 0000000..f34230b --- /dev/null +++ b/.settings/org.eclipse.cdt.managedbuilder.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/CPATH/delimiter=; +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/CPATH/operation=remove +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/C_INCLUDE_PATH/delimiter=; +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/C_INCLUDE_PATH/operation=remove +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/append=true +environment/buildEnvironmentInclude/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/appendContributed=true +environment/buildEnvironmentLibrary/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/LIBRARY_PATH/delimiter=; +environment/buildEnvironmentLibrary/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/LIBRARY_PATH/operation=remove +environment/buildEnvironmentLibrary/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/append=true +environment/buildEnvironmentLibrary/ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074/appendContributed=true diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..50f01ad --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +encoding/.cproject=GBK +encoding//Peripheral/inc/ch564.h=UTF-8 diff --git a/.template b/.template new file mode 100644 index 0000000..6498948 --- /dev/null +++ b/.template @@ -0,0 +1,18 @@ +Vendor=WCH +Toolchain=RISC-V +Series=CH564 +RTOS=NoneOS +MCU=CH564F +Link=WCH-Link +PeripheralVersion=====1.2 +Description=====CH564 is an industrial-grade microcontroller based on barley RISC-V core design. CH564 built-in USBHS PHY and PD PHY, support for USB Host host and USB Device device functions, PDUSB and Type-C fast charging; built-in Ethernet controller MAC and 10 megabits/100 megabits physical layer transceiver; provides an external bus interface XBUS, 8-bit passive parallel port SLV, 12-bit analogue-to-digital converter ADC, multi-group timer, 4-group UART serial port, I2C interface, 2 SPI interface and other rich peripheral resources. +Mcu Type=CH564 +Address=0x00000000 +Target Path=obj\BLV_C1P_20250514.hex +CLKSpeed=1 +DebugInterfaceMode=1 +Erase All=true +Program=true +Verify=true +Reset=true +SDIPrintf=false diff --git a/BLV_C1P_Bootload.wvproj b/BLV_C1P_Bootload.wvproj new file mode 100644 index 0000000..33ec8c5 --- /dev/null +++ b/BLV_C1P_Bootload.wvproj @@ -0,0 +1 @@ +?6`Ob9Kt!6;$ XAIENR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); +} + +/********************************************************************* + * @fn NVIC_DisableIRQ + * + * @brief Disable Interrupt + * + * @param IRQn - Interrupt Numbers + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) +{ + NVIC->IRER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); +} + +/********************************************************************* + * @fn NVIC_GetStatusIRQ + * + * @brief Get Interrupt Enable State + * + * @param IRQn - Interrupt Numbers + * + * @return 1 - Interrupt Pending Enable + * 0 - Interrupt Pending Disable + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t NVIC_GetStatusIRQ(IRQn_Type IRQn) +{ + return ((uint32_t)((NVIC->ISR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F))) ? 1 : 0)); +} + +/********************************************************************* + * @fn NVIC_GetPendingIRQ + * + * @brief Get Interrupt Pending State + * + * @param IRQn - Interrupt Numbers + * + * @return 1 - Interrupt Pending Enable + * 0 - Interrupt Pending Disable + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) +{ + return ((uint32_t)((NVIC->IPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F))) ? 1 : 0)); +} + +/********************************************************************* + * @fn NVIC_SetPendingIRQ + * + * @brief Set Interrupt Pending + * + * @param IRQn - Interrupt Numbers + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) +{ + NVIC->IPSR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); +} + +/********************************************************************* + * @fn NVIC_ClearPendingIRQ + * + * @brief Clear Interrupt Pending + * + * @param IRQn - Interrupt Numbers + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) +{ + NVIC->IPRR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); +} + +/********************************************************************* + * @fn NVIC_GetActive + * + * @brief Get Interrupt Active State + * + * @param IRQn - Interrupt Numbers + * + * @return 1 - Interrupt Active + * 0 - Interrupt No Active + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) +{ + return ((uint32_t)((NVIC->IACTR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F))) ? 1 : 0)); +} + +/********************************************************************* + * @fn NVIC_SetPriority + * + * @brief Set Interrupt Priority + * + * @param IRQn - Interrupt Numbers + * interrupt nesting enable(CSR-0x804 bit1 = 1) + * priority - bit[7] - Preemption Priority + * bit[6:5] - Sub priority + * bit[4:0] - Reserve + * interrupt nesting disable(CSR-0x804 bit1 = 0) + * priority - bit[7:5] - Sub priority + * bit[4:0] - Reserve + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint8_t priority) +{ + NVIC->IPRIOR[(uint32_t)(IRQn)] = priority; +} + +/********************************************************************* + * @fn __WFI + * + * @brief Wait for Interrupt + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void __WFI(void) +{ + NVIC->SCTLR &= ~(1 << 3); // wfi + __asm volatile("wfi"); +} + +/********************************************************************* + * @fn _SEV + * + * @brief Set Event + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void _SEV(void) +{ + uint32_t t; + + t = NVIC->SCTLR; + NVIC->SCTLR |= (1 << 3) | (1 << 5); + NVIC->SCTLR = (NVIC->SCTLR & ~(1 << 5)) | (t & (1 << 5)); +} + +/********************************************************************* + * @fn _WFE + * + * @brief Wait for Events + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void _WFE(void) +{ + NVIC->SCTLR |= (1 << 3); + __asm volatile("wfi"); +} + +/********************************************************************* + * @fn __WFE + * + * @brief Wait for Events + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void __WFE(void) +{ + _SEV(); + _WFE(); + _WFE(); +} + +/********************************************************************* + * @fn SetVTFIRQ + * + * @brief Set VTF Interrupt + * + * @param addr - VTF interrupt service function base address. + * IRQn - Interrupt Numbers + * num - VTF Interrupt Numbers + * NewState - DISABLE or ENABLE + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void SetVTFIRQ(uint32_t addr, IRQn_Type IRQn, uint8_t num, + FunctionalState NewState) +{ + if (num > 3) + return; + + if (NewState != DISABLE) + { + NVIC->VTFIDR[num] = IRQn; + NVIC->VTFADDR[num] = ((addr & 0xFFFFFFFE) | 0x1); + } + else + { + NVIC->VTFIDR[num] = IRQn; + NVIC->VTFADDR[num] = ((addr & 0xFFFFFFFE) & (~0x1)); + } +} + +/********************************************************************* + * @fn ICacheEnable + * + * @brief Enable ICache + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void ICacheEnable(void) +{ + WRITE_CSR(0xBD0, 0x4); + __asm volatile("fence.i"); + CLEAR_CSR(0xBC2, 0x2); +} + +/********************************************************************* + * @fn ICacheDisable + * + * @brief Disable ICache + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void ICacheDisable(void) +{ + SET_CSR(0xBC2, 0x2); + WRITE_CSR(0xBD0, 0x4); + __asm volatile("fence.i"); +} + +/********************************************************************* + * @fn ICacheInvalidate + * + * @brief Invalidate ICache + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void ICacheInvalidate(void) +{ + WRITE_CSR(0xBD0, 0x4); + __asm volatile("fence.i"); +} + +/********************************************************************* + * @fn ICacheInvalidate_By_Address + * + * @brief Invalidate ICache By Address + * + * @param addr - operation address(addr%4 = 0) + * size - operation size(unit 4Byte) + * + * @return none + */ +__attribute__((always_inline)) RV_STATIC_INLINE void ICacheInvalidate_By_Address(uint32_t *addr, uint32_t size) +{ + uint32_t t; + uint32_t temp; + + for (t = 0; t < size; t++) + { + temp = (uint32_t)(addr + t); + WRITE_CSR(0xBD0, (temp & 0xFFFFFFF8)); + __asm volatile("fence.i"); + } +} + + + +/********************************************************************* + * @fn __AMOADD_W + * + * @brief Atomic Add with 32bit value + * Atomically ADD 32bit value with value in memory using amoadd.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be ADDed + * + * @return return memory value + add value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOADD_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amoadd.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOAND_W + * + * @brief Atomic And with 32bit value + * Atomically AND 32bit value with value in memory using amoand.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be ANDed + * + * @return return memory value & and value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOAND_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amoand.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOMAX_W + * + * @brief Atomic signed MAX with 32bit value + * Atomically signed max compare 32bit value with value in memory using amomax.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be compared + * + * @return the bigger value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOMAX_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amomax.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOMAXU_W + * + * @brief Atomic unsigned MAX with 32bit value + * Atomically unsigned max compare 32bit value with value in memory using amomaxu.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be compared + * + * @return return the bigger value + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t __AMOMAXU_W(volatile uint32_t *addr, uint32_t value) +{ + uint32_t result; + + __asm volatile("amomaxu.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOMIN_W + * + * @brief Atomic signed MIN with 32bit value + * Atomically signed min compare 32bit value with value in memory using amomin.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be compared + * + * @return the smaller value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOMIN_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amomin.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOMINU_W + * + * @brief Atomic unsigned MIN with 32bit value + * Atomically unsigned min compare 32bit value with value in memory using amominu.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be compared + * + * @return the smaller value + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t __AMOMINU_W(volatile uint32_t *addr, uint32_t value) +{ + uint32_t result; + + __asm volatile("amominu.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOOR_W + * + * @brief Atomic OR with 32bit value + * Atomically OR 32bit value with value in memory using amoor.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be ORed + * + * @return return memory value | and value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOOR_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amoor.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/********************************************************************* + * @fn __AMOSWAP_W + * + * @brief Atomically swap new 32bit value into memory using amoswap.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * newval - New value to be stored into the address + * + * @return return the original value in memory + */ +__attribute__((always_inline)) RV_STATIC_INLINE uint32_t __AMOSWAP_W(volatile uint32_t *addr, uint32_t newval) +{ + uint32_t result; + + __asm volatile("amoswap.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(newval) : "memory"); + return result; +} + +/********************************************************************* + * @fn __AMOXOR_W + * + * @brief Atomic XOR with 32bit value + * Atomically XOR 32bit value with value in memory using amoxor.d. + * + * @param addr - Address pointer to data, address need to be 4byte aligned + * value - value to be XORed + * + * @return return memory value ^ and value + */ +__attribute__((always_inline)) RV_STATIC_INLINE int32_t __AMOXOR_W(volatile int32_t *addr, int32_t value) +{ + int32_t result; + + __asm volatile("amoxor.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); + return *addr; +} + +/* Core_Exported_Functions */ +extern uint32_t __get_MSTATUS(void); +extern void __set_MSTATUS(uint32_t value); +extern uint32_t __get_MISA(void); +extern void __set_MISA(uint32_t value); +extern uint32_t __get_MTVEC(void); +extern void __set_MTVEC(uint32_t value); +extern uint32_t __get_MSCRATCH(void); +extern void __set_MSCRATCH(uint32_t value); +extern uint32_t __get_MEPC(void); +extern void __set_MEPC(uint32_t value); +extern uint32_t __get_MCAUSE(void); +extern void __set_MCAUSE(uint32_t value); +extern uint32_t __get_MTVAL(void); +extern void __set_MTVAL(uint32_t value); +extern uint32_t __get_MVENDORID(void); +extern uint32_t __get_MARCHID(void); +extern uint32_t __get_MIMPID(void); +extern uint32_t __get_MHARTID(void); +extern uint32_t __get_SP(void); +extern void NVIC_SystemReset(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Flashlib/ISP564.h b/Flashlib/ISP564.h new file mode 100644 index 0000000..9e4296c --- /dev/null +++ b/Flashlib/ISP564.h @@ -0,0 +1,263 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ISP564.h + * Author : WCH + * Version : V1.1.0 + * Date : 2024/07/17 + * Description : This file contains all the functions prototypes for the + * FLASH firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __ISP564_H +#define __ISP564_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "stdint.h" + +/* FLASH Status */ +typedef enum +{ + FLASH_COMPLETE, + FLASH_TIMEOUT, + FLASH_VERIFY_ERROR, + FLASH_ADR_RANGE_ERROR, + FLASH_UNLOCK_ERROR, +}FLASH_Status; + +/********************************************************************* + * @fn FLASH_Unlock + * + * @brief Unlocks the FLASH Program and Erase Controller. + * + * @return none + */ +extern void FLASH_Unlock(void); + +/********************************************************************* + * @fn FLASH_Lock + * + * @brief Locks the FLASH Program and Erase Controller. + * + * @return none + */ +extern void FLASH_Lock(void); + +/********************************************************************* + * @fn GetMACAddress + * + * @brief Get MAC address(6Bytes) + * + * @param Buffer - Pointer to the buffer where data should be stored, + * Must be aligned to 4 bytes. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT. + */ +extern FLASH_Status GetMACAddress( void *Buffer ); + +/********************************************************************* + * @fn GET_UNIQUE_ID + * + * @brief Get unique ID(8Bytes) + * + * @param Buffer - Pointer to the buffer where data should be stored, + * Must be aligned to 4 bytes. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT. + */ +extern FLASH_Status GET_UNIQUE_ID( void *Buffer ); + +/********************************************************************* + * @fn GetCHIPID + * + * @brief Get chip ID(4Bytes) + * + * @param Buffer - Pointer to the buffer where data should be stored, + * Must be aligned to 4 bytes. + * ChipID List- + * CH564L-0x564005x8 + * CH564Q-0x564105x8 + * CH564F-0x564305x8 + * CH564C-0x564205x8 + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT. + */ +extern FLASH_Status GetCHIPID( void *Buffer ); + +/********************************************************************* + * @fn Get_Flash_Size + * + * @brief Get FLASH Size(1Bytes) + * + * @param Buffer - Pointer to the buffer where data should be stored. + * 0 - FLASH-256K + * ROMA(UserFLASH) + * - Size(192K) + * - Address range(0x0 -- 0x2FFFF) + * EEPROM(DataFLASH) + * - Size(32K) + * - Address range(0x30000 -- 0x37FFF) + * 1 - FLASH-512K + * ROMA(UserFLASH) + * - Size(448K) + * - Address range(0x0 -- 0x6FFFF) + * EEPROM(DataFLASH) + * - Size(32K) + * - Address range(0x70000 -- 0x77FFF) + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT. + */ +extern FLASH_Status Get_Flash_Size( void *Buffer ); + +/********************************************************************* + * @fn FLASH_EnableCodeProtection + * + * @brief Enables the code protection. + * + * @return FLASH Status - The returned value can be: FLASH_BUSY, FLASH_ERROR_PG, + * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +extern FLASH_Status FLASH_EnableCodeProtection( void ); + +/********************************************************************* + * @fn FLASH_ROM_PWR_UP + * + * @brief The function `FLASH_ROM_PWR_DOWN` sends a command to put + * the SPI flash memory into power down mode. + * + * @return none + */ +extern void FLASH_ROM_PWR_DOWN( void ); + +/********************************************************************* + * @fn FLASH_ROM_PWR_UP + * + * @brief The function `FLASH_ROM_PWR_UP` sets up the SPI flash + * control register to power up the flash memory + * + * @return none + */ +extern void FLASH_ROM_PWR_UP( void ); + +/********************************************************************* + * @fn EEPROM_READ + * + * @brief (DataFLASH) - The EEPROM_READ function reads data from a specified address + * in flash memory with error handling for address range checks. + * + * @param StartAddr - Read the starting address of the DataFLASH. + * Buffer - Read the value of the DataFLASH. + * Length - Read the length of the DataFLASH. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR. + */ +extern FLASH_Status EEPROM_READ( uint32_t StartAddr, void *Buffer, uint32_t Length ); + +/********************************************************************* + * @fn EEPROM_ERASE + * + * @brief (DataFLASH) - The function EEPROM_ERASE checks the flash size and address + * range before erasing a specified portion of flash memory. + * + * @param StartAddr - Erases the starting address of the DataFLASH(StartAddr%4096 == 0). + * Length - Erases the length of the DataFLASH(Length%4096 == 0). + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR,FLASH_UNLOCK_ERROR. + */ +extern FLASH_Status EEPROM_ERASE( uint32_t StartAddr, uint32_t Length ); + +/********************************************************************* + * @fn EEPROM_WRITE + * + * @brief (DataFLASH) - The function EEPROM_WRITE writes data to EEPROM memory + * based on specified address and length, performing address + * range and unlock checks. + * + * @param StartAddr - Writes the starting address of the DataFLASH. + * Buffer - Writes the value of the DataFLASH. + * Length - Writes the length of the DataFLASH. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR,FLASH_UNLOCK_ERROR. + */ +extern FLASH_Status EEPROM_WRITE( uint32_t StartAddr, void *Buffer, uint32_t Length ); + +/********************************************************************* + * @fn FLASH_ROMA_ERASE + * + * @brief (UserFLASH) - The function `FLASH_ROMA_ERASE` checks the flash size and + * address range before erasing a specified portion of flash + * memory. + * + * @param StartAddr - Erases the starting address of the UserFLASH(StartAddr%4096 == 0). + * Length - Erases the length of the UserFLASH(Length%4096 == 0). + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR,FLASH_UNLOCK_ERROR. + */ +extern FLASH_Status FLASH_ROMA_ERASE( uint32_t StartAddr, uint32_t Length ); + +/********************************************************************* + * @fn FLASH_ROMA_WRITE + * + * @brief (UserFLASH) - The function FLASH_ROMA_WRITE writes data to a specific + * flash memory address after performing size and unlock checks. + * + * @param StartAddr - Writes the starting address of the UserFLASH. + * Buffer - Writes the value of the UserFLASH. + * Length - Writes the length of the UserFLASH. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR,FLASH_UNLOCK_ERROR. + */ +extern FLASH_Status FLASH_ROMA_WRITE( uint32_t StartAddr, void *Buffer, uint32_t Length ); + +/********************************************************************* + * @fn FLASH_ROMA_VERIFY + * + * @brief (UserFLASH) - The function `FLASH_ROMA_VERIFY` verifies the contents of + * a specified flash memory region against a provided buffer. + * + * @param StartAddr - Verify the starting address of the UserFLASH. + * Buffer - Verify the value of the UserFLASH. + * Length - Verify the length of the UserFLASH. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR,FLASH_VERIFY_ERROR. + */ +extern FLASH_Status FLASH_ROMA_VERIFY( uint32_t StartAddr, void *Buffer, uint32_t Length ); + +/********************************************************************* + * @fn FLASH_ROMA_READ + * + * @brief (UserFLASH) - The function `FLASH_ROMA_READ` reads data from a specific + * flash memory address with error handling for different flash + * size + * + * @param StartAddr - Read the starting address of the UserFLASH. + * Buffer - Read the value of the UserFLASH. + * Length - Read the length of the UserFLASH. + * + * @return FLASH_Status -The returned value can be: FLASH_COMPLETE, + * FLASH_TIMEOUT,FLASH_ADR_RANGE_ERROR. + */ +extern FLASH_Status FLASH_ROMA_READ( uint32_t StartAddr, void *Buffer, uint32_t Length ); + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Flashlib/libISP564.a b/Flashlib/libISP564.a new file mode 100644 index 0000000..698c08e Binary files /dev/null and b/Flashlib/libISP564.a differ diff --git a/Ld/Link.ld b/Ld/Link.ld new file mode 100644 index 0000000..d65c35a --- /dev/null +++ b/Ld/Link.ld @@ -0,0 +1,222 @@ +ENTRY( _start ) + +__stack_size = 4096; + +PROVIDE( _stack_size = __stack_size ); + + +MEMORY +{ +/* FLASH + RAM supports the following configuration + FLASH-80K + RAM-64K + FLASH-48K + RAM-96K + FLASH-16K + RAM-128K +*/ + +/* FLASH-16K + RAM-128K */ +/* + FLASH (rx) : ORIGIN = 0x00000000 , LENGTH = 16K + FLASH1 (rx) : ORIGIN = 0x00004000 , LENGTH = 448K - 16K + RAM (xrw) : ORIGIN = 0x20000000 , LENGTH = 128K +*/ +/* + FLASH (rx) : ORIGIN = 0x20000000 , LENGTH = 28K + FLASH1 (rx) : ORIGIN = 0x00028000 , LENGTH = 448K - 160K + RAM (xrw) : ORIGIN = 0x20007000 , LENGTH = 64K - 28K +*/ +/* FLASH-48K + RAM-96K */ +/* + FLASH (rx) : ORIGIN = 0x00000000 , LENGTH = 48K + FLASH1 (rx) : ORIGIN = 0x0000C000 , LENGTH = 448K - 48K + RAM (xrw) : ORIGIN = 0x20000000 , LENGTH = 96K +*/ + +/* FLASH-80K + RAM-64K */ +/* + FLASH (rx) : ORIGIN = 0x00000000 , LENGTH = 80K + FLASH1 (rx) : ORIGIN = 0x00014000 , LENGTH = 448K - 80K + RAM (xrw) : ORIGIN = 0x20000000 , LENGTH = 64K +*/ + + FLASH (rx) : ORIGIN = 0x00000000 , LENGTH = 80K + FLASH1 (rx) : ORIGIN = 0x00014000 , LENGTH = 448K - 80K + RAM (xrw) : ORIGIN = 0x20000000 , LENGTH = 64K +} + + +SECTIONS +{ + .init : + { + _sinit = .; + . = ALIGN(4); + KEEP(*(SORT_NONE(.init))) + . = ALIGN(4); + _einit = .; + } >FLASH AT>FLASH + + .vector : + { + *(.vector); + _endof_Vector = .; + ASSERT(_endof_Vector < ORIGIN(FLASH1), "The vector must maintain in 0-wait zone"); + . = ALIGN(4); + } >FLASH AT>FLASH + + PROVIDE( _cache_beg = __cache_beg ); + PROVIDE( _cache_end = __cache_end ); + + .text : + { + . = ALIGN(4); + KEEP(*libISP564.a:(.text)) + KEEP(*libISP564.a:(.text.*)) + KEEP(*libISP564.a:(.rodata)) + KEEP(*libISP564.a:(.rodata.*)) + _endof_Flashlib = .; + ASSERT(_endof_Flashlib < ORIGIN(FLASH1), "The Flash lib must maintain in 0-wait zone"); + *(.text) + *(.text.*) + *(.rodata) + *(.rodata*) + *(.gnu.linkonce.t.*) + . = ALIGN(4); + } >FLASH AT>FLASH + + .text1 : + { + . = ALIGN(4); + PROVIDE( __cache_beg = .); + *(.cache); + *(.cache.*); + PROVIDE( __cache_end = .); + *(.non_0_wait); + *(.non_0_wait.*); + . = ALIGN(4); + } >FLASH1 AT>FLASH1 + + .fini : + { + KEEP(*(SORT_NONE(.fini))) + . = ALIGN(4); + } >FLASH AT>FLASH + + PROVIDE( _etext = . ); + PROVIDE( _eitcm = . ); + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH AT>FLASH + + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) + KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH AT>FLASH + + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) + KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH AT>FLASH + + .ctors : + { + /* gcc uses crtbegin.o to find the start of + the constructors, so we make sure it is + first. Because this is a wildcard, it + doesn't matter if the user does not + actually link against crtbegin.o; the + linker won't look for a file to match a + wildcard. The wildcard also means that it + doesn't matter which directory crtbegin.o + is in. */ + KEEP (*crtbegin.o(.ctors)) + KEEP (*crtbegin?.o(.ctors)) + /* We don't want to include the .ctor section from + the crtend.o file until after the sorted ctors. + The .ctor section from the crtend file contains the + end of ctors marker and it must be last */ + KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*(.ctors)) + } >FLASH AT>FLASH + + .dtors : + { + KEEP (*crtbegin.o(.dtors)) + KEEP (*crtbegin?.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*(.dtors)) + } >FLASH AT>FLASH + + .dalign : + { + . = ALIGN(4); + PROVIDE(_data_vma = .); + } >RAM AT>FLASH + + .dlalign : + { + . = ALIGN(4); + PROVIDE(_data_lma = .); + } >FLASH AT>FLASH + + .data : + { + *(.gnu.linkonce.r.*) + *(.data .data.*) + *(.gnu.linkonce.d.*) + . = ALIGN(8); + PROVIDE( __global_pointer$ = . + 0x800 ); + *(.sdata .sdata.*) + *(.sdata2.*) + *(.gnu.linkonce.s.*) + . = ALIGN(8); + *(.srodata.cst16) + *(.srodata.cst8) + *(.srodata.cst4) + *(.srodata.cst2) + *(.srodata .srodata.*) + . = ALIGN(4); + PROVIDE( _edata = .); + } >RAM AT>FLASH + + .bss : + { + . = ALIGN(4); + PROVIDE( _sbss = .); + *(.sbss*) + *(.gnu.linkonce.sb.*) + *(.bss*) + *(.gnu.linkonce.b.*) + *(COMMON*) + . = ALIGN(4); + PROVIDE( _ebss = .); + } >RAM AT>FLASH + + PROVIDE( _end = _ebss); + PROVIDE( end = . ); + + .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size : + { + PROVIDE( _heap_end = . ); + . = ALIGN(4); + PROVIDE(_susrstack = . ); + . = . + __stack_size; + PROVIDE( _eusrstack = .); + } >RAM + +} + + + + diff --git a/MCU_Driver/bootload_fun.c b/MCU_Driver/bootload_fun.c new file mode 100644 index 0000000..d8712d4 --- /dev/null +++ b/MCU_Driver/bootload_fun.c @@ -0,0 +1,1149 @@ +/* + * launcher_fun.c + * Code Flashܿռ 0x00000000 ~ 0x00070000 448KB + * Launcher 0x00000000 ~ 0x00003FFF 16KB + * APP 0x00004000 ~ 0x0006FFFF 432KB + * Data Flashܿռ 0x00070000 ~ 0x00077FFF 32KB + * + * Created on: Jul 28, 2025 + * Author: cc + */ +#include "includes.h" +#include + +G_SYS_FEATURE_T g_app_feature; +G_SYS_FEATURE_T g_mcu_app_feature; +UPDATE_RECORD_T g_update_recode; //Ϣ + +uint8_t g_jump_flag = 0; //ת־λ +uint32_t g_Boot_Tick = 0; //Bootʱ λms +uint32_t g_Boot_Time= 0; //Bootʱ λms + +/******************************************************************************* +* Function Name : Boot_Time_Refresh +* Description : Bootʱ +*******************************************************************************/ +void Boot_Time_Refresh(void) +{ + g_Boot_Tick = SysTick_1ms; +} + +/******************************************************************************* +* Function Name : Boot_Timeout_Task +* Description : Bootʱ +*******************************************************************************/ +void Boot_Timeout_Task(void) +{ + if(SysTick_1ms - g_Boot_Tick >= g_Boot_Time) + { + while(1); //ִпŹλ + } +} + +/********************************************************************* + * @fn Jump_APP + * @brief תAPP + * @param addr - APPʼַ + * @return none + */ +void Jump_APP(uint32_t addr) +{ +// __asm volatile("jr %0": :"r"(addr)); + __asm("li a6, 0x0E000"); + __asm("jr a6"); + + while(1); +} + +/******************************************************************************* +* Function Name : SPI_FLASH_APP_Data_Erase +* Description : ⲿFlash APPռ +* APPռС Size: 0x00070000 ַΧ0x00000000 ~ 0x0006FFFF +*******************************************************************************/ +void SPI_FLASH_APP_Data_Erase(void) +{ + for(uint8_t i = 0;i < 7;i++) + { + Flash_Erase_Block(i); + } +} + +/******************************************************************************* +* Function Name : SPI_FLASH_Logic_File_Erase +* Description : ⲿFlash ļռ +* APPռС Size: 0x00090000 ַΧ0x00070000 ~ 0x000FFFFF +*******************************************************************************/ +void SPI_FLASH_Logic_File_Erase(void) +{ + for(uint8_t i = 7;i < 16;i++) + { + Flash_Erase_Block(i); + } +} + +/******************************************************************************* +* Function Name : CRC16_Check +* Description : CRC16У㷨 +*******************************************************************************/ +uint16_t CRC16_Check(uint8_t * aStr, uint16_t len) +{ + uint16_t xda , xdapoly ; + uint16_t i, j, xdabit ; + xda = 0xFFFF ; + xdapoly = 0xA001 ; // (X**16 + X**15 + X**2 + 1) + for (i = 0; i < len; i++) + { + xda ^= aStr[i] ; + for (j = 0; j < 8; j++) + { + xdabit = (unsigned char)(xda & 0x01) ; + xda >>= 1 ; + if ( xdabit ) xda ^= xdapoly ; + } + } + return xda; +} + + +/******************************************************************************* +* Function Name : Boot_Comm_FillReplyPack +* Description : BootͨѶЭظݴ +*******************************************************************************/ +void Boot_Comm_FillReplyPack(UART_t *g_rev) +{ + uint16_t data_len = g_rev->ackLen + BCOMM_FMT_PARAM; + + g_rev->ackBuffer[BCOMM_FMT_TXAddr] = g_mcu_dev.dev_addr; + g_rev->ackBuffer[BCOMM_FMT_SN] = g_rev->sn; + g_rev->ackBuffer[BCOMM_FMT_TYPE] = g_mcu_dev.dev_type; + g_rev->ackBuffer[BCOMM_FMT_RXAddr] = g_rev->pc_addr; + + g_rev->ackBuffer[BCOMM_FMT_CMD] = g_rev->cmd; + g_rev->ackBuffer[BCOMM_FMT_LEN_L] = data_len & 0xFF; + g_rev->ackBuffer[BCOMM_FMT_LEN_H] = (data_len >> 8) & 0xFF; + + g_rev->ackBuffer[BCOMM_FMT_CKS] = 0; + + g_rev->ackBuffer[BCOMM_FMT_CKS] = Data_CheckSum(g_rev->ackBuffer, data_len); + +#if DBG_LOG_EN + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"ACKBuff ",g_rev->ackBuffer,data_len); +#endif + + g_rev->send_data_cf(g_rev->ackBuffer,data_len); + +// memset(g_rev->ackBuffer,0,USART_BUFFER_SIZE); +// g_rev->ackLen = 0x00; +} + +uint8_t Launcher_Uart_Upgrade_Process(UART_t *g_rev) +{ + uint8_t deal_flag = 0,group_flag = 0,reply_flag = 0; + uint16_t crcNumIndex = 0,crcResultFlag = 0; + uint32_t temp_val = 0,temp_val_2 = 0; + + /*ڻе */ + __disable_irq(); + memcpy(g_rev->deal_buff,g_rev->RecvBuffer,g_rev->RecvLen); + g_rev->deal_len = g_rev->RecvLen; + g_rev->RecvLen = 0; + memset(g_rev->RecvBuffer,0,USART_BUFFER_SIZE); + + g_rev->Receiving = 0x00; //ս + g_rev->CommBusy &= ~(UART_COMMBUSY_RECV_Flag); //ձ־λ + + __enable_irq(); + + DBG_SYS_Printf("Len %d \r\n",g_rev->deal_len); + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"UARTx_Buff:",g_rev->deal_buff,g_rev->deal_len); + + temp_val = g_rev->deal_buff[BCOMM_FMT_LEN_H]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_LEN_L]; + + if(temp_val != g_rev->deal_len) + { + DBG_SYS_Printf("Len Fail \r\n"); + return 0x01; + } + + if(Data_CheckSum(g_rev->deal_buff,g_rev->deal_len) != 0) { + DBG_SYS_Printf("Boot_Comm_CheckSum Fail:%x ",Data_CheckSum(g_rev->deal_buff,g_rev->deal_len)); + return 0x02; + } + + if( (g_rev->deal_buff[BCOMM_FMT_SN] & 0x80) == 0x80){ + //Ⱥ־λ + group_flag = 0x01; + if( (g_rev->deal_buff[BCOMM_FMT_SN] & 0x0F) != g_rev->sn){ + deal_flag = 0x01; + + DBG_SYS_Printf("Group Data SN Disaffinity,Processing Data"); + }else { + deal_flag = 0x00; + + DBG_SYS_Printf("Group Data SN The Same,No Processing Data"); + } + }else { + //־λ + group_flag = 0x00; + if( (g_rev->deal_buff[BCOMM_FMT_SN] & 0x0F) != g_rev->sn){ + //Ų̫ͬҪ + DBG_SYS_Printf("Single Data SN Disaffinity,Processing Data"); + + deal_flag = 0x01; + reply_flag = 0x01; + }else if( (g_rev->deal_buff[BCOMM_FMT_SN] & 0x40) == 0x40 ){ + //ͬط־λλҪظ + deal_flag = 0x00; + reply_flag = 0x01; + + DBG_SYS_Printf("Single Data SN The Same,No Processing Data"); + } + } + + /*жǷͬҲǹ㲥*/ + if( (g_rev->deal_buff[BCOMM_FMT_TYPE] != g_mcu_dev.dev_type) && (g_rev->deal_buff[BCOMM_FMT_TYPE] != 0xFF) ){ + DBG_SYS_Printf("Boot_Comm_RecvType %d - %d ",g_mcu_dev.dev_type,g_rev->deal_buff[BCOMM_FMT_TYPE]); + return 0x03; + } + /*жǷ㲥㲥ַ*/ + if( (g_rev->deal_buff[BCOMM_FMT_RXAddr] != g_mcu_dev.dev_addr) && (g_rev->deal_buff[BCOMM_FMT_RXAddr] != 0xFF) ){ + DBG_SYS_Printf("Boot_Comm_RecvAddr %d - %d ",g_mcu_dev.dev_addr,g_rev->deal_buff[BCOMM_FMT_RXAddr]); + return 0x04; + } + + Boot_Time_Refresh(); + g_rev->pc_addr = g_rev->deal_buff[BCOMM_FMT_TXAddr]; + g_rev->sn = g_rev->deal_buff[BCOMM_FMT_SN] & 0x0F; + g_rev->cmd = g_rev->deal_buff[BCOMM_FMT_CMD]; + + switch(g_rev->cmd) + { + case BCOMM_CMD_Handshake: + + if( ( deal_flag == 0x01 ) && ( g_rev->deal_len >= ( BCOMM_FMT_PARAM + 4 ) ) ) { + /*Boot ʱʱ λS*/ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + if(temp_val != g_Boot_Time) + { + g_Boot_Time = temp_val; + if(g_Boot_Time < 10) g_Boot_Time = 10; + g_Boot_Time = g_Boot_Time * 1000; + } + + /*ظݵЧ*/ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + g_rev->ackValidity = temp_val; + } + + // - Ҫظݣظ + if(reply_flag != 0x01) break; //ظֱ˳ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = Project_Area; //ǰBootload 0x01Boot;0x02APP + g_rev->ackBuffer[BCOMM_FMT_PARAM + 1] = g_mcu_dev.dev_boot_ver; //Boot 汾 + g_rev->ackBuffer[BCOMM_FMT_PARAM + 2] = g_mcu_dev.dev_app_ver; //APP 汾 + //MCU UID + g_rev->ackBuffer[BCOMM_FMT_PARAM + 3] = 0x06; //CH564 MACַΪΨһID 6Byte + + GetMACAddress(&g_rev->ackBuffer[BCOMM_FMT_PARAM + 4]); + + //ͱ - 32Byte + g_rev->ackBuffer[BCOMM_FMT_PARAM + 10] = g_mcu_dev.dev_name_len; + g_rev->ackLen = 11; + for(uint8_t i=0;iackBuffer[BCOMM_FMT_PARAM + i + 11] = g_mcu_dev.dev_name[i]; + g_rev->ackLen++; + } + + break; + case BCOMM_CMD_Jump: //ת + if(deal_flag != 0x01) break; //ֱ˳ + + if(g_rev->deal_buff[BCOMM_FMT_PARAM] == 0x02){ + /*תAPP*/ + g_Boot_Time = 200; //Bootʱת + g_Boot_Tick = SysTick_1ms; + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + }else { + /**/ + + DBG_SYS_Printf("ERR:Jump_boot"); + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + } + + g_rev->ackLen = 1; + break; + case BCOMM_CMD_SetInfo: //ò + if(deal_flag != 0x01) break; //ֱ˳ + + if(g_rev->deal_len < (BCOMM_FMT_PARAM + 4) ) { + DBG_SYS_Printf("BCOMM_CMD_SetInfo Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_SetInfo Proecessing "); + + /*òʲ*/ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + temp_val *= 100; + + /*Boot ʱʱ*/ + g_Boot_Time = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + g_Boot_Time <<= 8; + g_Boot_Time |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + if(g_Boot_Time < 10) g_Boot_Time = 10; + g_Boot_Time = g_Boot_Time * 1000; + + DBG_SYS_Printf("BaudSet: %d",temp_val); + DBG_SYS_Printf("bootTimeout: %d",g_Boot_Time); + + g_rev->ChangeBaudFlag = 0x01; + g_rev->CommBaud = temp_val; + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + g_rev->ackLen = 1; + + break; + case BCOMM_CMD_WriteFlash: //дFlash + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 6) ) { + DBG_SYS_Printf("BCOMM_CMD_WriteFlash Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_WriteFlash Proecessing "); + + /*дFlashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + /*дFlash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + + DBG_SYS_Printf("WAddr: 0x%x Len:%d",temp_val,temp_val_2); + + if (temp_val_2 == ( g_rev->deal_len - BCOMM_FMT_PARAM - 6 )){ + /*Flash д*/ + + //g_rev->ackBuffer[BCOMM_FMT_PARAM] = MCU_APP_Flash_Write(&g_rev->deal_buff[BCOMM_FMT_PARAM + 6],temp_val_2,temp_val); + + Flash_Write_NoCheck(&g_rev->deal_buff[BCOMM_FMT_PARAM + 6],temp_val_2,temp_val); + + Flash_Read(g_read_buff, temp_val_2,temp_val); + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"App CRC BUFF:",g_read_buff,temp_val_2); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + }else { + /*дFlash ڵַΧ */ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + } + g_rev->ackLen = 1; + break; + case BCOMM_CMD_ReadFlash: //ȡFlash + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 6) ) { + DBG_SYS_Printf("BCOMM_CMD_ReadFlash Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_ReadFlash Proecessing "); + + /*ȡFlashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + /*ȡFlash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + + if(temp_val_2 > BCOMM_ParaSize) temp_val_2 = BCOMM_ParaSize; //ܳACK BUFFС + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = MCU_APP_Flash_Read(&g_rev->ackBuffer[BCOMM_FMT_PARAM + 1],temp_val_2,temp_val); + if(g_rev->ackBuffer[BCOMM_FMT_PARAM] == BCOMM_CMD_ReplySUCC) + { + g_rev->ackLen = temp_val_2 + 1; + }else { + g_rev->ackLen = 1; + } + break; + case BCOMM_CMD_EraseFlash: //Flash + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 1) ) { + DBG_SYS_Printf("BCOMM_CMD_ReadFlash Para Error "); + break; + } + DBG_SYS_Printf("BCOMM_CMD_EraseFlash Proecessing "); + + if(g_rev->deal_buff[BCOMM_FMT_PARAM] == 0x01){ + /*APP Flash ָ*/ + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 7) ) { + DBG_SYS_Printf("BCOMM_CMD_EraseFlash Para Error "); + break; + } + + /*Flashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + + /*Flash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 6]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + + if( (MCU_APP_Flash_Start_Addr <= temp_val) && ( (temp_val + temp_val_2) < MCU_APP_Flash_End_Addr ) ){ + + DBG_SYS_Printf("EraseFlash Addr:%x Len:%d ",temp_val,temp_val_2); + + temp_val = temp_val - (temp_val % MCU_APP_Flash_PageSize); + for(uint32_t i = temp_val;i<(temp_val + temp_val_2) ;i+=MCU_APP_Flash_PageSize){ + + DBG_SYS_Printf("PageErase Addr:%x ",i); + + //FLASH_ROMA_ERASE(i,MCU_APP_Flash_PageSize); + //Flash_Erase_Sector(i); + } + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + g_rev->ackLen = 1; + }else { + /*дFlash ڵַΧ */ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + g_rev->ackLen = 1; + } + + }else if(g_rev->deal_buff[BCOMM_FMT_PARAM] == 0x02){ + /*ȫAPP Flash ͬʱҲAPP */ + SPI_FLASH_APP_Data_Erase(); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + g_rev->ackLen = 1; + }else { + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + g_rev->ackLen = 1; + } + break; + case BCOMM_CMD_WriteEEPROM: //дEEPROM + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 6) ) { + DBG_SYS_Printf("BCOMM_CMD_WriteEEPROM Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_WriteEEPROM Proecessing "); + + /*дFlashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + /*дFlash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + + DBG_SYS_Printf("WAddr: 0x%x Len:%d",temp_val,temp_val_2); + + if (temp_val_2 == ( g_rev->deal_len - BCOMM_FMT_PARAM - 6 )){ + /*Flash д*/ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = MCU_EEPROM_Write(&g_rev->deal_buff[BCOMM_FMT_PARAM + 6],temp_val_2,temp_val); + }else { + /*дFlash ڵַΧ */ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + } + g_rev->ackLen = 1; + + break; + case BCOMM_CMD_ReadEEPROM: //дEEPROM + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 6) ) { + DBG_SYS_Printf("BCOMM_CMD_ReadFlash Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_ReadFlash Proecessing "); + + /*ȡFlashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + /*ȡFlash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + + if(temp_val_2 > BCOMM_ParaSize) temp_val_2 = BCOMM_ParaSize; //ܳACK BUFFС + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = MCU_APP_Flash_Read(&g_rev->ackBuffer[BCOMM_FMT_PARAM + 1],temp_val_2,temp_val); + if(g_rev->ackBuffer[BCOMM_FMT_PARAM] == BCOMM_CMD_ReplySUCC) + { + g_rev->ackLen = temp_val_2 + 1; + }else { + g_rev->ackLen = 1; + } + break; + case BCOMM_CMD_EraseEEPROM: //EEPROM + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 1) ) { + DBG_SYS_Printf("BCOMM_CMD_EraseEEPROM Para Error "); + break; + } + DBG_SYS_Printf("BCOMM_CMD_EraseEEPROM Proecessing "); + + if(g_rev->deal_buff[BCOMM_FMT_PARAM] == 0x01){ + /*APP Flash ָ*/ + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 7) ) { + DBG_SYS_Printf("BCOMM_CMD_EraseEEPROM Para Error "); + break; + } + + /*Flashַ */ + temp_val = g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + temp_val <<= 8; + temp_val |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + + /*Flash */ + temp_val_2 = g_rev->deal_buff[BCOMM_FMT_PARAM + 6]; + temp_val_2 <<= 8; + temp_val_2 |= g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + + if( (MCU_APP_Flash_Start_Addr <= temp_val) && ( (temp_val + temp_val_2) < MCU_APP_Flash_End_Addr ) ){ + + DBG_SYS_Printf("EraseFlash Addr:%x Len:%d ",temp_val,temp_val_2); + + temp_val = temp_val - (temp_val % MCU_APP_Flash_PageSize); + for(uint32_t i = temp_val;i<(temp_val + temp_val_2) ;i+=MCU_APP_Flash_PageSize){ + + DBG_SYS_Printf("PageErase Addr:%x ",i); + + FLASH_ROMA_ERASE(i,MCU_APP_Flash_PageSize); + } + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + g_rev->ackLen = 1; + }else { + /*дFlash ڵַΧ */ + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + g_rev->ackLen = 1; + } + + }else if(g_rev->deal_buff[BCOMM_FMT_PARAM] == 0x02){ + /*ȫEEPROM*/ + MCU_EEPROM_ALLErase(); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + g_rev->ackLen = 1; + }else { + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplyFAIL; + g_rev->ackLen = 1; + } + break; + case BCOMM_CMD_CheckData: //У + if(deal_flag != 0x01) break; //ֱ˳ + + if( g_rev->deal_len < (BCOMM_FMT_PARAM + 10) ) { + + DBG_SYS_Printf("BCOMM_CMD_CheckData Para Error "); + break; + } + + DBG_SYS_Printf("BCOMM_CMD_CheckData Proecessing "); + + memset(&g_app_feature,0,sizeof(G_SYS_FEATURE_T)); + + /* УCRC ʼַ*/ + g_app_feature.app_start_addr = g_rev->deal_buff[BCOMM_FMT_PARAM + 3]; + g_app_feature.app_start_addr <<= 8; + g_app_feature.app_start_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM + 2]; + g_app_feature.app_start_addr <<= 8; + g_app_feature.app_start_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM + 1]; + g_app_feature.app_start_addr <<= 8; + g_app_feature.app_start_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM]; + + /* УCRC ַ*/ + g_app_feature.app_end_addr = g_rev->deal_buff[BCOMM_FMT_PARAM + 7]; + g_app_feature.app_end_addr <<= 8; + g_app_feature.app_end_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM + 6]; + g_app_feature.app_end_addr <<= 8; + g_app_feature.app_end_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM + 5]; + g_app_feature.app_end_addr <<= 8; + g_app_feature.app_end_addr |= g_rev->deal_buff[BCOMM_FMT_PARAM + 4]; + + /* УCRC С*/ + g_app_feature.app_crc_size = g_rev->deal_buff[BCOMM_FMT_PARAM + 9]; + g_app_feature.app_crc_size <<= 8; + g_app_feature.app_crc_size |= g_rev->deal_buff[BCOMM_FMT_PARAM + 8]; + + DBG_SYS_Printf("App Start_addr :%x ",g_app_feature.app_start_addr); + DBG_SYS_Printf("App End_addr :%x ",g_app_feature.app_end_addr); + DBG_SYS_Printf("App CRC Block_Size :%d ",g_app_feature.app_crc_size); + + if( (g_app_feature.app_start_addr >= MCU_APP_Flash_Start_Addr) + && (g_app_feature.app_end_addr < MCU_APP_Flash_End_Addr) + && (g_app_feature.app_end_addr > g_app_feature.app_start_addr) + && (g_app_feature.app_crc_size == MCU_APP_Flash_PageSize) ) + { + temp_val = g_app_feature.app_end_addr - g_app_feature.app_start_addr; + + DBG_SYS_Printf("App Len :%d ",temp_val); + + if( (temp_val % g_app_feature.app_crc_size ) != 0x00 ){ + g_app_feature.app_crc_len = ((temp_val / g_app_feature.app_crc_size) + 1) * 2; + }else { + g_app_feature.app_crc_len = (temp_val / g_app_feature.app_crc_size) * 2; + } + + DBG_SYS_Printf("App CRC BLock:%d ",g_app_feature.app_crc_len); + + /*ȶУݰ Բ */ + if( (BCOMM_FMT_PARAM + 10 + g_app_feature.app_crc_len ) == g_rev->deal_len ){ + + uint32_t crc_data_len = 0; + crcNumIndex = 0; + + memcpy(g_app_feature.app_crc,&g_rev->deal_buff[BCOMM_FMT_PARAM + 10],(g_rev->deal_len - 10 - BCOMM_FMT_PARAM) ); + + for(uint32_t crc_addr = g_app_feature.app_start_addr; crc_addr < g_app_feature.app_end_addr;crc_addr += g_app_feature.app_crc_size) + { + if( g_app_feature.app_end_addr - crc_addr >= g_app_feature.app_crc_size) { + crc_data_len = g_app_feature.app_crc_size; + }else { + crc_data_len = g_app_feature.app_end_addr - crc_addr; + } + + memset(g_read_buff,0,sizeof(g_read_buff)); + + if(crc_data_len > 2048) + { + Flash_Read(g_read_buff,2048,crc_addr); + Flash_Read(&g_read_buff[2048],(crc_data_len - 2048),crc_addr+2048); + }else { + Flash_Read(g_read_buff,crc_data_len,crc_addr); + } + + temp_val = CRC16_Check(g_read_buff,crc_data_len); + temp_val_2 = g_app_feature.app_crc[crcNumIndex + 1]; + temp_val_2 <<= 8; + temp_val_2 |= g_app_feature.app_crc[crcNumIndex]; + + //DBG_SYS_Printf("App CRC ADDR:%x %x-%x",crc_addr,temp_val,temp_val_2); + //Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"App CRC BUFF:",g_read_buff,crc_data_len); + + if(temp_val != temp_val_2){ + /*Уʧ - */ + + g_rev->ackBuffer[BCOMM_FMT_PARAM ] = BCOMM_CMD_ReplyFAIL; + g_rev->ackBuffer[BCOMM_FMT_PARAM + 5 + crcResultFlag*4] = ((crc_addr >> 24) & 0xFF); + g_rev->ackBuffer[BCOMM_FMT_PARAM + 4 + crcResultFlag*4] = ((crc_addr >> 16) & 0xFF); + g_rev->ackBuffer[BCOMM_FMT_PARAM + 3 + crcResultFlag*4] = ((crc_addr >> 8) & 0xFF); + g_rev->ackBuffer[BCOMM_FMT_PARAM + 2 + crcResultFlag*4] = (crc_addr & 0xFF); + + DBG_SYS_Printf("App CRC Fail ADDR:%X %X-%X",crc_addr,temp_val,temp_val_2); + + crcResultFlag++; + if(crcResultFlag >= 20) break; + } + crcNumIndex += 2; + } + + if(crcResultFlag == 0x00){ + /*Уɹ - дAPP */ + g_app_feature.app_flag = App_Procedure_Ready; + g_app_feature.crc_check = 0x00; + + Write_APP_Feature_Info(0x02,&g_app_feature); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = BCOMM_CMD_ReplySUCC; + } + + g_rev->ackBuffer[BCOMM_FMT_PARAM + 1] = crcResultFlag; + g_rev->ackLen = 2 + crcResultFlag*4; + }else { + /*ݰ*/ + DBG_SYS_Printf("App CRC BLock ERROR:%d %d",temp_val,g_rev->deal_len); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = 0x02; + g_rev->ackLen = 1; + } + }else{ + + DBG_SYS_Printf("App CRC Para ERROR"); + + g_rev->ackBuffer[BCOMM_FMT_PARAM] = 0x01; + g_rev->ackLen = 1; + } + break; + + } + + /*ظͨѶ*/ + if( (group_flag == 0x00) && (reply_flag == 0x01) ) + { + Boot_Comm_FillReplyPack(g_rev); + } + + return 0; +} + +/******************************************************************************* +* Function Name : Read_APP_Feature +* Description : ȡAPP +* Return : + 0û + 1FlashAPPȷ + 2MCU APPҪ +*******************************************************************************/ +uint8_t Read_APP_Feature(void) +{ + uint8_t rev = 0; + uint8_t crcResultFlag = TRUE; + uint16_t crcNumIndex = 0; + uint16_t crcVal = 0; + uint8_t crcValH = 0, crcValL = 0; + uint32_t crc_data_len = 0; + + memset(&g_app_feature,0,sizeof(G_SYS_FEATURE_T)); + memset(&g_mcu_app_feature,0,sizeof(G_SYS_FEATURE_T)); + + /*һȶȡⲿFlashAPPǷݣͬʱ֤APPĺϷ*/ + rev = Read_APP_Feature_Info(0x02,&g_app_feature); + if(rev == 0x00) + { + DBG_SYS_Printf("SPIFlash APP Feature Check Succ"); + APP_Feature_Info_Printf(&g_app_feature); + + /*жAPP ־λǷ*/ + if(g_app_feature.app_flag == App_Procedure_Ready) + { + /*жAPP ʼַַԼCRCУСǷڷΧ*/ + if( ( g_app_feature.app_start_addr < MCU_APP_Flash_Start_Addr ) \ + || ( g_app_feature.app_end_addr > MCU_APP_Flash_End_Addr ) \ + || ( g_app_feature.app_crc_size != MCU_APP_Flash_PageSize ) ) + { + DBG_SYS_Printf("SPIFlash Flash APP ADDRESS ERROR!"); + LOG_Launcher_APP_Check_Record(0x03); + return 1; + } + + /*ⲿflash УAPP*/ + crcNumIndex = 0; + memset(g_read_buff,0,sizeof(g_read_buff)); + for(uint32_t i = g_app_feature.app_start_addr; i < g_app_feature.app_end_addr; i += g_app_feature.app_crc_size) + { + if( g_app_feature.app_end_addr - i >= g_app_feature.app_crc_size) { + crc_data_len = g_app_feature.app_crc_size; + }else { + crc_data_len = g_app_feature.app_end_addr - i; + } + + memset(g_read_buff,0,sizeof(g_read_buff)); + + if(crc_data_len > 2048) + { + Flash_Read(g_read_buff,2048,i); + Flash_Read(&g_read_buff[2048],(crc_data_len - 2048),i+2048); + }else { + Flash_Read(g_read_buff,crc_data_len,i); + } + + crcVal = CRC16_Check(g_read_buff, crc_data_len); + crcValH = crcVal >> 8; + crcValL = crcVal & 0xFF; + if((g_app_feature.app_crc[crcNumIndex + 1] != crcValH) || (g_app_feature.app_crc[ crcNumIndex] != crcValL)) + { + DBG_SYS_Printf("block:%d , app_crc:%x%x , crcVal:%X\r\n",crcNumIndex,g_app_feature.app_crc[crcNumIndex],g_app_feature.app_crc[1 + crcNumIndex],crcVal); + + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"Read Flash:",g_read_buff,MCU_APP_Flash_PageSize); + + crcResultFlag = FALSE; + break; + } + crcNumIndex+=2; + } + if(crcResultFlag == FALSE) + { + DBG_SYS_Printf("SPI FLash APP ERROR! - APP\r\n"); + + //Flash APP + Flash_Erase_Pageaddr(SPIFLASH_APP_FEATURE_Addr); + + LOG_Launcher_APP_Check_Record(0x04); + return 1; //Уʧ + } + }else{ + LOG_Launcher_APP_Check_Record(0x05); + return 1; //ûAPP + } + }else { + DBG_SYS_Printf("SPIFlash APP Feature Check Fail \r\n"); + LOG_Launcher_APP_Check_Record(0x06); + return 1; + } + + /*ڶȶȡMCU FlashAPPǷݣͬʱ֤APPĺϷ*/ + rev = Read_APP_Feature_Info(0x01,&g_mcu_app_feature); + if(rev == 0x00) + { + DBG_SYS_Printf("MCU Flash APP Feature Check Succ"); + APP_Feature_Info_Printf(&g_mcu_app_feature); + + /*жAPP ־λǷ*/ + if(g_mcu_app_feature.app_flag == App_Procedure_Ready) + { + /*жAPP ʼַַԼCRCУСǷڷΧ*/ + if( ( g_mcu_app_feature.app_start_addr < MCU_APP_Flash_Start_Addr ) \ + || ( g_mcu_app_feature.app_end_addr > MCU_APP_Flash_End_Addr ) \ + || ( g_mcu_app_feature.app_crc_size != MCU_APP_Flash_PageSize ) ) + { + DBG_SYS_Printf("MCU Flash APP ADDRESS ERROR!"); + LOG_Launcher_APP_Check_Record(0x03); + return 1; + } + + /*ⲿflash УAPP*/ + crcNumIndex = 0; + memset(g_read_buff,0,sizeof(g_read_buff)); + for(uint32_t i = g_mcu_app_feature.app_start_addr; i < g_mcu_app_feature.app_end_addr; i += g_mcu_app_feature.app_crc_size) + { + if( g_app_feature.app_end_addr - i >= g_app_feature.app_crc_size) { + crc_data_len = g_app_feature.app_crc_size; + }else { + crc_data_len = g_app_feature.app_end_addr - i; + } + + memset(g_read_buff,0,sizeof(g_read_buff)); + + MCU_APP_Flash_Read(g_read_buff ,crc_data_len,i); + + crcVal = CRC16_Check(g_read_buff, crc_data_len); + crcValH = crcVal >> 8; + crcValL = crcVal & 0xFF; + if((g_mcu_app_feature.app_crc[crcNumIndex + 1] != crcValH) || (g_mcu_app_feature.app_crc[crcNumIndex] != crcValL)) + { + DBG_SYS_Printf("block:%d , app_crc:%x%x , crcVal:%X\r\n",crcNumIndex,g_mcu_app_feature.app_crc[crcNumIndex],g_mcu_app_feature.app_crc[1 + crcNumIndex],crcVal); + + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"Read Flash:",g_read_buff,MCU_APP_Flash_PageSize); + + crcResultFlag = FALSE; + break; + } + crcNumIndex+=2; + } + if(crcResultFlag == FALSE) + { + DBG_SYS_Printf("APP ERROR! \r\n"); + + LOG_Launcher_APP_Check_Record(0x07); + return 2; //Уʧ + } + }else{ + LOG_Launcher_APP_Check_Record(0x08); + return 2; + } + }else { + DBG_SYS_Printf("MCU Feature ERROR! \r\n"); + LOG_Launcher_APP_Check_Record(0x09); + return 2; + } + + /*жMCU FlashеǷⲿSPI FlashеǷһ*/ + if(g_app_feature.app_crc_len != g_mcu_app_feature.app_crc_len) { + DBG_SYS_Printf("app_crc_len different!\r\n"); + LOG_Launcher_APP_Check_Record(0x02); + return 2; + } + + if(g_app_feature.app_start_addr != g_mcu_app_feature.app_start_addr) { + DBG_SYS_Printf("app_start_addr different!\r\n"); + LOG_Launcher_APP_Check_Record(0x02); + return 2; + } + + if(g_app_feature.app_end_addr != g_mcu_app_feature.app_end_addr) { + DBG_SYS_Printf("app_end_addr different!\r\n"); + LOG_Launcher_APP_Check_Record(0x02); + return 2; + } + + for(uint16_t j = 0;j MCU_APP_Data_End_Addr ) ){ + DBG_SYS_Printf("MCU Flash app_start_addr:0x%x Error",g_app_feature.app_start_addr); + return 0x01; + } + + if( ( g_app_feature.app_end_addr > MCU_APP_Data_End_Addr ) || ( g_app_feature.app_start_addr > g_app_feature.app_end_addr ) ){ + DBG_SYS_Printf("MCU Flash app_end_addr:0x%x - 0x%x Error",g_app_feature.app_start_addr,g_app_feature.app_end_addr); + return 0x01; + } + + if( g_app_feature.app_crc_size != MCU_APP_Flash_PageSize ){ + DBG_SYS_Printf("MCU Flash app_crc_size:%x Error",g_app_feature.app_crc_size); + return 0x01; + } + + /*1дAPP Flash - տСдAPP Flash*/ + for(uint32_t i = g_app_feature.app_start_addr;i < g_app_feature.app_end_addr;i += MCU_APP_Flash_PageSize ) + { + if( g_app_feature.app_end_addr - i >= g_app_feature.app_crc_size) { + crc_data_len = g_app_feature.app_crc_size; + }else { + crc_data_len = g_app_feature.app_end_addr - i; + } + + memset(g_read_buff,0,sizeof(g_read_buff)); + + if(crc_data_len > 2048) + { + Flash_Read(g_read_buff,2048,i); + Flash_Read(&g_read_buff[2048],(crc_data_len - 2048),i+2048); + }else { + Flash_Read(g_read_buff,crc_data_len,i); + } + + DBG_SYS_Printf("MCU Write APP Addr:%x",i); + + rev = MCU_APP_Flash_Write(g_read_buff,crc_data_len,i); + + if(rev != 0x00){ + DBG_SYS_Printf("MCU Flash Write:%x Error",i); + + return 0x01; + } + } + + /*2дAPP */ + g_mcu_app_feature.app_flag = g_app_feature.app_flag; + g_mcu_app_feature.app_start_addr = g_app_feature.app_start_addr; + g_mcu_app_feature.app_end_addr = g_app_feature.app_end_addr; + g_mcu_app_feature.app_crc_size = g_app_feature.app_crc_size; + g_mcu_app_feature.app_crc_len = g_app_feature.app_crc_len; + g_mcu_app_feature.crc_check = g_app_feature.crc_check; + memcpy(g_mcu_app_feature.app_crc,g_app_feature.app_crc,APP_Feature_CRC_Size); + rev = Write_APP_Feature_Info(0x01,&g_mcu_app_feature); + if(rev != 0x00){ + DBG_SYS_Printf("MCU Write APP Feature_Info Error"); + + return 0x01; + } + + /*3ȡAPPݣҶAPP FlashݽCRCУ*/ + rev = Read_APP_Feature_Info(0x01,&g_mcu_app_feature); + if(rev != 0x00){ + DBG_SYS_Printf("MCU Read APP Feature_Info Error"); + + return 0x01; + } + + for(uint32_t i = g_mcu_app_feature.app_start_addr; i < g_mcu_app_feature.app_end_addr; i += MCU_APP_Flash_PageSize) + { + if( g_app_feature.app_end_addr - i >= g_app_feature.app_crc_size) { + crc_data_len = g_app_feature.app_crc_size; + }else { + crc_data_len = g_app_feature.app_end_addr - i; + } + + memset(g_read_buff,0,sizeof(g_read_buff)); + + rev = MCU_APP_Flash_Read(g_read_buff,crc_data_len,i); + Dbg_Print_Buff(DBG_BIT_SYS_STATUS, "MCU Flash:", g_read_buff, crc_data_len); + + crcVal = CRC16_Check(g_read_buff, crc_data_len); + crcValH = crcVal >> 8; + crcValL = crcVal & 0xFF; + + DBG_SYS_Printf("MCU Write APP Addr:%x - CRC:%x",i,crcVal); + + if( ( g_mcu_app_feature.app_crc[crcNumIndex + 1] != crcValH ) || ( g_mcu_app_feature.app_crc[crcNumIndex] != crcValL ) ) + { + DBG_SYS_Printf("Addr:%x app_crc:%x%x crcVal:%x ",i,g_mcu_app_feature.app_crc[crcNumIndex],g_mcu_app_feature.app_crc[1 + crcNumIndex],crcVal); + Dbg_Print_Buff(DBG_BIT_SYS_STATUS, "MCU Flash:", g_read_buff, crc_data_len); + + if(crc_data_len > 2048) + { + Flash_Read(g_read_buff,2048,i); + Flash_Read(&g_read_buff[2048],(crc_data_len - 2048),i+2048); + }else { + Flash_Read(g_read_buff,crc_data_len,i); + } + Dbg_Print_Buff(DBG_BIT_SYS_STATUS, "SPI Flash:", g_flash_buff, MCU_APP_Flash_PageSize); + + for(uint32_t t_addr = 0;t_addr < crc_data_len;t_addr++ ) + { + if(g_read_buff[t_addr] != g_flash_buff[t_addr]) + { + DBG_SYS_Printf("Different Addr:%x %x - %x",i+t_addr,g_read_buff[t_addr],g_flash_buff[t_addr]); + } + } + + return 0x01; + } + + crcNumIndex += 2; + } + + /*4Уɹ*/ + DBG_SYS_Printf("MCU APP Update Succ!!"); + LOG_Launcher_Read_App_Record(0x00); + + return 0x00; +} + +/******************************************************************************* +* Function Name : SPIFLASH_Read_Update_Recode +* Description : MCU Flash APPд뺯 +* Input : +*******************************************************************************/ +uint8_t SPIFLASH_Read_Update_Recode(UPDATE_RECORD_T *info) +{ + uint16_t read_len = 0; + + memset(g_flash_buff,0,sizeof(g_flash_buff)); + + Flash_Read(g_flash_buff, APP_FEATURE_SIZE, SPIFLASH_UPDATE_RECORD_Addr); + + if(g_flash_buff[EEPROM_Offset_SaveFlag] == EEPROM_SVAE_FLAG) + { + read_len = g_flash_buff[EEPROM_Offset_Datalen + 1]; + read_len <<= 8; + read_len |= g_flash_buff[EEPROM_Offset_Datalen]; + + DBG_SYS_Printf("%s read_len : %d ",__func__,read_len); + if(read_len == UPDATE_RECORD_INFO_Size) + { + if(EEPROM_CheckSum(&g_flash_buff[EEPROM_Offset_Data],read_len) == g_flash_buff[EEPROM_Offset_Check]){ + + memcpy((uint8_t *)info,&g_flash_buff[EEPROM_Offset_Data],read_len); + + DBG_SYS_Printf("spiflash_fw_count:%d",g_mcu_dev.dev_addr); + DBG_SYS_Printf("spiflash_fw_succ:%d",g_mcu_dev.dev_type); + DBG_SYS_Printf("spiflash_fw_fail:%d",g_mcu_dev.dev_boot_ver); + DBG_SYS_Printf("EE DevAppVer:%d",g_mcu_dev.dev_app_ver); + DBG_SYS_Printf("EE DevNameLen:%d",g_mcu_dev.dev_name_len); + DBG_SYS_Printf("EE DevName:%s",g_mcu_dev.dev_name); + return 0x00; //ȡɹ + }else { + DBG_SYS_Printf("%s Check Error !",__func__); + } + }else { + DBG_SYS_Printf("%s Len Error !",__func__); + } + }else{ + DBG_SYS_Printf("%s Flag Error !",__func__); + } + + return 0x01; //ȡʧ +} + +uint8_t SPIFLASH_Write_Update_Recode(UPDATE_RECORD_T *info) +{ + uint16_t save_len = UPDATE_RECORD_INFO_Size; + memset(g_flash_buff,0,sizeof(g_flash_buff)); + + g_flash_buff[EEPROM_Offset_SaveFlag] = EEPROM_SVAE_FLAG; + g_flash_buff[EEPROM_Offset_Datalen] = save_len & 0xFF; + g_flash_buff[EEPROM_Offset_Datalen] = (save_len >> 8) & 0xFF; + + memcpy(&g_flash_buff[EEPROM_Offset_Data],(uint8_t *)info,save_len); + g_flash_buff[3] = EEPROM_CheckSum(&g_flash_buff[4],save_len); + + save_len+=4; + + Flash_Write(g_flash_buff, APP_FEATURE_SIZE, SPIFLASH_UPDATE_RECORD_Addr); + + return 0x00; +} + + + + + + + + + + + + + + + + + + + diff --git a/MCU_Driver/debug.c b/MCU_Driver/debug.c new file mode 100644 index 0000000..c100906 --- /dev/null +++ b/MCU_Driver/debug.c @@ -0,0 +1,368 @@ +/* + * debug.c + * + * Created on: May 14, 2025 + * Author: cc + */ +#include "debug.h" +#include +#include +#include + +volatile uint32_t SysTick_100us = 0; +volatile uint32_t SysTick_1ms = 0; +volatile uint32_t SysTick_1s = 0; + +void Systick_Init(void) +{ + /*жȼ*/ + NVIC_SetPriority(SysTick_IRQn, 0x00); + NVIC_EnableIRQ(SysTick_IRQn); + + /*öʱ*/ + SysTick->CTLR= 0; + SysTick->SR = 0; + SysTick->CNT = 0; + SysTick->CMP = SystemCoreClock/10000; //10001000HZ(Ǿ1msһж) + SysTick->CTLR= 0xf; +} + +void SysTick_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); +void SysTick_Handler(void) +{ + static uint8_t NUM = 0; + static uint16_t NUM_S = 0; + + SysTick->SR = 0; //жϱ־ + + SysTick_100us++; + NUM++; + + if(NUM >= 10){ + NUM = 0; + SysTick_1ms++; + NUM_S++; + + if(NUM_S >= 1000) + { + NUM_S = 0; + SysTick_1s++; + } + } +} + +/********************************************************************* + * @fn Delay_Us + * + * @brief Microsecond Delay Time. + * + * @param n - Microsecond number. + * + * @return None + */ +void Delay_Us(uint32_t n) +{ + for(uint32_t i=0;i _heap_end)) + return NULL - 1; + + curbrk += incr; + return curbrk - incr; +} + + +uint32_t SysTick_Now = 0, SysTick_Last = 0, SysTick_Diff = 0; +char Dbg_Buffer[100]; + +uint32_t Dbg_Switch = (DBG_OPT_ActCond_STATUS << DBG_BIT_ActCond_STATUS_bit) + \ + (DBG_OPT_MQTT_STATUS << DBG_BIT_MQTT_STATUS_bit) + \ + (DBG_OPT_Debug_STATUS << DBG_BIT_Debug_STATUS_bit) + \ + (DBG_OPT_LOGIC_STATUS << DBG_BIT_LOGIC_STATUS_bit) + \ + (DBG_OPT_DEVICE_STATUS << DBG_BIT_DEVICE_STATUS_bit) + \ + (DBG_OPT_NET_STATUS << DBG_BIT_NET_STATUS_bit) + \ + (DBG_OPT_SYS_STATUS << DBG_BIT_SYS_STATUS_bit); + +//÷ʽٴռ䣬 +void __putchar__ (char ch) +{ +#if 1 + +#if (DEBUG) == DEBUG_UART0 + while ((R8_UART0_LSR & RB_LSR_TX_FIFO_EMP) == 0); + R8_UART0_THR = ch; +#elif (DEBUG) == DEBUG_UART1 + while ((R8_UART1_LSR & RB_LSR_TX_FIFO_EMP) == 0); + R8_UART1_THR = ch; +#elif (DEBUG) == DEBUG_UART2 + while ((R8_UART2_LSR & RB_LSR_TX_FIFO_EMP) == 0); + R8_UART2_THR = ch; +#elif (DEBUG) == DEBUG_UART3 + while ((R8_UART3_LSR & RB_LSR_TX_FIFO_EMP) == 0); + R8_UART3_THR = ch; +#endif + +#else + //select debug serial Pane + volatile unsigned int *pdata = (unsigned int *)LDCC_DATA_P; + while (*pdata & LDCC_BIT_STATUS); //Waiting for data read. + *pdata = ch; +#endif +} + +int *myitoa(int value, int* string, int radix) +{ + int tmp[33]; + int* tp = tmp; + int i; + unsigned v; + int sign; + int* sp; + + if (radix > 36 || radix <= 1) + { + return 0; + } + + sign = (radix == 10 && value < 0); + if (sign) + v = -value; + else + v = (unsigned)value; + while (v || tp == tmp) + { + i = v % radix; + v = v / radix; + if (i < 10) { + *tp++ = i+'0'; + + } else { + *tp++ = i + 'a' - 10; + + } + + } + + sp = string; + + if (sign) + *sp++ = '-'; + while (tp > tmp) + *sp++ = *--tp; + *sp = 0; + return string; +} + + +void my_printf(const char *fmt, ...) +{ + const int *s; + int d; + + char ch, *pbuf; + int buf[16]; + va_list ap; + va_start(ap, fmt); + while (*fmt) { + if (*fmt != '%') { + __putchar__(*fmt++); + continue; + } + switch (*++fmt) { + case 's': + s = va_arg(ap, const int *); + for ( ; *s; s++) { + __putchar__(*s); + } + break; + case 'd': + d = va_arg(ap, int); + myitoa(d, buf, 10); + for (s = buf; *s; s++) { + __putchar__(*s); + } + break; + + case 'x': + case 'X': + d = va_arg(ap, int); + myitoa(d, buf, 16); + for (s = buf; *s; s++) { + __putchar__(*s); + } + break; + // Add other specifiers here... + case 'c': + case 'C': + ch = (unsigned char)va_arg(ap, int); + pbuf = &ch; + __putchar__(*pbuf); + break; + default: + __putchar__(*fmt); + break; + } + fmt++; + } + va_end(ap); +} + +void Dbg_Println(int DbgOptBit ,const char *fmt, ...) +{ + + char ch; + + va_list ap; + + if ( (DBG_LOG_EN & DBG_BIT_SYS_STATUS) != 0x00 ) + { + SysTick_Now = SysTick_1ms; + SysTick_Diff = SysTick_Now - SysTick_Last; //һδӡʱ + SysTick_Last = SysTick_Now; + + printf("%8d [%6d]: ",SysTick_Now,SysTick_Diff); + + va_start(ap, fmt); + while (*fmt) { + if (*fmt != '%') { + __putchar__(*fmt++); + continue; + } + switch (*++fmt) { + case 's': + { + char *str = va_arg(ap, char *); + printf("%s",str); + } + break; + case 'd': + { + int num = va_arg(ap, int); + printf("%d", num); + } + break; + + case 'x': + case 'X': + { + int num = va_arg(ap, unsigned int); + printf("%x", num); + } + break; + // Add other specifiers here... + case 'c': + case 'C': + ch = (unsigned char)va_arg(ap, int); + printf("%c", ch); + break; + default: + __putchar__(*fmt); + break; + } + fmt++; + } + va_end(ap); + printf("\r\n"); + } +} + + +/******************************************************************************* +* Function Name : Dbg_Print_Buff +* Description : DEBUGϢ - Buffе +* Input : +* Return : +*******************************************************************************/ +void Dbg_Print_Buff(int DbgOptBit ,const char *cmd ,uint8_t *buff,uint32_t len) +{ +#if DBG_LOG_EN + if ( (Dbg_Switch & DbgOptBit ) != 0x00 ) + { + SysTick_Now = SysTick_1ms; + SysTick_Diff = SysTick_Now - SysTick_Last; //һδӡʱ + SysTick_Last = SysTick_Now; + + printf("%8d [%6d]: %s",SysTick_Now,SysTick_Diff,cmd); + for(uint32_t i=0;i + +/* UART Printf Definition */ +#define DEBUG_UART0 1 +#define DEBUG_UART1 2 +#define DEBUG_UART2 3 +#define DEBUG_UART3 4 + +/* DEBUG log function. DEBUG printf() ض*/ +#ifndef DBG_LOG_EN +#define DBG_LOG_EN 1 //DEBUG LOG ܿ +#endif + +#define DBG_Particular_EN 1 //ϸϢ -- 嵽ļúк +#define DBG_NET_LOG_EN 1 //ģϢ + +/*Ϣʼ״̬*/ +#define DBG_OPT_ActCond_STATUS 1 //ִϢӡ +#define DBG_OPT_MQTT_STATUS 1 //MQTTϢӡ +#define DBG_OPT_Debug_STATUS 1 //ʱϢӡ +#define DBG_OPT_LOGIC_STATUS 1 //߼Ϣӡ +#define DBG_OPT_DEVICE_STATUS 1 //豸ӡϢӡ +#define DBG_OPT_NET_STATUS 1 //Ϣӡ +#define DBG_OPT_SYS_STATUS 1 //ϵͳϢӡ + +/*Ϣλ*/ +#define DBG_BIT_ActCond_STATUS_bit 6 +#define DBG_BIT_MQTT_STATUS_bit 5 +#define DBG_BIT_Debug_STATUS_bit 4 +#define DBG_BIT_LOGIC_STATUS_bit 3 +#define DBG_BIT_DEVICE_STATUS_bit 2 +#define DBG_BIT_NET_STATUS_bit 1 +#define DBG_BIT_SYS_STATUS_bit 0 + +#define DBG_BIT_ActCond_STATUS 0x00000040 +#define DBG_BIT_MQTT_STATUS 0x00000020 +#define DBG_BIT_Debug_STATUS 0x00000010 +#define DBG_BIT_LOGIC_STATUS 0x00000008 +#define DBG_BIT_DEVICE_STATUS 0x00000004 +#define DBG_BIT_NET_STATUS 0x00000002 +#define DBG_BIT_SYS_STATUS 0x00000001 + +extern uint32_t Dbg_Switch; +extern uint32_t SysTick_Now, SysTick_Last, SysTick_Diff; + +void Dbg_Println(int DbgOptBit ,const char *fmt, ...); + +#if DBG_LOG_EN + +#define DBG_Printf(...) printf(__VA_ARGS__) + +#define DBG_SYS_Printf(...) Dbg_Println(DBG_BIT_SYS_STATUS,__VA_ARGS__) + +//#define DBG_SYS_Printf(...) { \ +// if(Dbg_Switch & DBG_BIT_SYS_STATUS){ \ +// SysTick_Now = SysTick_1ms; \ +// SysTick_Diff = SysTick_Now - SysTick_Last; \ +// SysTick_Last = SysTick_Now; \ +// printf("%8d [%6d]:",SysTick_Now,SysTick_Diff); \ +// printf(__VA_ARGS__);printf("\r\n");}} + +#define DBG_Debug_Printf(...) { \ + if(Dbg_Switch & DBG_BIT_Debug_STATUS){ \ + SysTick_Now = SysTick_1ms; \ + SysTick_Diff = SysTick_Now - SysTick_Last; \ + SysTick_Last = SysTick_Now; \ + printf("%8d [%6d]:",SysTick_Now,SysTick_Diff); \ + printf(__VA_ARGS__);printf("\r\n");}} + +#define DBG_log(...) {DBG_Printf("%s %s-%d :",__FILE__,__func__,__LINE__);DBG_Printf(__VA_ARGS__);} + +#else + +#define DBG_Printf(...) +#define DBG_SYS_Printf(...) +#define DBG_Debug_Printf(...) + +#define DBG_log(...) + + + +#endif + + +extern volatile uint32_t SysTick_100us; +extern volatile uint32_t SysTick_1ms; +extern volatile uint32_t SysTick_1s; + +void Systick_Init(void); +void Delay_Us(uint32_t n); +void Delay_Ms(uint32_t n); + +void my_printf(const char *fmt, ...); +void Dbg_Print_Buff(int DbgOptBit ,const char *cmd ,uint8_t *buff,uint32_t len); + +#endif /* MCU_DRIVER_DEBUG_H_ */ diff --git a/MCU_Driver/inc/flash_mem_addr.h b/MCU_Driver/inc/flash_mem_addr.h new file mode 100644 index 0000000..738a2ec --- /dev/null +++ b/MCU_Driver/inc/flash_mem_addr.h @@ -0,0 +1,34 @@ +/* + * flash_mem_addr.h + * Description : ļΪⲿFlash ַӳ Size: 0x00200000 + * + * Created on: Jul 31, 2025 + * Author: cc + */ + +#ifndef _FLASH_MEM_ADDR_H_ +#define _FLASH_MEM_ADDR_H_ + +/*APPݼ*/ +#define SPIFLASH_APP_Start_Addr 0x00000000 + +#define SPIFLASH_APP_FEATURE_Addr 0x00000000 // - 512Byte + + +#define SPIFLASH_UPDATE_RECORD_Addr 0x00000200 //дͳƱַ - 512Byte + +#define SPIFLASH_APP_Data_Start_Addr 0x00004000 +#define SPIFLASH_APP_Data_End_Addr 0x0006FFFF + +#define SPIFLASH_APP_End_Addr 0x0006FFFF + +/*ļ*/ +#define SPIFLASH_LOGIC_FILE_Start_Addr 0x00070000 +#define SPIFLASH_LOGIC_DataFlag_ADDRESS 0x00070000 //ļ־λ - 4Byte +#define SPIFLASH_LOGIC_DataSize_ADDRESS 0x00070004 //ļ - 4Byte +#define SPIFLASH_LOGIC_DataMD5_ADDRESS 0x00070008 //ļMD5Уֵ - 16Byte +#define SPIFLASH_LOGIC_DataStart_ADDRESS 0x00070200 //ļʼַ +#define SPIFLASH_LOGIC_FILE_End_Addr 0x000FFFFF + + +#endif /* MCU_DRIVER_INC_FLASH_MEM_ADDR_H_ */ diff --git a/MCU_Driver/inc/led.h b/MCU_Driver/inc/led.h new file mode 100644 index 0000000..e960935 --- /dev/null +++ b/MCU_Driver/inc/led.h @@ -0,0 +1,20 @@ +/* + * led.h + * + * Created on: May 15, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_LED_H_ +#define MCU_DRIVER_INC_LED_H_ + +#include "ch564.h" + +#define SYS_LED_ON GPIOB_ResetBits(GPIO_Pin_12) +#define SYS_LED_OFF GPIOA_SetBits(GPIO_Pin_12) +#define SYS_LED_FLIP GPIOA_InverseBits(GPIO_Pin_12) + +void SYS_LED_Init(void); +void SYS_LED_Task(void); + +#endif /* MCU_DRIVER_INC_LED_H_ */ diff --git a/MCU_Driver/inc/log_api.h b/MCU_Driver/inc/log_api.h new file mode 100644 index 0000000..6c6b5d1 --- /dev/null +++ b/MCU_Driver/inc/log_api.h @@ -0,0 +1,86 @@ +/* + * log_api.h + * + * Created on: Jul 29, 2025 + * Author: cc + */ + +#ifndef _LOG_API_H_ +#define _LOG_API_H_ + +#include "ch564.h" +#include + +#define LogType_Enable 1 //LOGʹ + +/*־洢Ͷ*/ +#define LogType_Launcher 0x01 //LauncherϢ¼ +#define LogType_SYS_Record 0x02 //ϵͳϢ¼ +#define LogType_Device_COMM 0x03 //豸ͨѶ¼ +#define LogType_Device_Online 0x04 //豸ͨѶ״̬¼ +#define LogType_Global_Parameters 0x05 //豸״̬ڼ¼ +#define LogType_Net_COMM 0x06 //ͨѶ¼ +#define LogType_Logic_Record 0x07 //߼¼ + +/*־洢 - ʼ״̬*/ +#define LogType_Launcher_SWITCH 1 +#define LogType_SYS_Record_SWITCH 1 +#define LogType_Device_COMM_SWITCH 1 +#define LogType_Device_Online_SWITCH 1 +#define LogType_Global_Parameters_SWITCH 1 +#define LogType_Net_COMM_SWITCH 1 +#define LogType_Logic_Record_SWITCH 1 + +/*־洢λ*/ +#define LogType_Launcher_bit 0 +#define LogType_SYS_Record_bit 1 +#define LogType_Device_COMM_bit 2 +#define LogType_Device_Online_bit 3 +#define LogType_Global_Parameters_bit 4 +#define LogType_Net_COMM_bit 5 +#define LogType_Logic_Record_bit 6 + +/*־ز*/ +#define LogInfo_Device_Online 0x01 //豸 +#define LogInfo_Device_Offline 0x02 //豸 + +typedef enum{ + LLauncher_App_Check = 0x01, //УAPP + LLauncher_Read_App, //ȡAPPAPPд뵽MCU FLash + LLauncher_Write_Flash, //дFlash + LLauncher_Factory_Reset, //ָ + LLauncher_Reset_Source, //λԴ + LLauncher_RCUKey_State, //RCU¼¼ +}LOGTYPE_Launcher_E; + +typedef enum { + LSYS_PHY_Change = 0x01, //PHY״̬仯¼ + LSYS_DevInfo_Error, //豸Ϣ + LSYS_API_State, //״̬ + LSYS_NET_ARGC, //ʼ + LSYS_MQTT_ARGC, //MQTT + LSYS_Server_Comm_State, //ƶͨѶ״̬¼ + LSYS_NET_DefaultARGC, //Ĭϲ + LSYS_RCUKey_State, //RCU¼¼ +}LOGTYPR_SYSRecord; + +typedef enum{ + LCOMM_ASK_TO_Reply = 0x01, //ѯظ + LCOMM_Send_Control, //RCU· + LCOMM_Control_Reply, //RCUƻظ + LCOMM_Adjust_Baud, //豸 +}LOGTYPE_DEV_COMM; + +typedef enum{ + LGlobal_Para = 0x01, // + LGlobal_Dev, //豸 +}LOGTYPE_Global_E; + +void LOG_Launcher_APP_Check_Record(uint8_t state); +void LOG_Launcher_Read_App_Record(uint8_t state); +void LOG_Launcher_Write_Flash_Record(uint32_t addr,uint16_t len); +void LOG_Launcher_Factory_Reset_Record(uint8_t state); +void LOG_Launcher_Reset_Source_Record(uint8_t sour); +void LOG_Launcher_RCU_Key_State_Record(uint8_t state); + +#endif /* MCU_DRIVER_INC_LOG_API_H_ */ diff --git a/MCU_Driver/inc/mcu_flash.h b/MCU_Driver/inc/mcu_flash.h new file mode 100644 index 0000000..7295c45 --- /dev/null +++ b/MCU_Driver/inc/mcu_flash.h @@ -0,0 +1,123 @@ +/* + * mcu_flash.h + * + * Created on: Aug 2, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_MCU_FLASH_H_ +#define MCU_DRIVER_INC_MCU_FLASH_H_ + +#include "ch564.h" +#include + + +#define MCU_APP_Flash_PageSize 0x00001000 //MCU FlashҳΪ4096Byte +#define APP_Flash_WriteNum 0x05 //APPд + +#define App_Procedure_Ready 0x66 //APP׼־λ +#define App_Procedure_Not_Ready 0x44 //Appδ׼־λ + +//MCU Flash Address range(0x0 -- 0x6FFFF) Size(448K) +#define MCU_APP_Flash_Start_Addr 0x00007000 //MCU FlashAPPʼַ +#define MCU_APP_Data_Start_Addr 0x00007000 //MCU Flash APPʼַ +#define MCU_APP_Data_End_Addr 0x00027DFF //MCU Flash APPݽַ +#define MCU_APP_Feature_Addr 0x00027E00 //MCU Flash ݱַ +#define MCU_APP_Flash_End_Addr 0x00027FFF //MCU FlashAPPĽַ + +#define MCU_APP_Feature_PageAddr 0x00027000 //MCU APP ҳĵַ +#define MCU_APP_Feature_PageOffset 0x00000E00 //MCU APPҳƫ +#define APP_FEATURE_SIZE 0x0200 //512Byte + +//EEPROM Address range(0x70000 -- 0x77FFF) Size(32K) +#define MCU_EEPROM_Start_Addr 0x00070000 +#define MCU_EEPROM_MCUDevInfo_Address 0x00070000 //MCU 豸Ϣ̶ַΪ0x00070000СΪ4096 򲻿ɸĶ +#define MCU_EEPROM_End_Addr 0x00078000 + + + +/* EEPROM ݸʽ + * FLAG - 1Byte ־λ + * LEN - 2Byte ݳ + * CHECK - 1Byte У + * DATA - nByte + * + * */ +#define EEPROM_SVAE_FLAG 0xAE +#define EEPROM_DATA_Size_Max 0x40 //ĿǰΪ100Byte +#define EEPROM_PARA_Size 50 +#define EEPROM_DEV_NAME_Size 32 + +#define EEPROM_Offset_SaveFlag 0x00 +#define EEPROM_Offset_Datalen 0x01 +#define EEPROM_Offset_Check 0x03 +#define EEPROM_Offset_Data 0x04 + + +/* ݽṹ + * ע⣺risc-vûֽڶ + * ԱFlash/MCU Flashе˳ṹ嶨˳һ£ʹʱע + * */ +typedef enum{ + Feature_Check = 0x00, // 512Byte CRCУ - 2Byte + Feature_AppFlag = 0x02, // - APP־λ - 1Byte + Feature_AppStart = 0x03, // - APPʼַ - 4Byte + Feature_AppEnd = 0x07, // - APPַ - 4Byte + Feature_AppCrcSize = 0x0B, // - APP CRCij - 2Byte + Feature_AppCrcLen = 0x0D, // - APP CRCУݴС - 2Byte + Feature_AppFlashCrc = 0x0F, // - APP CRC +}FEATURE_E; + +#define APP_Feature_CRC_Size 497 + +typedef struct{ + uint8_t app_flag; //APP ־λ + uint8_t app_crc[APP_Feature_CRC_Size]; //APP CRCУֵ + + uint16_t app_crc_size; //APP CRCУݴС + uint16_t app_crc_len; //APP CRCУݳ + uint16_t crc_check; //CRCֵ - УǷϷ + + uint32_t app_start_addr; //APPʼַ + uint32_t app_end_addr; //APPַ +}G_SYS_FEATURE_T; + +/*ϢMCU EEPROM*/ +typedef struct{ + + uint8_t dev_addr; //豸ַ + uint8_t dev_type; //豸 + uint8_t dev_boot_ver; //豸Boot汾 + uint8_t dev_app_ver; //豸APP汾 + uint8_t dev_name_len; //豸Ƶij + uint8_t dev_name[EEPROM_DEV_NAME_Size]; //豸 + +}E_MCU_DEV_INFO; + + + +extern E_MCU_DEV_INFO g_mcu_dev; +extern uint8_t g_read_buff[4100]; +extern uint8_t g_flash_buff[4100]; + +void EEPROM_Init(void); +uint8_t MCU_APP_Flash_Write(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr); +uint8_t MCU_APP_Flash_Read(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t readAddr); +uint8_t MCU_APP_Flash_Erase(uint32_t readAddr,uint16_t NumByteToWrite); +uint8_t MCU_APP_Flash_ALLErase(void); +uint8_t MCU_EEPROM_Write(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr); +uint8_t MCU_EEPROM_Read(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t readAddr); +uint8_t MCU_EEPROM_Erase(uint32_t readAddr,uint16_t NumByteToWrite); +uint8_t MCU_EEPROM_ALLErase(void); + +uint8_t EEPROM_CheckSum(uint8_t *data,uint16_t len); +uint8_t EEPROM_ReadMCUDevInfo(E_MCU_DEV_INFO *info); +uint8_t EEPROM_WriteMCUDevInfo(E_MCU_DEV_INFO *info); +void EEPROM_Default_MCUDevInfo(E_MCU_DEV_INFO *info); +void EEPROM_Validate_MCUDevInfo(E_MCU_DEV_INFO *info); + +uint8_t Read_APP_Feature_Info(uint8_t option,G_SYS_FEATURE_T *feature_info); +uint8_t Write_APP_Feature_Info(uint8_t option,G_SYS_FEATURE_T *feature_info); +void APP_Feature_Info_Printf(G_SYS_FEATURE_T *feature_info); + +#endif /* MCU_DRIVER_INC_MCU_FLASH_H_ */ diff --git a/MCU_Driver/inc/rtc.h b/MCU_Driver/inc/rtc.h new file mode 100644 index 0000000..7e1bec2 --- /dev/null +++ b/MCU_Driver/inc/rtc.h @@ -0,0 +1,42 @@ +/* + * rtc.h + * + * Created on: Jul 29, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_RTC_H_ +#define MCU_DRIVER_INC_RTC_H_ + +#include +#include "ch564.h" + +typedef struct{ + uint8_t second; + uint8_t minute; + uint8_t hour; + uint8_t week; + uint8_t day; + uint8_t month; + uint8_t year; +}S_RTC; + +typedef struct{ + uint32_t hour; + uint16_t minute; + uint16_t second; +}G_CORE_RTC; + +extern S_RTC RTC_Raw_Data; +extern uint32_t Log_Time_ms; + +void RTC_Init(void); +uint8_t HEX_Conversion_To_DEC(uint8_t c_num); +uint8_t DEV_Conversion_To_HEX(uint8_t c_num); +uint32_t RTC_Conversion_To_Unix(S_RTC *rtc_time); +void Unix_Conversion_To_RTC(S_RTC *rtc_time,uint32_t utc_tick); +uint8_t RTC_ReadDate(S_RTC *psRTC); +uint8_t RTC_WriteDate(S_RTC SetRTC); +void RTC_TASK(void); + +#endif /* MCU_DRIVER_INC_RTC_H_ */ diff --git a/MCU_Driver/inc/rw_logging.h b/MCU_Driver/inc/rw_logging.h new file mode 100644 index 0000000..78f90f9 --- /dev/null +++ b/MCU_Driver/inc/rw_logging.h @@ -0,0 +1,41 @@ +/* + * rw_logging.h + * + * Created on: Jul 29, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_RW_LOGGING_H_ +#define MCU_DRIVER_INC_RW_LOGGING_H_ + +#include "ch564.h" +#include + +#define APPFlag_UartUpgrade_Reset 0xBBC1 //APP־λ + +//־ض +#define LOG_Data_Hand 0xA5 //LOGͷ +#define Log_Data_End 0x5A //LOGβ +#define Log_Data_Len_MAX 512 //־512Byte + +/*־ݸʽ*/ +typedef enum{ + S_Log_Hand, + S_Log_SN, //־ÿк + S_Log_Len, + S_Log_Len_8, + S_Log_Check, + S_Log_Date_H, //꣺5bit £5bit գ5bit + S_Log_Date_L, + S_Log_Type, + S_Log_Time8B, //Сʱʱ + S_Log_Time16B, + S_Log_Time24B, + S_Log_Time32B, + S_Log_Data, +}Sram_Log_Data_Format; + +uint8_t Data_CheckSum(uint8_t* data,uint16_t len); +uint8_t Log_write_sram(uint8_t data_type,uint8_t *buff,uint16_t len); + +#endif /* MCU_DRIVER_INC_RW_LOGGING_H_ */ diff --git a/MCU_Driver/inc/spi_flash.h b/MCU_Driver/inc/spi_flash.h new file mode 100644 index 0000000..b52b2cc --- /dev/null +++ b/MCU_Driver/inc/spi_flash.h @@ -0,0 +1,65 @@ +/* + * spi_flash.h + * + * Created on: May 20, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_SPI_FLASH_H_ +#define MCU_DRIVER_INC_SPI_FLASH_H_ + +#include "ch564.h" + +#define Flash_CS_H GPIOA_SetBits(GPIO_Pin_11) +#define Flash_CS_L GPIOA_ResetBits(GPIO_Pin_11) + +#define Flash_ADDRESS_MAX 0x00200000 + +/***********ָ**********/ +//Read +#define P24Q40H_ReadData 0x03 +#define P24Q40H_FastReadData 0x0B +#define P24Q40H_FastReadDual 0x3B +//Program and Erase +#define P24Q40H_PageErase 0x81 +#define P24Q40H_SectorErase 0x20 +#define P24Q40H_BlockErase 0xD8 +#define P24Q40H_ChipErase 0xC7 +#define P24Q40H_PageProgram 0x02 +//Protection +#define P24Q40H_WriteEnable 0x06 +#define P24Q40H_WriteDisable 0x04 +//Status Register +#define P24Q40H_ReadStatusReg 0x05 +#define P24Q40H_WriteStatusReg 0x01 +//Other Commands +#define P24Q40H_PowerDown 0xB9 +#define P24Q40H_ReleasePowerDown 0xAB +#define P24Q40H_ReadManufactureID 0x90 +#define P24Q40H_ReadDeviceID 0x9F +#define P24Q40H_ResetEnable 0x66 +#define P24Q40H_Reset 0x99 + +extern uint8_t Flash_Buffer[4150]; + +void SPI_FLASH_Init(void); +uint8_t Flash_ReadSR(void); +void Flash_WriteSR(uint8_t sr_val); +void Flash_Write_Enable(void); +void Flash_Write_Disable(void); +uint16_t Flash_ReadID(void); +uint8_t Flash_Wait_Busy(void); +void Flash_PowerDown(void); +void Flash_Wakeup(void); +void Flash_Erase_Chip(void); +void Flash_Erase_Block(uint32_t BLK_ID); +void Flash_Erase_Sector(uint32_t DST_ID); +void Flash_Erase_Page(uint32_t Page_ID); +void Flash_Erase_Pageaddr(uint32_t Page_addr); +void Flash_Read(uint8_t* pBuffer,uint16_t NumByteToRead,uint32_t ReadAddr); +void Flash_Write_Page(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr); +void Flash_Write_NoCheck(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr); +void Flash_Write(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t WriteAddr); + + +#endif /* MCU_DRIVER_INC_SPI_FLASH_H_ */ diff --git a/MCU_Driver/inc/spi_sram.h b/MCU_Driver/inc/spi_sram.h new file mode 100644 index 0000000..498b45d --- /dev/null +++ b/MCU_Driver/inc/spi_sram.h @@ -0,0 +1,46 @@ +/* + * spi_sram.h + * + * Created on: May 16, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_SPI_SRAM_H_ +#define MCU_DRIVER_INC_SPI_SRAM_H_ + +#include "ch564.h" + +#define SRAM_CE_H GPIOA_ResetBits(GPIO_Pin_11) +#define SRAM_CE_L GPIOA_SetBits(GPIO_Pin_11) + +#define SRAM_CMD_Read 0x03 +#define SRAM_CMD_Fast_Read 0x0B +#define SRAM_CMD_Fast_Read_Quad 0xEB +#define SRAM_CMD_Write 0x02 +#define SRAM_CMD_Quad_Write 0x38 +#define SRAM_CMD_Enter_Quad_Mode 0x35 +#define SRAM_CMD_Exit_Quad_Mode 0xF5 +#define SRAM_CMD_Reset_Enable 0x66 +#define SRAM_CMD_Reset 0x99 +#define SRAM_CMD_Wrap_Boundary_Toggle 0xC0 +#define SRAM_CMD_Read_ID 0x9F + +#define SRAM_ADDRESS_MAX 0x00800000 + + +void SPI_SRAM_Init(void); +void SRAM_Write_Byte(uint8_t wdate,uint32_t add); +uint8_t SRAM_Read_Byte(uint32_t add); +void SRAM_Write_Word(uint16_t wdate,uint32_t add); +uint16_t SRAM_Read_Word(uint32_t add); +void SRAM_Write_DW(uint32_t wdate,uint32_t add); +uint32_t SRAM_Read_DW(uint32_t add); +uint8_t SRAM_Read_ID_Opeartion(void); +void SRAM_Reset_Operation(void); + +void SRAM_DMA_Write_Buff(uint8_t* wbuff,uint16_t len,uint32_t add); +void SRAM_DMA_Read_Buff(uint8_t* rbuff,uint16_t len,uint32_t add); + + + +#endif /* MCU_DRIVER_INC_SPI_SRAM_H_ */ diff --git a/MCU_Driver/inc/sram_mem_addr.h b/MCU_Driver/inc/sram_mem_addr.h new file mode 100644 index 0000000..86ba60c --- /dev/null +++ b/MCU_Driver/inc/sram_mem_addr.h @@ -0,0 +1,33 @@ +/* + * sram_virt_mem_addr.h + * ⲿSRAMַռ滮 0x00000000 ~ 0x00800000 + * + * Created on: Jul 29, 2025 + * Author: cc + */ + +#ifndef _SRAM_MEM_ADDR_H_ +#define _SRAM_MEM_ADDR_H_ + + +/* + * 2025-07-29 ޸SRAM洢ַ 0x00400000 ~ 0x007FFFFF SIZE:4MByte + * 1޸ĶԿռַУ飬ֹ쳣 + * 2־ȥûʹõı + * + * */ +#define SRAM_LOG_WRITE_Address 0x00400000 //־ռʼַ - ǰSRAM־ݵдַ - 4Byte +#define SRAM_LOG_READ_Address 0x00400004 //־ϱȡַ - 4Byte +#define SRAM_LOG_Serial_Number 0x00400008 //־űַ - 2Byte Ŀǰֻʹ1Byte +#define SRAM_LOGFlag_Reset_Source 0x0040000A //LauncherԴ - APPʹ - 1Byte +#define SRAM_LOGFlag_Addr_INIT 0x0040000B //Launcher¼ַʼ־λ - APPʹ - 1Byte +#define SRAM_LOGFlag_Debug_Switch 0x0040000C //LauncherϢ 4Byte - APPʹ +#define SRAM_APPFlag_Reset_Source 0x00400010 //App־λ 2Byte - LauncherϢʹ 0xBBC1 +#define SRAM_LOG_DATA_Address 0x00400100 //־ݵַ +#define SRAM_LOG_End_Address 0x007FFFFF //־ռַ - 0x007FFFFF + + + + + +#endif /* MCU_DRIVER_INC_SRAM_MEM_ADDR_H_ */ diff --git a/MCU_Driver/inc/timer.h b/MCU_Driver/inc/timer.h new file mode 100644 index 0000000..164b6a0 --- /dev/null +++ b/MCU_Driver/inc/timer.h @@ -0,0 +1,20 @@ +/* + * timer.h + * + * Created on: May 16, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_TIMER_H_ +#define MCU_DRIVER_INC_TIMER_H_ + +#include "ch564.h" + + +extern volatile uint32_t Time0_100us; +extern volatile uint32_t Time0_1ms; + +void TIMER0_Init(void); +void Timer0_Task(void); + +#endif /* MCU_DRIVER_INC_TIMER_H_ */ diff --git a/MCU_Driver/inc/uart.h b/MCU_Driver/inc/uart.h new file mode 100644 index 0000000..22ea328 --- /dev/null +++ b/MCU_Driver/inc/uart.h @@ -0,0 +1,100 @@ +/* + * uart.h + * + * Created on: May 14, 2025 + * Author: cc + */ + +#ifndef MCU_DRIVER_INC_UART_H_ +#define MCU_DRIVER_INC_UART_H_ + +#include "ch564.h" + + +#define MCU485_EN1_H GPIOD_SetBits(GPIO_Pin_21) +#define MCU485_EN1_L GPIOD_ResetBits(GPIO_Pin_21) +#define MCU485_EN2_H GPIOB_SetBits(GPIO_Pin_15) +#define MCU485_EN2_L GPIOB_ResetBits(GPIO_Pin_15) + +#define UART_COMMBUSY_IDLE_Flag 0x00 +#define UART_COMMBUSY_RECV_Flag 0x01 +#define UART_COMMBUSY_SEND_Flag 0x02 + +#define Recv_2400_TimeOut 10 //ms +#define Recv_9600_TimeOut 5 //ms +#define Recv_115200_TimeOut 3 //ms +#define Recv_512000_TimeOut 3 //ms + +#define USART_BUFFER_SIZE 512 + + +typedef void (*Uart_prt)(uint8_t * ,uint16_t ); +typedef uint8_t (*Uart_set_prt)(uint32_t ); + +typedef enum +{ + UART_0, + UART_1, + UART_2, + UART_3, + UART_MAX, +}UART_IDX; + +typedef struct{ + + uint8_t RecvBuffer[USART_BUFFER_SIZE]; + uint8_t deal_buff[USART_BUFFER_SIZE]; + uint8_t ackBuffer[USART_BUFFER_SIZE]; + uint8_t SendBuffer[USART_BUFFER_SIZE]; + + uint8_t SendCount; //ܷʹ + uint8_t SendCnt; //ǰʹ + uint8_t CommBusy; //ͨѶæ״̬ + + uint8_t Receiving; + uint8_t sn; + uint8_t pc_addr; + uint8_t cmd; + + uint8_t appFlag; + uint8_t writeFlag; + uint8_t ChangeBaudFlag; //лʱ־λ + + uint16_t RecvLen; + uint16_t deal_len; + uint16_t ackLen; + uint16_t SendLen; //ͳ + + uint32_t CommBaud; //ͨѶ - лʱʹ + uint32_t ackValidity; //ݵЧ + uint32_t SendValidDuration; //Чʱ + uint32_t SendValidTick; //Чʱ + uint32_t SendInterval; //ͼ + uint32_t SendTick; //ʱ + + uint32_t RecvTimeout; + uint32_t RecvIdleTiming; + uint32_t SendIdleTick; //ȴʱ + + Uart_prt send_data_cf; + Uart_set_prt set_baud_cf; +}UART_t; + +extern UART_t g_uart[UART_MAX]; + +void UARTx_Init(UART_IDX uart_id, uint32_t buad); +void Set_Uart_recvTimeout(UART_t *set_uart,uint32_t baud); + +void UART0_RECEIVE(void); +void UART1_RECEIVE(void); +void UART2_RECEIVE(void); +void UART3_RECEIVE(void); + +uint8_t UART0_ChangeBaud(uint32_t baudrate); +uint8_t UART1_ChangeBaud(uint32_t baudrate); +uint8_t UART2_ChangeBaud(uint32_t baudrate); +uint8_t UART3_ChangeBaud(uint32_t baudrate); + +void Uart0_Task(void); + +#endif /* MCU_DRIVER_INC_UART_H_ */ diff --git a/MCU_Driver/led.c b/MCU_Driver/led.c new file mode 100644 index 0000000..83e1109 --- /dev/null +++ b/MCU_Driver/led.c @@ -0,0 +1,33 @@ +/* + * led.c + * + * Created on: 2025515 + * Author: cc + */ + +#include "led.h" +#include "debug.h" +#include +#include + +void SYS_LED_Init(void) +{ + GPIOA_ModeCfg(GPIO_Pin_12,GPIO_ModeOut_PP); //LED + + SYS_LED_ON; +} + +void SYS_LED_Task(void) +{ + static uint32_t led_tick = 0; + + if(SysTick_1ms - led_tick >= 1000 ){ + led_tick = SysTick_1ms; + + SYS_LED_FLIP; + } +} + + + + diff --git a/MCU_Driver/log_api.c b/MCU_Driver/log_api.c new file mode 100644 index 0000000..397280c --- /dev/null +++ b/MCU_Driver/log_api.c @@ -0,0 +1,175 @@ +/* + * log_api.c + * + * Created on: Jul 29, 2025 + * Author: cc + */ + +#include "rw_logging.h" +#include "SPI_SRAM.h" +#include "Log_api.h" +#include "string.h" + +uint32_t SYS_Log_Switch = (LogType_Launcher_SWITCH << LogType_Launcher_bit) + \ + (LogType_SYS_Record_SWITCH << LogType_SYS_Record_bit) + \ + (LogType_Device_COMM_SWITCH << LogType_Device_COMM_bit) + \ + (LogType_Device_Online_SWITCH << LogType_Device_Online_bit) + \ + (LogType_Global_Parameters_SWITCH << LogType_Global_Parameters_bit) + \ + (LogType_Net_COMM_SWITCH << LogType_Net_COMM_bit) + \ + (LogType_Logic_Record_SWITCH << LogType_Logic_Record_bit); + + +/******************************************************************************* +* Function Name : LOG_Launcher_APP_Check_Record +* Description : Launcher - УAPP +* Input : + state :״̬ + 0x00:ͬ + 0x01:汾Ųͬ + 0x02:CRCУ鲻ͬ + 0x03:FlashAPPַ + 0x04:Flash APPУ + 0x05:FlashAPP־δλ + 0x06:Flash CRCУ + 0x07:MCU FlashУ + 0x08:MCU FlashAPP־δλ + 0x09:MCU FlashCRCУ +* Return : None +*******************************************************************************/ +void LOG_Launcher_APP_Check_Record(uint8_t state) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[3] = {0}; + + temp_buff[0] = LLauncher_App_Check; + temp_buff[1] = state; + + Log_write_sram(LogType_Launcher,temp_buff,2); + } +} + +/******************************************************************************* +* Function Name : LOG_Launcher_APP_Check_Record +* Description : Launcher - УAPP +* Input : + state :״̬ + 0x00:ɹ + 0x01:ʧ +* Return : None +*******************************************************************************/ +void LOG_Launcher_Read_App_Record(uint8_t state) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[3] = {0}; + + temp_buff[0] = LLauncher_Read_App; + temp_buff[1] = state; + + Log_write_sram(LogType_Launcher,temp_buff,2); + } +} + +/******************************************************************************* +* Function Name : LOG_Launcher_Write_Flash_Record +* Description : Launcher - Flashд +* Input : + addr :дַ + len :д볤 +* Return : None +*******************************************************************************/ +void LOG_Launcher_Write_Flash_Record(uint32_t addr,uint16_t len) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[7] = {0}; + + temp_buff[0] = LLauncher_Write_Flash; + temp_buff[1] = addr & 0xFF; + temp_buff[2] = (addr >> 8) & 0xFF; + temp_buff[3] = (addr >> 16) & 0xFF; + temp_buff[4] = (addr >> 24) & 0xFF; + temp_buff[5] = len & 0xFF; + temp_buff[6] = (len >> 8) & 0xFF; + + Log_write_sram(LogType_Launcher,temp_buff,7); + } +} + +/******************************************************************************* +* Function Name : LOG_Launcher_Factory_Reset_Record +* Description : Launcher - ָ +* Input : + state + 0x01:дɹ + 0x02:дʧ - ûг + 0x03:дʧ - дʧ +* Return : None +*******************************************************************************/ +void LOG_Launcher_Factory_Reset_Record(uint8_t state) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[3] = {0}; + + temp_buff[0] = LLauncher_Factory_Reset; + temp_buff[1] = state; + + Log_write_sram(LogType_Launcher,temp_buff,2); + } +} + +/******************************************************************************* +* Function Name : LOG_Launcher_Factory_Reset_Record +* Description : Launcher - λԴ +* Input : + sourλźֵ + 0x00λ + 0x01ϵ縴λ + 0x02Źλ + 0x03ⲿֶλ + 0x05µģʽʱĸλ - ͨWCHISPTool¼ĸλ +* Return : None +*******************************************************************************/ +void LOG_Launcher_Reset_Source_Record(uint8_t sour) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[3] = {0}; + + temp_buff[0] = LLauncher_Reset_Source; + temp_buff[1] = sour; + + Log_write_sram(LogType_Launcher,temp_buff,2); + } +} + +/******************************************************************************* +* Function Name : LOG_Launcher_Factory_Reset_Record +* Description : Launcher - RCUذ +* Input : + state״̬ + 0x01㰴 + 0x02 + 0x03ɿ + 0x04ﵽָ״̬ +* Return : None +*******************************************************************************/ +void LOG_Launcher_RCU_Key_State_Record(uint8_t state) +{ + if(LogType_Enable && (SYS_Log_Switch & (1 << LogType_Launcher_bit )) ) + { + uint8_t temp_buff[3] = {0}; + + temp_buff[0] = LLauncher_RCUKey_State; + temp_buff[1] = state; + + Log_write_sram(LogType_Launcher,temp_buff,2); + } +} + + + + + diff --git a/MCU_Driver/mcu_flash.c b/MCU_Driver/mcu_flash.c new file mode 100644 index 0000000..455b484 --- /dev/null +++ b/MCU_Driver/mcu_flash.c @@ -0,0 +1,638 @@ +/* + * mcu_flash.c + * + * Created on: Aug 2, 2025 + * Author: cc + */ +#include "includes.h" +#include + +E_MCU_DEV_INFO g_mcu_dev; + +uint8_t g_read_buff[4100] = {0}; +uint8_t g_flash_buff[4100] = {0}; + +/******************************************************************************* +* Function Name : EEPROM_Init +* Description : EEPROM ʼ +*******************************************************************************/ +void EEPROM_Init(void) +{ + uint8_t rev = 0; + + rev = EEPROM_ReadMCUDevInfo(&g_mcu_dev); + if(rev == 0x00){ + //ȡɹʼУ² + EEPROM_Validate_MCUDevInfo(&g_mcu_dev); + }else{ + //ȡʧܣָĬϲ + DBG_SYS_Printf("EE Use Defalut Para"); + EEPROM_Default_MCUDevInfo(&g_mcu_dev); + + //DBG_SYS_Printf("EE Use Defalut Para"); + DBG_SYS_Printf("EE DevBootVer:%d",g_mcu_dev.dev_boot_ver); + DBG_SYS_Printf("EE DevNameLen:%d",g_mcu_dev.dev_name_len); + DBG_SYS_Printf("EE DevName:%s",g_mcu_dev.dev_name); + } + + //EEPROM_Default_MCUDevInfo(&g_mcu_dev); +} + +/******************************************************************************* +* Function Name : MCU_Flash_Write +* Description : MCU Flashд뺯 +* Input : + pBufferд + NumByteToWriteдݳ -- д볤ȱΪ4ı + writeAddrдַ 0x00004000 ~ 0x0006FFFF 432KB +*******************************************************************************/ +uint8_t MCU_APP_Flash_Write(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr) +{ + FLASH_Status sta; + + /* УдַͳǷ - дַǷAPP FlashΧԼд볤Ƿ4Byte*/ + if( ( writeAddr < MCU_APP_Flash_Start_Addr ) || ( ( writeAddr + NumByteToWrite ) > MCU_EEPROM_Start_Addr ) || ((NumByteToWrite % 4) != 0x00) ) { + DBG_SYS_Printf("MCU APP Flash Addr Error:%x - %x\r\n", writeAddr, NumByteToWrite); + return 0x01; + } + + FLASH_Unlock(); + sta = FLASH_ROMA_WRITE(writeAddr, pBuffer, NumByteToWrite); + FLASH_Lock(); + if (sta != FLASH_COMPLETE){ + DBG_SYS_Printf("Operation FLASH_ROMA_WRITE failed %#x!! Err Code %x\r\n", writeAddr, sta); + return 0x01; + } + + sta = FLASH_ROMA_VERIFY(writeAddr, pBuffer, NumByteToWrite); + if (sta != FLASH_COMPLETE){ + DBG_SYS_Printf("Operation FLASH_ROMA_VERIFY failed %#x!! Err Code %x\r\n", writeAddr, sta); + return 0x01; + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : MCU_Flash_Read +* Description : MCU Flashݶȡ +* Input : + pBufferд + NumByteToWriteдݳ -- д볤ȱΪ4ı + readAddrȡַ 0x00004000 ~ 0x0006FFFF 432KB +*******************************************************************************/ +uint8_t MCU_APP_Flash_Read(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t readAddr) +{ + FLASH_Status sta; + + /* УȡַͳǷ - ȡַǷAPP FlashΧ*/ + if( ( readAddr < MCU_APP_Flash_Start_Addr ) || ( ( readAddr + NumByteToWrite ) > MCU_EEPROM_Start_Addr ) ) { + DBG_SYS_Printf("MCU APP Flash Addr Error:%x - %x\r\n", readAddr, NumByteToWrite); + return 0x01; + } + + sta = FLASH_ROMA_READ(readAddr, pBuffer, NumByteToWrite); + + if (sta != FLASH_COMPLETE){ + DBG_Printf("Operation FLASH_ROMA_READ failed %x!! Err Code %x\r\n", readAddr, sta); + return 0x01; + } + + return 0x00; +} + + + +/******************************************************************************* +* Function Name : MCU_APP_Flash_Erase +* Description : MCU Flashݲ +* Input : + pBufferд + NumByteToWriteдݳ -- д볤ȱΪ4ı + readAddrȡַ 0x00004000 ~ 0x0006FFFF 432KB +*******************************************************************************/ +uint8_t MCU_APP_Flash_Erase(uint32_t readAddr,uint16_t NumByteToWrite) +{ + FLASH_Status sta; + + /* УȡַͳǷ - ȡַǷAPP FlashΧ*/ + if( ( readAddr < MCU_APP_Flash_Start_Addr ) || ( ( readAddr + NumByteToWrite ) > MCU_EEPROM_Start_Addr ) ) { + DBG_SYS_Printf("MCU EEPROM Addr Error:%x - %x\r\n", readAddr, NumByteToWrite); + return 0x01; + } + + FLASH_Unlock(); + sta = FLASH_ROMA_ERASE(readAddr, NumByteToWrite); + FLASH_Lock(); + + if (sta != FLASH_COMPLETE){ + DBG_Printf("Operation FLASH_ROMA_ERASE failed %x!! Err Code %x\r\n", readAddr, sta); + return 0x01; + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : MCU_APP_Flash_ALLErase +* Description : MCU Flash - APP(APP) +*******************************************************************************/ +uint8_t MCU_APP_Flash_ALLErase(void) +{ + FLASH_Status sta; + + for(uint32_t i=MCU_APP_Flash_Start_Addr;i MCU_EEPROM_End_Addr ) || ((NumByteToWrite % 4) != 0x00)) { + DBG_SYS_Printf("MCU EEPROM Addr Error:%x - %x\r\n", writeAddr, NumByteToWrite); + return 0x01; + } + + FLASH_Unlock(); + sta = EEPROM_WRITE(writeAddr, pBuffer, NumByteToWrite); + FLASH_Lock(); + + if (sta != FLASH_COMPLETE){ + DBG_SYS_Printf("Operation FLASH_ROMA_WRITE failed %x!! Err Code %x\r\n", writeAddr, sta); + + return 0x01; + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : MCU_EEPROM_Read +* Description : MCU EEPROMݶȡ +* Input : + pBufferд + NumByteToWriteдݳ -- д볤ȱΪ4ı + readAddrȡַ 0x00004000 ~ 0x0006FFFF 432KB +*******************************************************************************/ +uint8_t MCU_EEPROM_Read(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t readAddr) +{ + FLASH_Status sta; + + /* УȡַͳǷ - ȡַǷAPP FlashΧ*/ + if( ( readAddr < MCU_EEPROM_Start_Addr ) || ( ( readAddr + NumByteToWrite ) > MCU_EEPROM_End_Addr ) ) { + DBG_SYS_Printf("MCU EEPROM Addr Error:%x - %x\r\n", readAddr, NumByteToWrite); + return 0x01; + } + + sta = EEPROM_READ(readAddr, pBuffer, NumByteToWrite); + + if (sta != FLASH_COMPLETE){ + DBG_Printf("Operation FLASH_ROMA_READ failed %x!! Err Code %x\r\n", readAddr, sta); + return 0x01; + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : MCU_EEPROM_Erase +* Description : MCU EEPROMݲ +* Input : + eraseAddrַ 0x70000 -- 0x77FFF + lengthֻܰտСΪ4096 +*******************************************************************************/ +uint8_t MCU_EEPROM_Erase(uint32_t eraseAddr,uint16_t length) +{ + FLASH_Status sta; + + /* УȡַͳǷ - ȡַǷAPP FlashΧ */ + if( ( eraseAddr < MCU_EEPROM_Start_Addr ) || ( ( eraseAddr + length ) > MCU_EEPROM_End_Addr ) ) { + DBG_SYS_Printf("MCU EEPROM Addr Error:%x - %x\r\n", eraseAddr, length); + return 0x01; + } + + FLASH_Unlock(); + sta = EEPROM_ERASE(eraseAddr, length); + FLASH_Lock(); + + if (sta != FLASH_COMPLETE){ + DBG_Printf("Operation MCU_EEPROM_Erase failed %x!! Err Code %x\r\n", eraseAddr, sta); + return 0x01; + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : MCU_EEPROM_ALLErase +* Description : MCU Flash - EEPROM +*******************************************************************************/ +uint8_t MCU_EEPROM_ALLErase(void) +{ + FLASH_Status sta; + + for(uint32_t i=MCU_EEPROM_Start_Addr;idev_addr); + DBG_SYS_Printf("EE DevType:%d",info->dev_type); + DBG_SYS_Printf("EE DevBootVer:%d",info->dev_boot_ver); + DBG_SYS_Printf("EE DevAppVer:%d",info->dev_app_ver); + DBG_SYS_Printf("EE DevNameLen:%d",info->dev_name_len); + DBG_SYS_Printf("EE DevName:%s",info->dev_name); + + return 0x00; + } + } + } + + return 0x01; +} + +/******************************************************************************* +* Function Name : EEPROM_WriteMCUDevInfo +* Description : 豸Ϣд뵽EEPROM +*******************************************************************************/ +uint8_t EEPROM_WriteMCUDevInfo(E_MCU_DEV_INFO *info) +{ + uint8_t save_data[EEPROM_DATA_Size_Max + 6]; + uint16_t save_len = sizeof(E_MCU_DEV_INFO); + + if(save_len >= EEPROM_DATA_Size_Max) save_len = EEPROM_DATA_Size_Max; + + save_data[0] = EEPROM_SVAE_FLAG; + save_data[1] = save_len & 0xFF; + save_data[2] = (save_len >> 8) & 0xFF; + + memcpy(&save_data[4],(uint8_t *)info,save_len); + + save_data[3] = EEPROM_CheckSum(&save_data[4],save_len); + + save_len+=4; + + MCU_EEPROM_Write(save_data,save_len,MCU_EEPROM_MCUDevInfo_Address); + + return 0; +} + +/******************************************************************************* +* Function Name : EEPROM_Default_MCUDevInfo +* Description : EEPROMвָĬֵҽĬϲEEPROM +*******************************************************************************/ +void EEPROM_Default_MCUDevInfo(E_MCU_DEV_INFO *info) +{ +#if (Project_Area == 0x01) + /*Boot */ + info->dev_addr = 0x00; + info->dev_type = 0x00; + info->dev_app_ver = 0x00; + info->dev_boot_ver = Project_FW_Version; + info->dev_name_len = sizeof(Peoject_Name); + + memset((char *)info->dev_name,0,EEPROM_DEV_NAME_Size); + memcpy((char *)info->dev_name,(char *)Peoject_Name,info->dev_name_len); + + //EEPROM_WriteMCUDevInfo(info); +#elif (Project_Area == 0x02) + /*APP */ + info->dev_addr = 0x00; + info->dev_type = Project_Type; + info->dev_app_ver = Project_FW_Version; + info->dev_name_len = sizeof(Peoject_Name); + + memset((char *)info->dev_name,0,EEPROM_DEV_NAME_Size); + memcpy((char *)info->dev_name,(char *)Peoject_Name,info->dev_name_len); + + EEPROM_WriteMCUDevInfo(info); +#endif +} + +/******************************************************************************* +* Function Name : EEPROM_Validate_MCUDevInfo +* Description : УEEPROM жȡIJǷȷȷĻ㽫ǰȷIJд + APPУжAPPEEPROMм¼Ƿһ + BootУжBootEEPROMм¼Ƿһ +*******************************************************************************/ +void EEPROM_Validate_MCUDevInfo(E_MCU_DEV_INFO *info) +{ +#if (Project_Area == 0x01) + /*Boot */ + uint8_t save_flag = 0; + + if(info->dev_boot_ver != Project_FW_Version) + { + info->dev_boot_ver = Project_FW_Version; + save_flag = 0x01; + } + + if(save_flag == 0x01) + { + EEPROM_WriteMCUDevInfo(info); + } +#elif (Project_Area == 0x02) + /*APP */ + U8_T save_flag = 0; + + if(info->dev_app_ver != Project_FW_Version) + { + info->dev_app_ver = Project_FW_Version; + save_flag = 0x01; + } + + if(info->dev_type != Project_Type) + { + info->dev_type = Project_Type; + save_flag = 0x01; + } + + if(info->dev_name_len != sizeof(Peoject_Name)) + { + info->dev_name_len = sizeof(Peoject_Name); + save_flag = 0x01; + } + + if(strncmp((char *)info->dev_name,(char *)Peoject_Name,sizeof(Peoject_Name))) + { + memcpy((char *)info->dev_name,(char *)Peoject_Name,info->dev_name_len); + save_flag = 0x01; + } + + if(save_flag == 0x01) + { + EEPROM_WriteMCUDevInfo(info); + } +#endif +} + +/******************************************************************************* +* Function Name : Read_APP_Feature_Info +* Description : ȡAPP +*******************************************************************************/ +uint8_t Read_APP_Feature_Info(uint8_t option,G_SYS_FEATURE_T *feature_info) +{ + uint16_t crc_val = 0,crc_val2 = 0; + uint32_t temp_val = 0; + memset(g_read_buff,0,sizeof(g_read_buff)); + + if(option == 0x01){ + //ȡMCU Flash APP + MCU_APP_Flash_Read(g_read_buff,APP_FEATURE_SIZE,MCU_APP_Feature_Addr); + }else if(option == 0x02){ + //ȡⲿ Flash APP + Flash_Read(g_read_buff,APP_FEATURE_SIZE,SPIFLASH_APP_FEATURE_Addr); + } + + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"APP Feature :",g_read_buff,APP_FEATURE_SIZE); + + crc_val = g_read_buff[1]; + crc_val <<= 0x08; + crc_val |= g_read_buff[0]; + + crc_val2 = CRC16_Check(&g_read_buff[2],510); + DBG_SYS_Printf("%s CRC: %x - %x",__func__,crc_val,crc_val2); + + if(crc_val == crc_val2) + { + /*Уͨ*/ + feature_info->app_flag = g_read_buff[Feature_AppFlag]; + + temp_val = g_read_buff[Feature_AppStart + 3]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppStart + 2]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppStart + 1]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppStart]; + feature_info->app_start_addr = temp_val; + + temp_val = g_read_buff[Feature_AppEnd + 3]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppEnd + 2]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppEnd + 1]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppEnd]; + feature_info->app_end_addr = temp_val; + + temp_val = g_read_buff[Feature_AppCrcSize + 1]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppCrcSize]; + feature_info->app_crc_size = temp_val; + + temp_val = g_read_buff[Feature_AppCrcLen + 1]; + temp_val <<= 8; + temp_val |= g_read_buff[Feature_AppCrcLen]; + feature_info->app_crc_len = temp_val; + + memcpy(feature_info->app_crc,&g_read_buff[Feature_AppFlashCrc],APP_Feature_CRC_Size); + + /*УǷΧ*/ + if( ( feature_info->app_start_addr < MCU_APP_Flash_Start_Addr ) || ( feature_info->app_start_addr > MCU_APP_Data_End_Addr ) ){ + DBG_SYS_Printf("%s app_start_addr:0x%x Error",__func__, feature_info->app_start_addr); + return 0x02; + } + + if( ( feature_info->app_end_addr > MCU_APP_Data_End_Addr ) || ( feature_info->app_start_addr > feature_info->app_end_addr ) ){ + DBG_SYS_Printf("%s app_end_addr:0x%x - 0x%x Error",__func__,feature_info->app_start_addr,feature_info->app_end_addr); + return 0x02; + } + + if( feature_info->app_crc_size != MCU_APP_Flash_PageSize ){ + DBG_SYS_Printf("%s app_crc_size:%#x Error",__func__,feature_info->app_crc_size); + return 0x02; + } + + return 0x00; + } + + return 0x01; +} + +/******************************************************************************* +* Function Name : Write_APP_Feature_Info +* Description : дAPP +*******************************************************************************/ +uint8_t Write_APP_Feature_Info(uint8_t option,G_SYS_FEATURE_T *feature_info) +{ + uint8_t rev = 0; + + memset(g_read_buff,0,sizeof(g_read_buff)); + memset(g_flash_buff,0,sizeof(g_flash_buff)); + + g_flash_buff[Feature_AppFlag] = feature_info->app_flag; + + g_flash_buff[Feature_AppStart] = feature_info->app_start_addr & 0xFF; + g_flash_buff[Feature_AppStart + 1] = ( feature_info->app_start_addr >> 8 ) & 0xFF; + g_flash_buff[Feature_AppStart + 2] = ( feature_info->app_start_addr >> 16 ) & 0xFF; + g_flash_buff[Feature_AppStart + 3] = ( feature_info->app_start_addr >> 24 ) & 0xFF; + + g_flash_buff[Feature_AppEnd] = feature_info->app_end_addr & 0xFF; + g_flash_buff[Feature_AppEnd + 1] = ( feature_info->app_end_addr >> 8 ) & 0xFF; + g_flash_buff[Feature_AppEnd + 2] = ( feature_info->app_end_addr >> 16 ) & 0xFF; + g_flash_buff[Feature_AppEnd + 3] = ( feature_info->app_end_addr >> 24 ) & 0xFF; + + g_flash_buff[Feature_AppCrcSize] = feature_info->app_crc_size & 0xFF; + g_flash_buff[Feature_AppCrcSize + 1] = ( feature_info->app_crc_size >> 8 ) & 0xFF; + + g_flash_buff[Feature_AppCrcLen] = feature_info->app_crc_len & 0xFF; + g_flash_buff[Feature_AppCrcLen + 1] = ( feature_info->app_crc_len >> 8 ) & 0xFF; + + memcpy(&g_flash_buff[Feature_AppFlashCrc],feature_info->app_crc,APP_Feature_CRC_Size); + + feature_info->crc_check = CRC16_Check(&g_flash_buff[2], 510); + + g_flash_buff[Feature_Check] = feature_info->crc_check & 0xFF; + g_flash_buff[Feature_Check + 1] = ( feature_info->crc_check >> 8 ) & 0xFF; + + if(option == 0x01){ + //ȡMCU Flash APP СΪ512Bytemcu flash ÿд붼дԼ 4096byte + /*д - 1ȶȡ*/ + + MCU_APP_Flash_Read(g_read_buff,MCU_APP_Flash_PageSize,MCU_APP_Feature_PageAddr); + + memcpy(&g_read_buff[MCU_APP_Feature_PageOffset],g_flash_buff,512); + + /*д - 2*/ + rev = MCU_APP_Flash_Erase(MCU_APP_Feature_PageAddr,MCU_APP_Flash_PageSize); + + if(rev != 0x00) { + DBG_SYS_Printf("MCU_APP_Flash_Erase Fail:%d %x - %x",rev,MCU_APP_Feature_PageAddr,MCU_APP_Flash_PageSize); + return 0x01; + } + + /*д - 3д*/ + rev = MCU_APP_Flash_Write(g_read_buff,MCU_APP_Flash_PageSize,MCU_APP_Feature_PageAddr); + + if(rev != 0x00) { + DBG_SYS_Printf("MCU_APP_Flash_Write Fail:%d %#x - %#x",rev,MCU_APP_Feature_PageAddr,MCU_APP_Flash_PageSize); + return 0x02; + } + + /*д - 4Уд*/ + rev = FLASH_ROMA_VERIFY(MCU_APP_Feature_PageAddr,g_read_buff,MCU_APP_Flash_PageSize); + if(rev != 0x00) { + DBG_SYS_Printf("FLASH_ROMA_VERIFY Fail:%d %#x - %#x",rev,MCU_APP_Feature_PageAddr,MCU_APP_Flash_PageSize); + return 0x03; + } + + }else if(option == 0x02){ + //ȡⲿ Flash APP + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"SPI Flash Para:",g_flash_buff,APP_FEATURE_SIZE); + + Flash_Write(g_flash_buff,APP_FEATURE_SIZE,SPIFLASH_APP_FEATURE_Addr); + } + + return 0x00; +} + +/******************************************************************************* +* Function Name : APP_Feature_Info_Printf +* Description : APPݴӡ +*******************************************************************************/ +void APP_Feature_Info_Printf(G_SYS_FEATURE_T *feature_info) +{ + DBG_SYS_Printf("Feature crc_check: %x \r\n",feature_info->crc_check); + DBG_SYS_Printf("Feature app_flag: %x \r\n",feature_info->app_flag); + + + DBG_SYS_Printf("Feature app_start_addr: %x \r\n",feature_info->app_start_addr); + DBG_SYS_Printf("Feature app_end_addr: %x \r\n",feature_info->app_end_addr); + DBG_SYS_Printf("Feature app_crc_len: %d \r\n",feature_info->app_crc_len); + Dbg_Print_Buff(DBG_BIT_SYS_STATUS,"Feature app_crc:",feature_info->app_crc,471); +} + + + + diff --git a/MCU_Driver/rtc.c b/MCU_Driver/rtc.c new file mode 100644 index 0000000..31a2ff4 --- /dev/null +++ b/MCU_Driver/rtc.c @@ -0,0 +1,221 @@ +/* + * rtc.c + * + * Created on: Jul 29, 2025 + * Author: cc + */ +#include "includes.h" +#include + +S_RTC RTC_Raw_Data = { + .year = 0, + .month = 1, + .day = 1, + .week = 0, + .hour = 0, + .minute = 0, + .second = 0, +}; + +S_RTC MCU_RTC_Data = { + .year = 0, + .month = 1, + .day = 1, + .week = 0, + .hour = 0, + .minute = 0, + .second = 0, +}; + +uint32_t Mcu_GetTime_tick = 0; +uint32_t Log_Time_ms = 0; + +/******************************************************************************* +* Function Name : RTC_Init +* Description : RTCʼ - עBLV-C1PûRTCܣֻʹϵͳʱģRTCʱ +* Return : None +*******************************************************************************/ +void RTC_Init(void) +{ + memset(&RTC_Raw_Data,0,sizeof(S_RTC)); + memset(&MCU_RTC_Data,0,sizeof(S_RTC)); + + RTC_Raw_Data.year = 0x00; + RTC_Raw_Data.month = 0x01; + RTC_Raw_Data.day = 0x01; + RTC_Raw_Data.week = 0x00; + RTC_Raw_Data.hour = 0x00; + RTC_Raw_Data.minute = 0x00; + RTC_Raw_Data.second = 0x00; + + MCU_RTC_Data.year = 0x00; + MCU_RTC_Data.month = 0x01; + MCU_RTC_Data.day = 0x01; + MCU_RTC_Data.week = 0x00; + MCU_RTC_Data.hour = 0x00; + MCU_RTC_Data.minute = 0x00; + MCU_RTC_Data.second = 0x00; + +} + +/******************************************************************************* +* Function Name : HEX_data_conversion_to_DEC +* Description : ʮƱʮתΪʵʵʮ 0x20 -> 20 +* Return : None +*******************************************************************************/ +uint8_t HEX_Conversion_To_DEC(uint8_t c_num) +{ + uint8_t rev_num = 0; + + rev_num = (c_num/16)*10 + (c_num%16); + + return rev_num; +} + +/******************************************************************************* +* Function Name : HEX_data_conversion_to_DEC +* Description : ʮתΪʮƷʽ 20 -> 0x20 +* Return : None +*******************************************************************************/ +uint8_t DEV_Conversion_To_HEX(uint8_t c_num) +{ + uint8_t rev_num = 0; + + rev_num = (c_num/10)*16 + (c_num%10); + + return rev_num; +} + +/******************************************************************************* +* Function Name : RTC_Conversion_To_UTC +* Description : RTCʱתΪUTCʱ +* Return : None +*******************************************************************************/ +uint32_t RTC_Conversion_To_Unix(S_RTC *rtc_time) +{ +// uint32_t timestamp = 0; +// struct tm test_time; +// +// test_time.tm_year = HEX_Conversion_To_DEC(rtc_time->year) + 2000 - 1900; +// if(rtc_time->month != 0x00) +// { +// test_time.tm_mon = HEX_Conversion_To_DEC(rtc_time->month) - 1; +// }else { +// test_time.tm_mon = 1; +// } +// +// test_time.tm_mday = HEX_Conversion_To_DEC(rtc_time->day); +// test_time.tm_hour = HEX_Conversion_To_DEC(rtc_time->hour); +// test_time.tm_min = HEX_Conversion_To_DEC(rtc_time->minute); +// test_time.tm_sec = HEX_Conversion_To_DEC(rtc_time->second); +// test_time.tm_isdst = -1; +// +// timestamp = mktime(&test_time); //תı־UTCʱ +// +// /*ʱ仹Ҫȥ8Сʱ*/ +// timestamp -= 8*3600; +// +// return timestamp; + + return 0x00; +} + +/******************************************************************************* +* Function Name : UTC_Conversion_To_RTC +* Description : UTCʱתΪRTCʱ +* Return : None +*******************************************************************************/ +void Unix_Conversion_To_RTC(S_RTC *rtc_time,uint32_t utc_tick) +{ +// uint8_t temp = 0; +// time_t temp_tick = utc_tick + 8*3600; /*ʱ任ɱ׼Ҫ8Сʱ*/ +// struct tm *test_time; +// +// test_time = localtime(&temp_tick); +// +// temp = ( 1900 + test_time->tm_year ) - 2000; +// rtc_time->year = DEV_Conversion_To_HEX(temp); +// temp = 1 + test_time->tm_mon; +// rtc_time->month = DEV_Conversion_To_HEX(temp); +// temp = test_time->tm_mday; +// rtc_time->day = DEV_Conversion_To_HEX(temp); +// +// temp = test_time->tm_hour; +// rtc_time->hour = DEV_Conversion_To_HEX(temp); +// temp = test_time->tm_min; +// rtc_time->minute = DEV_Conversion_To_HEX(temp); +// temp = test_time->tm_sec; +// rtc_time->second = DEV_Conversion_To_HEX(temp); +// +// temp = test_time->tm_wday; +// rtc_time->week = DEV_Conversion_To_HEX(temp); + +} + +/******************************************************************************* +* Function Name : RTC_ReadDate +* Description : RTCʱȡ - BLV_C1PûRTCܣֶֻʱ +* Return : None +*******************************************************************************/ +uint8_t RTC_ReadDate(S_RTC *psRTC) +{ + //ĵǰʱ+ؼ + uint32_t rtc_tick = 0; + + rtc_tick = RTC_Conversion_To_Unix(&MCU_RTC_Data); + //rtc_tick += rtc_hour*3600+rtc_min*60+rtc_sec; + rtc_tick += SysTick_1s - Mcu_GetTime_tick; + Unix_Conversion_To_RTC(psRTC,rtc_tick); + + return 0; +} + +/******************************************************************************* +* Function Name : RTC_WriteDate +* Description : RTCʱ - BLV_C1PûRTCܣֶֻʱ +* Return : None +*******************************************************************************/ +uint8_t RTC_WriteDate(S_RTC SetRTC) +{ + //2Сʱѯʵĵǰʱ䣬ؼ + MCU_RTC_Data.year = SetRTC.year; + MCU_RTC_Data.month = SetRTC.month; + MCU_RTC_Data.day = SetRTC.day; + MCU_RTC_Data.hour = SetRTC.hour; + MCU_RTC_Data.minute = SetRTC.minute; + MCU_RTC_Data.second = SetRTC.second; + + Mcu_GetTime_tick = SysTick_1s; //¼ǰʱ + + return 0; +} + +/******************************************************************************* +* Function Name : RTC_TASK +* Description : RTC - BLV_C1PûRTCܣֶֻʱ +* Return : None +*******************************************************************************/ +void RTC_TASK(void) +{ + static uint32_t RTC_Tick = 0; + uint8_t r_minute = 0; + if(SysTick_1ms - RTC_Tick >= 1000) + { + r_minute = RTC_Raw_Data.minute; + RTC_Tick = SysTick_1ms; + RTC_ReadDate(&RTC_Raw_Data); + + if(r_minute != RTC_Raw_Data.minute) + { + Log_Time_ms = SysTick_1ms; //ÿʱ + } + } +} + + + + + + + + diff --git a/MCU_Driver/rw_logging.c b/MCU_Driver/rw_logging.c new file mode 100644 index 0000000..ad8137e --- /dev/null +++ b/MCU_Driver/rw_logging.c @@ -0,0 +1,202 @@ +/* + * rw_logging.c + * + * Created on: Jul 29, 2025 + * Author: cc + */ +#include "includes.h" + +/******************************************************************************* +* Function Name : Log_CheckSum +* Description : УȡݴSRAMжȡ +*******************************************************************************/ +uint8_t Log_CheckSum(uint32_t addr,uint8_t len) +{ + uint8_t data_sum = 0; + for(uint8_t i = 0;i SRAM_LOG_End_Address)) rev = SRAM_LOG_DATA_Address; + + return rev; +} + +/******************************************************************************* +* Function Name : Set_Log_Current_Address +* Description : SRAM־ǰдַ +*******************************************************************************/ +void Set_Log_Current_Address(uint32_t W_addr) +{ + uint32_t Last_addr = W_addr; + uint8_t write_buff[4] = {0}; + + if((Last_addr < SRAM_LOG_DATA_Address) || (Last_addr > SRAM_LOG_End_Address)) Last_addr = SRAM_LOG_DATA_Address; + + write_buff[0] = (uint8_t)(Last_addr & 0xFF); + write_buff[1] = (uint8_t)((Last_addr >> 8) & 0xFF); + write_buff[2] = (uint8_t)((Last_addr >> 16) & 0xFF); + write_buff[3] = (uint8_t)((Last_addr >> 24) & 0xFF); + + SRAM_DMA_Write_Buff(write_buff,0x04,SRAM_LOG_WRITE_Address); +} + +/******************************************************************************* +* Function Name : SRAM_Get_READ_Log_Address +* Description : ȡSRAMеǰ־ַ +*******************************************************************************/ +uint32_t SRAM_Get_READ_Log_Address(void) +{ + uint32_t rev = 0; + uint8_t read_buff[4] = {0}; + + SRAM_DMA_Read_Buff(read_buff,0x04,SRAM_LOG_READ_Address); + + rev = read_buff[3]; + rev <<= 8; + rev |= read_buff[2]; + rev <<= 8; + rev |= read_buff[1]; + rev <<= 8; + rev |= read_buff[0]; + + if((rev < SRAM_LOG_DATA_Address) || (rev > SRAM_LOG_End_Address)) rev = SRAM_LOG_DATA_Address; + + return rev; +} + +/******************************************************************************* +* Function Name : SRAM_Set_READ_LOG_Address +* Description : SRAMеǰ־ַ +*******************************************************************************/ +void SRAM_Set_READ_LOG_Address(uint32_t r_addr) +{ + uint32_t Last_addr = r_addr; + uint8_t write_buff[4] = {0}; + + if((Last_addr < SRAM_LOG_DATA_Address) || (Last_addr > SRAM_LOG_End_Address)) Last_addr = SRAM_LOG_DATA_Address; + + write_buff[0] = (uint8_t)(Last_addr & 0xFF); + write_buff[1] = (uint8_t)((Last_addr >> 8) & 0xFF); + write_buff[2] = (uint8_t)((Last_addr >> 16) & 0xFF); + write_buff[3] = (uint8_t)((Last_addr >> 24) & 0xFF); + + SRAM_DMA_Write_Buff(write_buff,0x04,SRAM_LOG_READ_Address); +} + +/******************************************************************************* +* Function Name : ־湦 +* Description : ־ÿһСʱSRAMе־ݽзװ + װֻǼϰͷβǰʱ +*******************************************************************************/ +uint8_t Log_write_sram(uint8_t data_type,uint8_t *buff,uint16_t len) +{ + uint32_t Last_add = 0; + uint8_t temp = 0,temp_len = 0,temp_number = 0; + uint8_t temp_buff[20] = {0}; + uint16_t data_len = len,temp_date = 0,write_len = 0; + uint32_t Log_Hour_Tick = SysTick_1ms - Log_Time_ms; //2021-09-23 Log_Time_msñжндֹֹȫֱжwhileͬʱд + + Log_Hour_Tick += (uint32_t)HEX_Conversion_To_DEC(RTC_Raw_Data.minute)*60000; + Log_Hour_Tick += (uint32_t)HEX_Conversion_To_DEC(RTC_Raw_Data.hour)*3600000; + + if(data_len >= Log_Data_Len_MAX) data_len = Log_Data_Len_MAX; //޶ݳ + write_len = S_Log_Data + data_len + 1; + + /*һȡ־дַ ־*/ + SRAM_DMA_Read_Buff(temp_buff,0x0A,SRAM_LOG_WRITE_Address); + + Last_add = temp_buff[3]; //ȡ־дַ + Last_add <<= 8; + Last_add |= temp_buff[2]; + Last_add <<= 8; + Last_add |= temp_buff[1]; + Last_add <<= 8; + Last_add |= temp_buff[0]; + + temp_number = temp_buff[8]; //ȡ־ + + //ǰַǷЧҿԽ־ + if((Last_add + write_len) >= SRAM_LOG_End_Address) + { + Last_add = SRAM_LOG_DATA_Address; + } + + /*ڶָʽ־*/ + temp_buff[temp_len++] = LOG_Data_Hand; //ͷ + temp_buff[temp_len++] = temp_buff[8]; //к + temp_buff[temp_len++] = write_len; //ݳ 2Byte + temp_buff[temp_len++] = (write_len >> 8) & 0xFF; + temp_buff[temp_len++] = 0x00; + temp_date = (HEX_Conversion_To_DEC(RTC_Raw_Data.year) << 10) + (HEX_Conversion_To_DEC(RTC_Raw_Data.month) << 5) + HEX_Conversion_To_DEC(RTC_Raw_Data.day); + temp_buff[temp_len++] = (temp_date >> 8) & 0xFF; + temp_buff[temp_len++] = temp_date & 0xFF; + temp_buff[temp_len++] = data_type; + temp_buff[temp_len++] = Log_Hour_Tick & 0xFF; + temp_buff[temp_len++] = (Log_Hour_Tick >> 8) & 0xFF; + temp_buff[temp_len++] = (Log_Hour_Tick >> 16) & 0xFF; + temp_buff[temp_len++] = (Log_Hour_Tick >> 24) & 0xFF; + + SRAM_DMA_Write_Buff(temp_buff,S_Log_Data,Last_add); // + SRAM_DMA_Write_Buff(buff,data_len,Last_add + S_Log_Data); // + SRAM_Write_Byte(Log_Data_End,Last_add + S_Log_Data + data_len); //β + + /*У*/ + temp = Log_CheckSum(Last_add,write_len); + SRAM_Write_Byte(temp,Last_add + S_Log_Check); //Уֵ + + /*ˢ־дַ Լ־*/ + Last_add = Last_add + write_len; + Set_Log_Current_Address(Last_add); + if(temp_number >= 0xFF) + { + temp_number = 0x00; + }else { + temp_number++; + } + SRAM_Write_Byte(temp_number,SRAM_LOG_Serial_Number); //β + + return 0; +} + + + + + + diff --git a/MCU_Driver/spi_flash.c b/MCU_Driver/spi_flash.c new file mode 100644 index 0000000..95d5e2c --- /dev/null +++ b/MCU_Driver/spi_flash.c @@ -0,0 +1,495 @@ +/* + * spi_flash.c + * + * Created on: May 20, 2025 + * Author: cc + */ + +#include "spi_flash.h" +#include "debug.h" + +uint8_t Flash_Buffer[4150]; //FLash д뻺BUFF + +void SPI_FLASH_Init(void) +{ + /* SPI Flash SPI SRAM SPI + * SPI Flash ųʼ + * */ + + DBG_SYS_Printf("SPI Flash ID:0x%x\r\n",Flash_ReadID()); +} + +/******************************************************************************* +* Function Name : Flash_ReadSR +* Description : P25Q40H Flashȡ״̬Ĵ +* Input : None +* Return : P25Q40H Flash״̬Ĵֵ + BIT7 6 5 4 3 2 1 0 + SPR0 BP4 BP3 BP2 BP1 BP0 WEL WIP + SPR:Ĭ0,״̬Ĵλ,WPʹ + BP4,BP3,BP2,BP1,BP0:FLASHд + WEL:дʹ + BUSY:æλ(1,æ;0,) + Ĭ:0x00 +*******************************************************************************/ +uint8_t Flash_ReadSR(void) +{ + uint8_t byte = 0; + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_ReadStatusReg); //Ͷȡ״̬Ĵ + byte = SPI0_MasterRecvByte(); + Flash_CS_H; + return byte; +} + +/******************************************************************************* +* Function Name : Flash_WriteSR +* Description : P25Q40H Flashд״̬Ĵ +* Input : + sr_val:д״̬Ĵֵ + BIT7 6 5 4 3 2 1 0 + SPR0 BP4 BP3 BP2 BP1 BP0 WEL WIP + + ֻSPR0,BP3,BP2,BP1,BP0(bit 7,5,4,3,2)д!!! +* Return : None +*******************************************************************************/ +void Flash_WriteSR(uint8_t sr_val) +{ + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_WriteStatusReg); + SPI0_MasterSendByte(sr_val); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_Write_Enable +* Description : P25Q40H дʹ -- WELλ +* Input : None +* Return : None +*******************************************************************************/ +void Flash_Write_Enable(void) +{ + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_WriteEnable); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_Write_Disable +* Description : P25Q40H дֹ -- WEL +* Input : None +* Return : None +*******************************************************************************/ +void Flash_Write_Disable(void) +{ + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_WriteDisable); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_ReadID +* Description : P25Q40H Flash ȡоƬID +* Input : None +* Return : ֵ£ + 0x8512:ʾоƬͺΪP25Q40H + 0x8511:ʾоƬͺΪP25Q20H + 0x8510:ʾоƬͺΪP25Q10H + 0x8509:ʾоƬͺΪP25Q05H +*******************************************************************************/ +uint16_t Flash_ReadID(void) +{ + uint16_t temp=0; + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_ReadManufactureID); + SPI0_MasterRecvByte(); + SPI0_MasterRecvByte(); + SPI0_MasterRecvByte(); + temp |= SPI0_MasterRecvByte()<<8; + temp |= SPI0_MasterRecvByte(); + Flash_CS_H; + return temp; +} + +/******************************************************************************* +* Function Name : Flash_Wait_Busy +* Description : ȴ +* Input : None +* Return : 1ȴʱڷæ״̬ + 0״̬ +*******************************************************************************/ +uint8_t Flash_Wait_Busy(void) +{ + uint8_t temp=0; + uint16_t i=0; + temp = Flash_ReadSR(); + while((temp&0x01)==0x01) + { + FEED_DOG(); //ι + Delay_Us(100); + temp = Flash_ReadSR(); + i++; + if(i>3000) return 1; + }; + return 0; +} + +/******************************************************************************* +* Function Name : Flash_PowerDown +* Description : Flash ģʽ +* Input : None +* Return : None +*******************************************************************************/ +void Flash_PowerDown(void) +{ + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_PowerDown); + Delay_Us(3); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_PowerDown +* Description : Flash ѵģʽ +* Input : None +* Return : None +*******************************************************************************/ +void Flash_Wakeup(void) +{ + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_ReleasePowerDown); + Delay_Us(3); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_Erase_Chip +* Description : оƬ +* Input : None +* Return : None +*******************************************************************************/ +void Flash_Erase_Chip(void) +{ + Flash_Write_Enable(); + Flash_Wait_Busy(); + Flash_CS_L; + SPI0_MasterSendByte(P24Q40H_ChipErase); + Flash_CS_H; + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Erase_Block +* Description : +* Input : BLK_ID(0~31) 2M +* Return : None +*******************************************************************************/ +void Flash_Erase_Block(uint32_t BLK_ID) +{ + uint8_t flash_buff[5]; + + BLK_ID*=0x10000; //64K + flash_buff[0] = P24Q40H_BlockErase; + flash_buff[1] = (uint8_t)((BLK_ID >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((BLK_ID >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((BLK_ID) & 0xFF); + flash_buff[4] = 0x00; + + Flash_Write_Enable(); + Flash_Wait_Busy(); + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + Flash_CS_H; + + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Erase_Sector +* Description : +* Input : DST_Addr(0~511) 2M +* Return : None +*******************************************************************************/ +void Flash_Erase_Sector(uint32_t DST_ID) +{ + uint8_t flash_buff[5]; + + DST_ID*=4096; + flash_buff[0] = P24Q40H_SectorErase; + flash_buff[1] = (uint8_t)((DST_ID >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((DST_ID >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((DST_ID) & 0xFF); + flash_buff[4] = 0x00; + + Flash_Write_Enable(); + Flash_Wait_Busy(); + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + Flash_CS_H; + + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Erase_Page +* Description : ҳ +* Input : Page_IDҳ(0~8191) +* Return : None +*******************************************************************************/ +void Flash_Erase_Page(uint32_t Page_ID) +{ + uint8_t flash_buff[5]; + + Page_ID*=256; + flash_buff[0] = P24Q40H_PageErase; + flash_buff[1] = (uint8_t)((Page_ID >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((Page_ID >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((Page_ID) & 0xFF); + flash_buff[4] = 0x00; + + Flash_Write_Enable(); + Flash_Wait_Busy(); + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + Flash_CS_H; + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Erase_Page +* Description : ҳ +* Input : Page_addr:ַ +* Return : None +*******************************************************************************/ +void Flash_Erase_Pageaddr(uint32_t Page_addr) +{ + uint8_t flash_buff[5]; + + flash_buff[0] = P24Q40H_PageErase; + flash_buff[1] = (uint8_t)((Page_addr >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((Page_addr >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((Page_addr) & 0xFF); + flash_buff[4] = 0x00; + + Flash_Write_Enable(); + Flash_Wait_Busy(); + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + Flash_CS_H; + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Read +* Description : P25Q40H Flash ַָʼȡָȵ +* Input : + pBufferݴ洢 + NumByteToReadҪȡֽ(65535) + ReadAddrȡʼַ(24bit) +* Return : None +*******************************************************************************/ +void Flash_Read(uint8_t* pBuffer,uint16_t NumByteToRead,uint32_t ReadAddr) +{ + uint8_t flash_buff[5]; + + flash_buff[0] = P24Q40H_ReadData; + flash_buff[1] = (uint8_t)((ReadAddr >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((ReadAddr >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((ReadAddr) & 0xFF); + flash_buff[4] = 0x00; + + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + SPI0_DMARecv(pBuffer,NumByteToRead); + Flash_CS_H; +} + +/******************************************************************************* +* Function Name : Flash_Write_Page +* Description : P25Q40H Flash ַָʼдָȵ +* Input : + pBufferݴ洢 + NumByteToReadҪдֽ(256),Ӧóҳʣֽ!!! + ReadAddrȡʼַ(24bit) +* Return : None +*******************************************************************************/ +void Flash_Write_Page(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr) +{ + uint8_t flash_buff[5]; + + flash_buff[0] = P24Q40H_PageProgram; + flash_buff[1] = (uint8_t)((writeAddr >> 16) & 0xFF); + flash_buff[2] = (uint8_t)((writeAddr >> 8) & 0xFF); + flash_buff[3] = (uint8_t)((writeAddr) & 0xFF); + flash_buff[4] = 0x00; + + Flash_Write_Enable(); + Flash_CS_L; + SPI0_DMATrans(flash_buff,0x04); + SPI0_DMATrans(pBuffer,NumByteToWrite); + Flash_CS_H; + Flash_Wait_Busy(); +} + +/******************************************************************************* +* Function Name : Flash_Write_NoCheck +* Description : ޼дP25Q40H FLASH +ע⣺ȷдĵַΧڵȫΪ0XFF,ڷ0XFFдݽʧ! + Զҳ + ַָʼдָȵ,ҪȷַԽ! +* Input : + pBufferݴ洢 + NumByteToReadҪдֽ(65535) + ReadAddrȡʼַ(24bit) +* Return : None +*******************************************************************************/ +void Flash_Write_NoCheck(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t writeAddr) +{ + uint16_t pageremain; + pageremain=256-writeAddr%256; //ҳʣֽ + if(NumByteToWrite<=pageremain) pageremain=NumByteToWrite;//256ֽ + while(1) + { + FEED_DOG(); //ι + + Flash_Write_Page(pBuffer,pageremain,writeAddr); + if(pageremain == NumByteToWrite) break; //д + else { + pBuffer+=pageremain; + writeAddr+=pageremain; + + NumByteToWrite-=pageremain; + if(NumByteToWrite>256) pageremain=256; + else pageremain=NumByteToWrite; + } + }; +} + +/******************************************************************************* +* Function Name : Flash_Write +* Description : ޼дP25Q40H FLASH +ע⣺ȷдĵַΧڵȫΪ0XFF,ڷ0XFFдݽʧ! + Զҳ + ַָʼдָȵ,ҪȷַԽ! +* Input : + pBufferݴ洢 + NumByteToReadҪдֽ(65535) + ReadAddrȡʼַ(24bit) +* Return : None +*******************************************************************************/ +void Flash_Write(uint8_t* pBuffer,uint16_t NumByteToWrite,uint32_t WriteAddr) +{ + uint32_t secpos; + uint16_t secoff,secremain,i; + uint8_t* Write_Buff; + + if(NumByteToWrite <= 256*2) + { + Write_Buff = Flash_Buffer; + + secpos = WriteAddr/256; //ҳַ + secoff = WriteAddr%256; //ڵƫ + secremain = 256 - secoff; //ʣռ + + if(NumByteToWrite<=secremain) secremain = NumByteToWrite; //ǰҳʣռԴ + + while(1) + { + FEED_DOG(); //ι + + Flash_Read(Write_Buff,256,secpos*256); //ȡ + + for(i=0;i 256) secremain = 256; //һҳд + else secremain = NumByteToWrite; //һҳд + } + } + } + else + { + Write_Buff = Flash_Buffer; + + secpos = WriteAddr/4096; //ַ + secoff = WriteAddr%4096; //ڵƫ + secremain = 4096 - secoff; //ʣռ + + if(NumByteToWrite<=secremain) secremain = NumByteToWrite; //ǰʣռԴ + + while(1) + { + FEED_DOG(); //ι + + Flash_Read(Write_Buff,2048,secpos*4096); //ȡ + Flash_Read(Write_Buff+2048,2048,secpos*4096+2048); //ȡ + + for(i=0;i 4096) secremain = 4096; //һд + else secremain = NumByteToWrite; //һд + } + } + } +} + + + + + diff --git a/MCU_Driver/spi_sram.c b/MCU_Driver/spi_sram.c new file mode 100644 index 0000000..a35c311 --- /dev/null +++ b/MCU_Driver/spi_sram.c @@ -0,0 +1,266 @@ +/* + * spi.c + * + * Created on: May 16, 2025 + * Author: cc + */ +#include "spi_sram.h" +#include "debug.h" +#include + +void SPI_SRAM_Init(void) +{ + GPIOA_ModeCfg(GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_11, GPIO_ModeOut_PP); + GPIOA_ModeCfg(GPIO_Pin_5, GPIO_ModeIN_Floating); + + GPIO_PinRemapConfig(GPIO_PartialRemap2_SPI0,ENABLE); + + /*Եó SPI߲30MHZ ֲдSPIͨѶΪ50MHZ 24MHZ*/ + SPI0_MasterInit(24000000); + SPI0_DataMode(Mode0_HighBitINFront); + + SRAM_CE_H; + + /*ȡSRAMоƬID*/ + //SRAM_Read_ID_Opeartion(); +} + +/******************************************************************************* +* Function Name : SRAM_Write_Byte +* Description : SRAMдֽ +* Input : + wdate : Ҫдֽ + add ֽдĵַ +* Return : None +*******************************************************************************/ +void SRAM_Write_Byte(uint8_t wdate,uint32_t add) +{ + uint8_t Hadd16=0x00,Hadd8=0x00,Ladd=0x00; + Ladd=add; + Hadd8=add>>8; + Hadd16=add>>16; + + if(add >= SRAM_ADDRESS_MAX) return ; + + SRAM_CE_L; + SPI0_MasterSendByte(SRAM_CMD_Write); + SPI0_MasterSendByte(Hadd16); + SPI0_MasterSendByte(Hadd8); + SPI0_MasterSendByte(Ladd); + SPI0_MasterSendByte(wdate); + + SRAM_CE_H; +} + +/******************************************************************************* +* Function Name : SRAM_Read_Byte +* Description : SRAMֽ +* Input : + add ȡֽڵĵַ +* Return : ضȡֽ +*******************************************************************************/ +uint8_t SRAM_Read_Byte(uint32_t add) +{ + uint8_t Hadd8=0x00,Hadd16=0x00,Ladd=0x00,rdate=0x00; + Ladd=add; + Hadd8=add>>8; + Hadd16=add>>16; + + if(add >= SRAM_ADDRESS_MAX) return 0x00; + + SRAM_CE_L; + SPI0_MasterSendByte(SRAM_CMD_Read); + SPI0_MasterSendByte(Hadd16); + SPI0_MasterSendByte(Hadd8); + SPI0_MasterSendByte(Ladd); + rdate = SPI0_MasterRecvByte(); + SRAM_CE_H; + + return rdate; +} + +/******************************************************************************* +* Function Name : SRAM_Write_Word +* Description : SRAMдuint16_t -- Сģʽ +* Input : + wdate : Ҫдֽ + add ֽдĵַ +* Return : ضȡֽ +*******************************************************************************/ +void SRAM_Write_Word(uint16_t wdate,uint32_t add) +{ + SRAM_Write_Byte((uint8_t)(wdate & 0xFF),add); + SRAM_Write_Byte((uint8_t)((wdate >> 8) & 0xFF),add + 1); +} + +/******************************************************************************* +* Function Name : SRAM_Read_Word +* Description : SRAMдuint16_t -- Сģʽ +* Input : + add ȡֵĵַ +* Return : ضȡ +*******************************************************************************/ +uint16_t SRAM_Read_Word(uint32_t add) +{ + uint16_t rev = 0; + rev = SRAM_Read_Byte(add + 1); + rev <<= 8; + rev |= SRAM_Read_Byte(add); + return rev; +} + +/******************************************************************************* +* Function Name : SRAM_Write_DW +* Description : SRAMдuint32_t -- Сģʽ +* Input : + wdate : Ҫд˫ + add ˫дĵַ +* Return : ضȡ˫ +*******************************************************************************/ +void SRAM_Write_DW(uint32_t wdate,uint32_t add) +{ + uint8_t write_buff[4] = {0}; + + write_buff[0] = (uint8_t)(wdate & 0xFF); + write_buff[1] = (uint8_t)((wdate >> 8) & 0xFF); + write_buff[2] = (uint8_t)((wdate >> 16) & 0xFF); + write_buff[3] = (uint8_t)((wdate >> 24) & 0xFF); + + SRAM_DMA_Write_Buff(write_buff,0x04,add); +} + +/******************************************************************************* +* Function Name : SRAM_Read_DW +* Description : SRAMдuint32_t -- Сģʽ +* Input : + add ȡ˫ֵĵַ +* Return : ضȡ˫ +*******************************************************************************/ +uint32_t SRAM_Read_DW(uint32_t add) +{ + uint32_t rev = 0; + uint8_t read_buff[4] = {0}; + + SRAM_DMA_Read_Buff(read_buff,0x04,add); + + rev = read_buff[3]; + rev <<= 8; + rev |= read_buff[2]; + rev <<= 8; + rev |= read_buff[1]; + rev <<= 8; + rev |= read_buff[0]; + + return rev; +} + +/******************************************************************************* +* Function Name : SRAM_Read_ID_Opeartion +* Description : SRAM ȡоƬID +* Input : NULL +* Return : ضȡ +*******************************************************************************/ +uint8_t SRAM_Read_ID_Opeartion(void) +{ + uint8_t spi_addr[5]; + uint8_t read_id[9]; + + memset(spi_addr,0,0x05); + memset(read_id,0,0x04); + + spi_addr[0] = SRAM_CMD_Read_ID; + spi_addr[1] = 0x00 ; + spi_addr[2] = 0x00 ; + spi_addr[3] = 0x00 ; + + SRAM_CE_L; + SPI0_DMATrans(spi_addr,0x04); + SPI0_DMARecv(read_id,0x08); + SRAM_CE_H; + +// Dbg_Println(DBG_BIT_SYS_STATUS_bit, "SRAM MFID:%X",read_id[0]); +// if(read_id[1] == 0x5D) +// { +// Dbg_Println(DBG_BIT_SYS_STATUS_bit, "SRAM KGD:%X - Known Good Die PASS",read_id[1]); +// }else { +// Dbg_Println(DBG_BIT_SYS_STATUS_bit, "SRAM KGD:%X - Known Good Die FAIL",read_id[1]); +// } +// Dbg_Print_Buff(DBG_BIT_SYS_STATUS_bit, "SRAM EID:",&read_id[2],0x06); + + return 0; +} + +/******************************************************************************* +* Function Name : SRAM_Reset_Operation +* Description : SRAM λ - ͨλ +* Input : NULL +* Return : NULL +*******************************************************************************/ +void SRAM_Reset_Operation(void) +{ + SRAM_CE_L; + SPI0_MasterSendByte(SRAM_CMD_Reset_Enable); + SRAM_CE_H; + //Delay_Ms(2); + SRAM_CE_L; + SPI0_MasterSendByte(SRAM_CMD_Reset); + SRAM_CE_H; +} + +/******************************************************************************* +* Function Name : SRAM_DMA_Write_Buff +* Description : SRAM DMAʽд +* Input : + wbuff : Ҫд + len : дݵij -- 4095ֽڳ + add ֽдĵַ +* Return : None +*******************************************************************************/ +void SRAM_DMA_Write_Buff(uint8_t* wbuff,uint16_t len,uint32_t add) +{ + uint8_t spi_addr[5]; + + if(add + len >= SRAM_ADDRESS_MAX) return ; + + memset(spi_addr,0,0x05); + + spi_addr[0] = SRAM_CMD_Write; + spi_addr[1] = (add >> 16) & 0xFF ; + spi_addr[2] = (add >> 8) & 0xFF ; + spi_addr[3] = (add) & 0xFF ; + + SRAM_CE_L; + SPI0_DMATrans(spi_addr,0x04); + SPI0_DMATrans(wbuff,len); + SRAM_CE_H; +} + +/******************************************************************************* +* Function Name : SRAM_DMA_Read_Buff +* Description : SRAM DMAʽȡ +* Input : + rbuff : Ҫȡ + len : ȡݵij -- 4095ֽڳ + add ֽдĵַ +* Return : None +*******************************************************************************/ +void SRAM_DMA_Read_Buff(uint8_t* rbuff,uint16_t len,uint32_t add) +{ + uint8_t spi_addr[5]; + + if(add + len >= SRAM_ADDRESS_MAX) return ; + + memset(spi_addr,0,0x05); + + spi_addr[0] = SRAM_CMD_Read; + spi_addr[1] = (add >> 16) & 0xFF ; + spi_addr[2] = (add >> 8) & 0xFF ; + spi_addr[3] = (add) & 0xFF ; + + SRAM_CE_L; + SPI0_DMATrans(spi_addr,0x04); + SPI0_DMARecv(rbuff,len); + SRAM_CE_H; +} + + diff --git a/MCU_Driver/timer.c b/MCU_Driver/timer.c new file mode 100644 index 0000000..d210eb5 --- /dev/null +++ b/MCU_Driver/timer.c @@ -0,0 +1,51 @@ +/* + * timer.c + * + * Created on: May 16, 2025 + * Author: cc + */ +#include "timer.h" +#include +#include + + + +void TIMER0_Init(void) +{ + TMR0_DeInit(); + TMR0_TimerInit(SystemCoreClock / 10000); + TMR0_ITCfg(RB_TMR_IF_CYC_END, ENABLE); + NVIC_EnableIRQ(TIM0_IRQn); + TMR0_Enable(); +} + +volatile uint32_t Time0_100us = 0; +volatile uint32_t Time0_1ms = 0; + +void __attribute__((interrupt("WCH-Interrupt-fast"))) TIM0_IRQHandler() +{ + static uint8_t NUM_1 = 0; + + TMR0_ClearITFlag(RB_TMR_IF_CYC_END); + + Time0_100us++; + NUM_1++; + + if(NUM_1 >= 10){ + NUM_1 = 0; + Time0_1ms++; + } +} + +void Timer0_Task(void) +{ + static uint32_t timer0_tick = 0; + + if(Time0_1ms - timer0_tick >= 1000 ){ + timer0_tick = Time0_1ms; + + printf("Run:%d ..",timer0_tick); + } +} + + diff --git a/MCU_Driver/uart.c b/MCU_Driver/uart.c new file mode 100644 index 0000000..9b5af9a --- /dev/null +++ b/MCU_Driver/uart.c @@ -0,0 +1,732 @@ +/* + * uart.c + * + * Created on: May 14, 2025 + * Author: cc + * + * Ŀǰ RS485 + * + * Uart1 -> Դ + * Uart0 -> U1 -> RS485 1 + * UART2 -> U2 -> RS485 2 + * Uart3 -> U3 -> BUS + * + */ + +#include "includes.h" + +#include + +UART_t g_uart[UART_MAX]; + +void UART0_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); +void UART1_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); +void UART2_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); +void UART3_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); + +/********************************************************************* + * @fn UARTx_Init + * @brief UARTʼע⴮2ͨѶPB22,PB23 - Boot,RST + * @param uart_id - ID + * @param buad - + * @param prt_cf - ڽջص + * @return none + */ +void UARTx_Init(UART_IDX uart_id, uint32_t buad) { + + switch (uart_id) { + case UART_0: + //RS485ͨѶ + GPIOD_ModeCfg(GPIO_Pin_21, GPIO_ModeOut_PP); + MCU485_EN1_L; + + UART0_Reset(); + + GPIO_PinRemapConfig(GPIO_NoRemap_UART0,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_9, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_8, GPIO_ModeIN_Floating); + + UART0_BaudRateCfg(buad); + R8_UART0_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART0_LCR = RB_LCR_WORD_SZ; + R8_UART0_IER = RB_IER_TXD_EN; + + UART0_CLR_RXFIFO(); + UART0_CLR_TXFIFO(); + + UART0_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART0_IRQn); + + memset(&g_uart[UART_0],0,sizeof(UART_t)); + Set_Uart_recvTimeout(&g_uart[UART_0],buad); + + g_uart[UART_0].send_data_cf = UART0_SendString; + g_uart[UART_0].set_baud_cf = UART0_ChangeBaud; + break; + case UART_1: + UART1_Reset(); + + GPIO_PinRemapConfig(GPIO_NoRemap_UART1,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_11, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_10, GPIO_ModeIN_Floating); + + UART1_BaudRateCfg(buad); + R8_UART1_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART1_LCR = RB_LCR_WORD_SZ; + R8_UART1_IER = RB_IER_TXD_EN; + + UART1_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART1_IRQn); + + memset(&g_uart[UART_1],0,sizeof(UART_t)); + Set_Uart_recvTimeout(&g_uart[UART_1],buad); + + g_uart[UART_1].send_data_cf = UART1_SendString; + g_uart[UART_1].set_baud_cf = UART1_ChangeBaud; + break; + case UART_2: + //RS485ͨѶ + GPIOB_ModeCfg(GPIO_Pin_15, GPIO_ModeOut_PP); + MCU485_EN2_L; + + UART2_Reset(); + + GPIO_PinRemapConfig(GPIO_PartialRemap1_UART2,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_14, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_12, GPIO_ModeIN_Floating); + + UART2_BaudRateCfg(buad); + R8_UART2_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART2_LCR = RB_LCR_WORD_SZ; + R8_UART2_IER = RB_IER_TXD_EN; + + UART2_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART2_IRQn); + + memset(&g_uart[UART_2],0,sizeof(UART_t)); + Set_Uart_recvTimeout(&g_uart[UART_2],buad); + + g_uart[UART_2].send_data_cf = UART2_SendString; + g_uart[UART_2].set_baud_cf = UART2_ChangeBaud; + break; + case UART_3: + UART3_Reset(); + + GPIO_PinRemapConfig(GPIO_PartialRemap1_UART3,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_19, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_18, GPIO_ModeIN_Floating); + + UART3_BaudRateCfg(buad); + R8_UART3_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART3_LCR = RB_LCR_WORD_SZ; + R8_UART3_IER = RB_IER_TXD_EN; + + UART3_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART3_IRQn); + + memset(&g_uart[UART_3],0,sizeof(UART_t)); + Set_Uart_recvTimeout(&g_uart[UART_3],buad); + + g_uart[UART_3].send_data_cf = UART3_SendString; + g_uart[UART_3].set_baud_cf = UART3_ChangeBaud; + break; + } +} + +void Set_Uart_recvTimeout(UART_t *set_uart,uint32_t baud) +{ + if(baud == 115200) + { + set_uart->RecvTimeout = Recv_115200_TimeOut; + }else if(baud == 9600) + { + set_uart->RecvTimeout = Recv_9600_TimeOut; + }else if(baud == 2400) + { + set_uart->RecvTimeout = Recv_2400_TimeOut; + }else if(baud == 512000) + { + set_uart->RecvTimeout = Recv_512000_TimeOut; + }else + { + set_uart->RecvTimeout = 20; + } +} + +/********************************************************************* + * @fn USART1_IRQHandler + * + * @brief USART1жϺ + * + * @return none + */ +void UART0_IRQHandler(void) +{ + switch( UART0_GetITFlag() ) + { + case UART_II_THR_EMPTY: + + break; + case UART_II_RECV_RDY: + case UART_II_RECV_TOUT: + if( (g_uart[UART_0].RecvLen + 1) >= USART_BUFFER_SIZE ) g_uart[UART_0].RecvLen = 0x00; + g_uart[UART_0].RecvBuffer[g_uart[UART_0].RecvLen] = UART0_RecvByte(); + g_uart[UART_0].RecvLen += 1; + g_uart[UART_0].Receiving = 0x01; + g_uart[UART_0].RecvIdleTiming = SysTick_1ms; + + //ǰڷæ״̬ + g_uart[UART_0].CommBusy |= UART_COMMBUSY_RECV_Flag; + break; + } + +} + +/********************************************************************* + * @fn USART1_IRQHandler + * + * @brief USART1жϺ + * + * @return none + */ +void UART1_IRQHandler(void) +{ + switch( UART1_GetITFlag() ) + { + case UART_II_THR_EMPTY: + + break; + case UART_II_RECV_RDY: + case UART_II_RECV_TOUT: + if( (g_uart[UART_1].RecvLen + 1) >= USART_BUFFER_SIZE ) g_uart[UART_1].RecvLen = 0x00; + g_uart[UART_1].RecvBuffer[g_uart[UART_1].RecvLen] = UART1_RecvByte(); + g_uart[UART_1].RecvLen += 1; + g_uart[UART_1].Receiving = 0x01; + g_uart[UART_1].RecvIdleTiming = SysTick_1ms; + break; + } +} + +/********************************************************************* + * @fn UART2_IRQHandler + * + * @brief USART2жϺ + * + * @return none + */ +void UART2_IRQHandler(void) +{ + switch( UART2_GetITFlag() ) + { + case UART_II_THR_EMPTY: + + break; + case UART_II_RECV_RDY: + case UART_II_RECV_TOUT: + if( (g_uart[UART_2].RecvLen + 1) >= USART_BUFFER_SIZE ) g_uart[UART_2].RecvLen = 0x00; + g_uart[UART_2].RecvBuffer[g_uart[UART_2].RecvLen] = UART2_RecvByte(); + g_uart[UART_2].RecvLen += 1; + g_uart[UART_2].Receiving = 0x01; + g_uart[UART_2].RecvIdleTiming = SysTick_1ms; + break; + } +} + +/********************************************************************* + * @fn USART3_IRQHandler + * + * @brief USART3жϺ + * + * @return none + */ +void UART3_IRQHandler(void) +{ + switch( UART3_GetITFlag() ) + { + case UART_II_THR_EMPTY: + + break; + case UART_II_RECV_RDY: + case UART_II_RECV_TOUT: + if( (g_uart[UART_3].RecvLen + 1) >= USART_BUFFER_SIZE ) g_uart[UART_3].RecvLen = 0x00; + g_uart[UART_3].RecvBuffer[g_uart[UART_3].RecvLen] = UART3_RecvByte(); + g_uart[UART_3].RecvLen += 1; + g_uart[UART_3].Receiving = 0x01; + g_uart[UART_3].RecvIdleTiming = SysTick_1ms; + break; + } +} + +/********************************************************************* + * @fn USART1_RECEIVE + * + * @brief USART1 + * + * @return none + */ +void UART0_RECEIVE(void) +{ + if(g_uart[UART_0].Receiving == 0x01) + { + if(SysTick_1ms - g_uart[UART_0].RecvIdleTiming >= g_uart[UART_0].RecvTimeout) + { + g_uart[UART_0].RecvIdleTiming = SysTick_1ms; + + DBG_SYS_Printf("--UART0_RECEIVE--\r\n"); + Launcher_Uart_Upgrade_Process(&g_uart[UART_0]); + + g_uart[UART_0].RecvLen = 0; + g_uart[UART_0].Receiving = 0; + } + } +} + +/********************************************************************* + * @fn USART1_RECEIVE + * + * @brief USART1 + * + * @return none + */ +void UART1_RECEIVE(void) +{ + if(g_uart[UART_1].Receiving == 0x01) + { + if(SysTick_1ms - g_uart[UART_1].RecvIdleTiming >= g_uart[UART_1].RecvTimeout) + { + g_uart[UART_1].RecvIdleTiming = SysTick_1ms; + + DBG_SYS_Printf("--UART1_RECEIVE--\r\n"); + Launcher_Uart_Upgrade_Process(&g_uart[UART_1]); + + g_uart[UART_1].RecvLen = 0; + g_uart[UART_1].Receiving = 0; + } + } +} + + + +/********************************************************************* + * @fn UART2_RECEIVE + * + * @brief USART2 + * + * @return none + */ +void UART2_RECEIVE(void) +{ + if(g_uart[UART_2].Receiving == 1) + { + if(SysTick_1ms - g_uart[UART_2].RecvIdleTiming > g_uart[UART_2].RecvTimeout) + { + g_uart[UART_2].RecvIdleTiming = SysTick_1ms; + + DBG_SYS_Printf("--UART2_RECEIVE--\r\n"); + Launcher_Uart_Upgrade_Process(&g_uart[UART_2]); + + g_uart[UART_2].RecvLen = 0; + g_uart[UART_2].Receiving = 0; + } + } +} + + + +/********************************************************************* + * @fn USART3_RECEIVE + * + * @brief UART3 + * + * @return none + */ +void UART3_RECEIVE(void) +{ + if(g_uart[UART_3].Receiving == 1) + { + if(SysTick_1ms - g_uart[UART_3].RecvIdleTiming > g_uart[UART_3].RecvTimeout) + { + g_uart[UART_3].RecvIdleTiming = SysTick_1ms; + + DBG_SYS_Printf("--UART3_RECEIVE--\r\n"); + Launcher_Uart_Upgrade_Process(&g_uart[UART_3]); + + g_uart[UART_3].RecvLen = 0; + g_uart[UART_3].Receiving = 0; + } + } +} + +/********************************************************************* + * @fn UART0_ChangeBaud + * + * @brief UART0л + * + * @return none + */ +uint8_t UART0_ChangeBaud(uint32_t baudrate) +{ + uint16_t delay_num = 0; + + while(1) + { + if( UART0_GetLinSTA() & RB_LSR_TX_ALL_EMP ) + { + /*Ϊ*/ + __disable_irq(); + + UART0_Reset(); + + GPIO_PinRemapConfig(GPIO_NoRemap_UART0,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_9, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_8, GPIO_ModeIN_Floating); + + UART0_BaudRateCfg(baudrate); + R8_UART0_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART0_LCR = RB_LCR_WORD_SZ; + R8_UART0_IER = RB_IER_TXD_EN; + + UART0_CLR_RXFIFO(); + UART0_CLR_TXFIFO(); + + UART0_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART0_IRQn); + + Set_Uart_recvTimeout(&g_uart[UART_0],baudrate); + + __enable_irq(); + + return 0; + } + + Delay_Us(100); + delay_num++; + if(delay_num > 500) break; + } + + return 1; +} + +/********************************************************************* + * @fn UART1_ChangeBaud + * + * @brief UART1л + * + * @return none + */ +uint8_t UART1_ChangeBaud(uint32_t baudrate) +{ + uint16_t delay_num = 0; + + while(1) + { + if( UART0_GetLinSTA() & RB_LSR_TX_ALL_EMP ) + { + /*Ϊ*/ + __disable_irq(); + + UART1_Reset(); + + GPIO_PinRemapConfig(GPIO_NoRemap_UART1,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_11, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_10, GPIO_ModeIN_Floating); + + UART1_BaudRateCfg(baudrate); + R8_UART1_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART1_LCR = RB_LCR_WORD_SZ; + R8_UART1_IER = RB_IER_TXD_EN; + + UART1_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART1_IRQn); + + Set_Uart_recvTimeout(&g_uart[UART_1],baudrate); + + __enable_irq(); + + return 0; + } + + Delay_Us(100); + delay_num++; + if(delay_num > 500) break; + } + + return 1; +} + +/********************************************************************* + * @fn UART2_ChangeBaud + * + * @brief UART2л + * + * @return none + */ +uint8_t UART2_ChangeBaud(uint32_t baudrate) +{ + uint16_t delay_num = 0; + + while(1) + { + if( UART0_GetLinSTA() & RB_LSR_TX_ALL_EMP ) + { + /*Ϊ*/ + __disable_irq(); + + UART2_Reset(); + + GPIO_PinRemapConfig(GPIO_PartialRemap1_UART2,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_14, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_12, GPIO_ModeIN_Floating); + + UART2_BaudRateCfg(baudrate); + R8_UART2_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART2_LCR = RB_LCR_WORD_SZ; + R8_UART2_IER = RB_IER_TXD_EN; + + UART2_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART2_IRQn); + + Set_Uart_recvTimeout(&g_uart[UART_2],baudrate); + + __enable_irq(); + + return 0; + } + + Delay_Us(100); + delay_num++; + if(delay_num > 500) break; + } + + return 1; +} + +/********************************************************************* + * @fn UART3_ChangeBaud + * + * @brief UART3л + * + * @return none + */ +uint8_t UART3_ChangeBaud(uint32_t baudrate) +{ + uint16_t delay_num = 0; + + while(1) + { + if( UART0_GetLinSTA() & RB_LSR_TX_ALL_EMP ) + { + /*Ϊ*/ + __disable_irq(); + + UART3_Reset(); + + GPIO_PinRemapConfig(GPIO_PartialRemap1_UART3,ENABLE); + GPIOB_ModeCfg(GPIO_Pin_19, GPIO_ModeOut_PP); + GPIOB_ModeCfg(GPIO_Pin_18, GPIO_ModeIN_Floating); + + UART3_BaudRateCfg(baudrate); + R8_UART3_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART3_LCR = RB_LCR_WORD_SZ; + R8_UART3_IER = RB_IER_TXD_EN; + + UART3_INTCfg(ENABLE, RB_IER_RECV_RDY | RB_IER_THR_EMPTY); + NVIC_EnableIRQ(UART3_IRQn); + + Set_Uart_recvTimeout(&g_uart[UART_3],baudrate); + + __enable_irq(); + + return 0; + } + + Delay_Us(100); + delay_num++; + if(delay_num > 500) break; + } + + return 1; +} + +/* + * RS485ͨѶϼ + * 1ݺ󣬵ȴ߿(ݲͬIJʣȴʱ䲻ͬ),ȴʱ߿ + * 2յݺ󣬵ȴݽϣΪ״̬ + * 3߿пɽݷͣ߷æɷ + * 4ݷҪЧڷͣÿҪǰҪ¼ǰʱ䣬Чں󣬸ݱ㲻ڷ + * 5ͨѶɺлͨѶ + * + * - + * - 1æ״̬ + * - 2ȴʱ + * - 3Чʱ + * + * */ + +uint8_t MCU485_SendString_1(uint8_t *buff, uint16_t len) +{ + uint32_t delay_num = 0; + MCU485_EN1_H; + + UART0_SendString(buff,len); + + //ȴ - 50ms + while(1) + { + if((R8_UART0_LSR & RB_LSR_TX_ALL_EMP)) break; + Delay_Us(1); + delay_num++; + if(delay_num > 50000) break; + } + + MCU485_EN1_L; + return 0x00; +} + +uint8_t MCU485_SendString_2(uint8_t *buff, uint16_t len) +{ + uint32_t delay_num = 0; + MCU485_EN2_H; + + UART2_SendString(buff,len); + + //ȴ - 50ms + while(1) + { + if((R8_UART2_LSR & RB_LSR_TX_ALL_EMP)) break; + Delay_Us(1); + delay_num++; + if(delay_num > 50000) break; + } + + MCU485_EN2_L; + return 0x00; +} + +/******************************************************************************* +* Function Name : Uart0_Add_Data_To_SendBuff +* Description : Uart0 뷢ͻ +* Input : + buff + lenݳ + sendCount ʹ + ValidDuration Чʱ䣬λms + sendInterval ͼʱ䣬λms +*******************************************************************************/ +uint8_t Uart0_Add_Data_To_SendBuff(uint8_t *buff,uint16_t len,uint8_t sendCount,uint32_t ValidDuration,uint32_t sendInterval) +{ + if( buff == NULL) return 0x01; + if( len > USART_BUFFER_SIZE ) return 0x02; + + memset(g_uart[UART_0].SendBuffer,0,USART_BUFFER_SIZE); + memcpy(g_uart[UART_0].SendBuffer,buff,len); + g_uart[UART_0].SendLen = len; + g_uart[UART_0].SendCount = sendCount; + g_uart[UART_0].SendCnt = 0; + g_uart[UART_0].SendValidDuration = ValidDuration; + g_uart[UART_0].SendInterval = sendInterval; + g_uart[UART_0].SendValidTick = SysTick_1ms; + + return 0x00; +} + +/******************************************************************************* +* Function Name : Uart0_Clear_SendBuff +* Description : Uart0 ͻͬʱȡ +*******************************************************************************/ +uint8_t Uart0_Clear_SendBuff(void) +{ + memset(g_uart[UART_0].SendBuffer,0,USART_BUFFER_SIZE); + g_uart[UART_0].SendLen = 0x00; + + return 0x00; +} + +/******************************************************************************* +* Function Name : Uart0_Avoid_Conflict_Send_Task +* Description : Uart0 ͻ - +*******************************************************************************/ +uint8_t Uart0_Avoid_Conflict_Send_Task(void) +{ + if( (g_uart[UART_0].SendLen == 0x00) || (g_uart[UART_0].SendLen > USART_BUFFER_SIZE) ) return 0x01; + + if( g_uart[UART_0].SendCnt >= g_uart[UART_0].SendCount ) { + //ʹﵽޣݷ + g_uart[UART_0].SendLen = 0x00; + return 0x02; + } + + if( SysTick_1ms - g_uart[UART_0].SendValidTick >= g_uart[UART_0].SendInterval ){ + //ѹЧڣ㲻ڽݷ + g_uart[UART_0].SendLen = 0x00; + return 0x03; + } + + if( g_uart[UART_0].CommBusy != UART_COMMBUSY_IDLE_Flag ) return 0x04; //ͨѶڷæ״̬ + + //ݷ + if( ( g_uart[UART_0].SendCnt == 0x00 ) || ( SysTick_1ms - g_uart[UART_0].SendTick >= g_uart[UART_0].SendInterval ) ) + { + __disable_irq(); //رȫж + g_uart[UART_0].CommBusy |= UART_COMMBUSY_SEND_Flag; + g_uart[UART_0].SendIdleTick = SysTick_1ms; + __enable_irq(); //ȫж + + UART0_SendString(g_uart[UART_0].SendBuffer, g_uart[UART_0].SendLen); + g_uart[UART_0].SendTick = SysTick_1ms; + g_uart[UART_0].SendCnt++; + + if( g_uart[UART_0].SendCnt >= g_uart[UART_0].SendCount ) + { + memset(g_uart[UART_0].SendBuffer,0,USART_BUFFER_SIZE); + g_uart[UART_0].SendLen = 0x00; + + return 0x05; //ͨѶ + } + } + + return 0x00; +} + +void Uart0_Task(void) +{ + UART0_RECEIVE(); + + Uart0_Avoid_Conflict_Send_Task(); + + if( g_uart[UART_0].CommBusy == UART_COMMBUSY_IDLE_Flag ) + { + /*ǰ߿״̬ - Խлʲ*/ + if( g_uart[UART_0].ChangeBaudFlag == 0x01 ) + { + g_uart[UART_0].set_baud_cf(g_uart[UART_0].CommBaud); + g_uart[UART_0].ChangeBaudFlag = 0x00; + } + + }else { + /*ǰڷͷæ״̬ȴ߿״̬ - жʹóʱʱճʱʱһ*/ + if( ((g_uart[UART_0].CommBusy & UART_COMMBUSY_SEND_Flag) != 0x00 ) && ( SysTick_1ms - g_uart[UART_0].SendIdleTick >= g_uart[UART_0].RecvTimeout ) ) + { + g_uart[UART_0].SendIdleTick = SysTick_1ms; + + __disable_irq(); //رȫж + g_uart[UART_0].CommBusy &= ~(UART_COMMBUSY_SEND_Flag); + g_uart[UART_0].SendIdleTick = SysTick_1ms; + __enable_irq(); //ȫж + } + } + +} + + + + + diff --git a/Peripheral/inc/ch564.h b/Peripheral/inc/ch564.h new file mode 100644 index 0000000..de924f3 --- /dev/null +++ b/Peripheral/inc/ch564.h @@ -0,0 +1,1864 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : CH564 Device Peripheral Access Layer Header File. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_H +#define __CH564_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define HSE_VALUE ((uint32_t)25000000) /* Value of the External oscillator in Hz */ +#define HSI_VALUE ((uint32_t)20000000) /* Value of the Internal oscillator in Hz */ + +/* HSE HSI and PLL stabilization time(us) */ +#define HSE_STARTUP_TIME ((uint32_t)2500) +#define HSI_STARTUP_TIME ((uint32_t)12) +#define PLL_STARTUP_TIME ((uint32_t)35) + + +/* CH564 Standard Peripheral Library version number */ +#define __CH564_STDPERIPH_VERSION_MAIN (0x01) /* [15:8] main version */ +#define __CH564_STDPERIPH_VERSION_SUB (0x02) /* [7:0] sub version */ +#define __CH564_STDPERIPH_VERSION ((__CH564_STDPERIPH_VERSION_MAIN << 8)\ + | (__CH564_STDPERIPH_VERSION_SUB << 0)) + +/* ********************************************************************************************************************* */ +/* Base types & constants */ + +#ifndef TRUE +#define TRUE 1 +#define FALSE 0 +#endif +#ifndef NULL +#define NULL 0 +#endif + +#ifndef VOID +#define VOID void +#endif +#ifndef CONST +#define CONST const +#endif +#ifndef BOOL +typedef unsigned char BOOL; +#endif +#ifndef BOOLEAN +typedef unsigned char BOOLEAN; +#endif +#ifndef CHAR +typedef char CHAR; +#endif +#ifndef INT8 +typedef char INT8; +#endif +#ifndef INT16 +typedef short INT16; +#endif +#ifndef INT32 +typedef long INT32; +#endif +#ifndef UINT8 +typedef unsigned char UINT8; +#endif +#ifndef UINT16 +typedef unsigned short UINT16; +#endif +#ifndef UINT32 +typedef unsigned long UINT32; +#endif +#ifndef UINT8V +typedef unsigned char volatile UINT8V; +#endif +#ifndef UINT16V +typedef unsigned short volatile UINT16V; +#endif +#ifndef UINT32V +typedef unsigned long volatile UINT32V; +#endif + +#ifndef PVOID +typedef void *PVOID; +#endif +#ifndef PCHAR +typedef char *PCHAR; +#endif +#ifndef PCHAR +typedef const char *PCCHAR; +#endif +#ifndef PINT8 +typedef char *PINT8; +#endif +#ifndef PINT16 +typedef short *PINT16; +#endif +#ifndef PINT32 +typedef long *PINT32; +#endif +#ifndef PUINT8 +typedef unsigned char *PUINT8; +#endif +#ifndef PUINT16 +typedef unsigned short *PUINT16; +#endif +#ifndef PUINT32 +typedef unsigned long *PUINT32; +#endif +#ifndef PUINT8V +typedef volatile unsigned char *PUINT8V; +#endif +#ifndef PUINT16V +typedef volatile unsigned short *PUINT16V; +#endif +#ifndef PUINT32V +typedef volatile unsigned long *PUINT32V; +#endif + +/* ********************************************************************************************************************* */ +/* Base macros */ + +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#if DEBUG +#define PRINT(X...) printf(X) +#else +#define PRINT(X...) +#endif + +/* Calculate the byte offset of a field in a structure of type */ +#define FIELD_OFFSET(Type, Field) ((UINT16)&(((Type *)0)->Field)) + +/* Calculate the size of a field in a structure of type */ +#define FIELD_SIZE(Type, Field) (sizeof(((Type *)0)->Field)) + +/* An expression that yields the type of a field in a struct */ +#define FIELD_TYPE(Type, Field) (((Type *)0)->Field) + +/* Return the number of elements in a statically sized array */ +#define NUMBER_OF(Array) (sizeof(Array)/sizeof((Array)[0])) +#define NUMBER_OF_FIELD(Type, Field) (NUMBER_OF(FIELD_TYPE(Type, Field))) + +/* Interrupt Number Definition, according to the selected device */ +typedef enum IRQn +{ + /****** RISC-V Processor Exceptions Numbers *******************************************************/ + NonMaskableInt_IRQn = 2, /* 2 Non Maskable Interrupt */ + HardFault_IRQn = 3, /* 3 HardFault Interrupt */ + Ecall_M_Mode_IRQn = 5, /* 5 Ecall M Mode Interrupt */ + Ecall_U_Mode_IRQn = 8, /* 8 Ecall U Mode Interrupt */ + Break_Point_IRQn = 9, /* 9 Break Point Interrupt */ + SysTick_IRQn = 12, /* 12 System timer Interrupt */ + Software_IRQn = 14, /* 14 software Interrupt */ + /****** RISC-V specific Interrupt Numbers *********************************************************/ + IIC_EV_IRQn = 16, /* 16 IIC Event Interrupt */ + IIC_ER_IRQn = 17, /* 17 IIC Error Interrupt */ + ETH_IRQn = 18, /* 18 ETH Global Interrupt */ + USBPD_IRQn = 19, /* 19 USBPD Global Interrupt */ + TIM0_IRQn = 20, /* 20 TIM0 Global Interrupt */ + TIM1_IRQn = 21, /* 21 TIM1 Global Interrupt */ + TIM2_IRQn = 22, /* 22 TIM2 Global Interrupt */ + TIM3_IRQn = 23, /* 23 TIM3 Global Interrupt */ + SPI0_IRQn = 24, /* 24 SPI0 Global Interrupt */ + SPI1_IRQn = 25, /* 25 SPI1 Global Interrupt */ + UART0_IRQn = 26, /* 26 UART0 Global Interrupt */ + UART1_IRQn = 27, /* 27 UART1 Global Interrupt */ + PA_IRQn = 28, /* 28 PA External Interrupt */ + PB_IRQn = 29, /* 29 PB External Interrupt */ + PD_IRQn = 30, /* 30 PC External Interrupt */ + ADC_IRQn = 31, /* 31 ADC Global Interrupt */ + SLV_IRQn = 32, /* 32 Slave Parallel Port Global Interrupt */ + USBHS_HOST_IRQn = 33, /* 33 USBHOST Global Interrupt */ + USBHS_DEV_IRQn = 34, /* 34 USBDEVICE Global Interrupt */ + UART2_IRQn = 35, /* 35 UART0 Global Interrupt */ + UART3_IRQn = 36, /* 36 UART1 Global Interrupt */ + ETHWakeUp_IRQn = 37, /* 37 ETH Wake up Interrupt */ + USBHSWakeUp_IRQn = 38, /* 38 USBHS Wake up Interrupt */ + USBPDWakeUp_IRQn = 39, /* 39 USBPD Wake up Interrupt */ +} IRQn_Type; + +#include +#include "core_riscv.h" +#include "system_ch564.h" + +/* Reset and Clock Control */ +typedef struct +{ + __IO uint8_t SAFE_ACCESS_SIG; + uint8_t RESERVED0; + __IO uint8_t SAFE_ACCESS_ID; + __IO uint8_t WDOG_CLEAR; + __IO uint8_t GLOB_MEM_CFG; + __IO uint8_t GLOB_LOCK_PORT; + __IO uint8_t GLOB_RST_CFG; + __IO uint8_t GLOB_RESET_KEEP; + uint8_t RESERVED1; + __IO uint8_t PLL_OUT_DIV; + uint16_t RESERVED2; + __IO uint8_t SLP_CLK_OFF0; + __IO uint8_t SLP_CLK_OFF1; + __IO uint8_t SLP_WAKE_CTRL; + __IO uint8_t SLP_CTRL_PLL; +} RCC_Typedef; + +/* General Purpose Input Output */ +typedef struct +{ + __IO uint32_t DIR; + __IO uint32_t PIN; + __IO uint32_t OUT; + __IO uint32_t CLR; + __IO uint32_t PU; + __IO uint32_t PD; +} GPIO_Typedef; + +/* Alternate Function IO */ +typedef struct +{ + __IO uint32_t PCFR1; + __IO uint32_t RESERVED1[7]; + __IO uint32_t PCFR2; +} AFIO_Typedef; + +/* External Interrupts */ +typedef struct +{ + __IO uint32_t STATUS; + __IO uint32_t ENABLE; + __IO uint32_t MODE; + __IO uint32_t POLAR; +} EXTI_Typedef; + +/* Timer */ +typedef struct +{ + __IO uint8_t CTRL_MOD; + __IO uint8_t CTRL_DMA; + __IO uint8_t INTER_EN; + uint8_t RESERVED0[3]; + __IO uint8_t INT_FLAG; + __IO uint8_t FIFO_COUNT; + __IO uint32_t COUNT; + __IO uint32_t CNT_END; + __IO uint32_t FIFO; + union + { + __IO uint32_t TMR0_DMA_NOW; + __IO uint32_t TMR1_DMA_NOW; + __IO uint32_t TMR2_DMA_NOW; + uint32_t RESERVED1; + }; + union + { + __IO uint32_t TMR0_DMA_BEG; + __IO uint32_t TMR1_DMA_BEG; + __IO uint32_t TMR2_DMA_BEG; + uint32_t RESERVED2; + }; + union + { + __IO uint32_t TMR0_DMA_END; + __IO uint32_t TMR1_DMA_END; + __IO uint32_t TMR2_DMA_END; + uint32_t RESERVED3; + }; + +} TIM_Typedef; + +/* Analog-to-Digital Converter */ +typedef struct +{ + __IO uint8_t CTRL_MOD; + __IO uint8_t CTRL_DMA; + __IO uint8_t INTER_EN; + __IO uint8_t CLOCK_DIV; + __IO uint16_t DATA; + __IO uint8_t INT_FLAG; + __IO uint8_t FIFO_COUNT; + __IO uint32_t CTRL; + __IO uint16_t CMP_VALUE; + uint16_t RESERVED0; + __IO uint16_t FIFO; + uint16_t RESERVED1; + __IO uint32_t DMA_NOW; + __IO uint32_t DMA_BEG; + __IO uint32_t DMA_END; +} ADC_Typedef; + +/* Universal Synchronous/Asynchronous Receiver/Transmitter */ +typedef struct +{ + union + { + __IO uint8_t RBR; + __IO uint8_t THR; + __IO uint8_t DLL; + __IO uint8_t ADR; + }; + union + { + __IO uint8_t IER; + __IO uint8_t DLM; + }; + union + { + __IO uint8_t IIR; + __IO uint8_t FCR; + }; + __IO uint8_t LCR; + __IO uint8_t MCR; + __IO uint8_t LSR; + __IO uint8_t MSR; + __IO uint8_t DIV; + __IO uint8_t DMA_CTRL; + __IO uint8_t DMA_IF; + uint16_t RESERVED0; + __IO uint32_t DMA_WR_NOW_ADDR; + __IO uint32_t DMA_WR_START_ADDR; + __IO uint32_t DMA_WR_END_ADDR; + __IO uint32_t DMA_RD_NOW_ADDR; + __IO uint32_t DMA_RD_START_ADDR; + __IO uint32_t DMA_RD_END_ADDR; +} UART_Typedef; + +/* Inter Integrated Circuit Interface */ +typedef struct +{ + __IO uint16_t CTLR1; + uint16_t RESERVED0; + __IO uint16_t CTLR2; + uint16_t RESERVED1; + __IO uint16_t OADDR1; + uint16_t RESERVED2; + __IO uint16_t OADDR2; + uint16_t RESERVED3; + __IO uint16_t DATAR; + uint16_t RESERVED4; + __IO uint16_t STAR1; + uint16_t RESERVED5; + __IO uint16_t STAR2; + uint16_t RESERVED6; + __IO uint16_t CKCFGR; + uint16_t RESERVED7; + __IO uint16_t RTR; +} I2C_Typedef; + +/* Serial Peripheral Interface */ +typedef struct +{ + union + { + __IO uint32_t CONTROL_R32; + struct + { + __IO uint8_t CTRL_MOD; + __IO uint8_t CTRL_DMA; + __IO uint8_t INTER_EN; + union + { + __IO uint8_t CLOCK_DIV; + __IO uint8_t SLAVE_PRE; + }; + }; + }; + union + { + __IO uint32_t STATUS_R32; + struct + { + __IO uint8_t BUFFER; + __IO uint8_t RUN_FLAG; + __IO uint8_t INT_FLAG; + __IO uint8_t FIFO_COUNT; + }; + }; + __IO uint8_t RESET_CMD; + __IO uint8_t BUSY; + uint16_t RESERVED0; + __IO uint16_t TOTAL_CNT; + uint16_t RESERVED1; + union + { + __IO uint32_t FIFO_R32; + struct + { + __IO uint8_t FIFO; + uint16_t RESERVED2; + __IO uint8_t FIFO_COUNT1; + }; + }; + union + { + __IO uint32_t SPI0_DMA_NOW; + uint32_t RESERVED3; + }; + union + { + __IO uint32_t SPI0_DMA_BEG; + uint32_t RESERVED4; + }; + union + { + __IO uint32_t SPI0_DMA_END; + uint32_t RESERVED5; + }; +} SPI_Typedef; + +/* passive parallel port (computing) */ +typedef struct +{ + __IO uint8_t CONFIG; + uint8_t RESERVED0; + __IO uint8_t DOUT; + __IO uint8_t STATUS; + uint8_t RESERVED1[42]; + __IO uint8_t INT_FLAG_SLV; + __IO uint8_t INT_SLV_DIN; + uint8_t RESERVED2[316]; + __IO uint8_t DMA_EN_SLV; + __IO uint8_t DMA_MODE_CTRL_SLV; + __IO uint8_t DMA_MODE_EN_SLV; + uint8_t RESERVED3; + __IO uint8_t DMA_INT_FLAG_SLV; + uint8_t RESERVED4[3]; + __IO uint32_t WR_DMA_START_ADDR_SLV; + __IO uint32_t WR_DMA_END_ADDR_SLV; + uint32_t RESERVED5; + __IO uint32_t RD_DMA_START_ADDR_SLV; + __IO uint32_t RD_DMA_END_ADDR_SLV; + __IO uint32_t DMA_END_NOW_SLV; + __IO uint8_t DMA_CMD0_SLV; + __IO uint8_t DMA_CMD1_SLV; + uint16_t RESERVED6; + __IO uint8_t SLV_RESET_CMD; + __IO uint8_t SLV_BUSY; + uint8_t RESERVED7[10]; + __IO uint8_t OTHER_DATA; + uint8_t RESERVED9[3]; + __IO uint16_t DMA_DEC_LEN; + __IO uint16_t DMA_DEC_OFFSET; +} SLV_Typedef; + +/* XBUS */ +typedef struct +{ + __IO uint8_t CONFIG; + uint8_t RESERVED0; + __IO uint8_t CYCLE; + __IO uint8_t SETUP_HOLD; +} XBUS_Typedef; + +/* Ethernet MAC */ +typedef struct +{ + __IO uint32_t MACCR; + __IO uint32_t MACFFR; + __IO uint32_t MACHTHR; + __IO uint32_t MACHTLR; + __IO uint32_t MACMIIAR; + __IO uint32_t MACMIIDR; + __IO uint32_t MACFCR; + __IO uint32_t MACVLANTR; + uint32_t RESERVED0[2]; + __IO uint32_t MACRWUFFR; + __IO uint32_t MACPMTCSR; + uint32_t RESERVED1[2]; + __IO uint32_t MACSR; + __IO uint32_t MACIMR; + __IO uint32_t MACA0HR; + __IO uint32_t MACA0LR; + __IO uint32_t MACA1HR; + __IO uint32_t MACA1LR; + __IO uint32_t MACA2HR; + __IO uint32_t MACA2LR; + __IO uint32_t MACA3HR; + __IO uint32_t MACA3LR; + uint32_t RESERVED2[8]; + __IO uint32_t PHY_CR; + __IO uint32_t CHKSUM_CR; + __IO uint32_t IP_PDR; + __IO uint32_t CHKSUM_HR; + __IO uint32_t CHKSUM_PR; + uint32_t RESERVED3[27]; + __IO uint32_t MMCCR; + __IO uint32_t MMCRIR; + __IO uint32_t MMCTIR; + __IO uint32_t MMCRIMR; + __IO uint32_t MMCTIMR; + uint32_t RESERVED4[14]; + __IO uint32_t MMCTGFSCCR; + __IO uint32_t MMCTGFMSCCR; + uint32_t RESERVED5[5]; + __IO uint32_t MMCTGFCR; + uint32_t RESERVED6[10]; + __IO uint32_t MMCRFCECR; + __IO uint32_t MMCRFAECR; + __IO uint32_t MMCRAFCR; + __IO uint32_t ETH_STATE; + uint32_t RESERVED7[8]; + __IO uint32_t MMCRGUFCR; + uint32_t RESERVED8[334]; + __IO uint32_t PTPTSCR; + __IO uint32_t PTPSSIR; + __IO uint32_t PTPTSHR; + __IO uint32_t PTPTSLR; + __IO uint32_t PTPTSHUR; + __IO uint32_t PTPTSLUR; + __IO uint32_t PTPTSAR; + __IO uint32_t PTPTTHR; + __IO uint32_t PTPTTLR; + uint32_t RESERVED9[567]; + __IO uint32_t DMABMR; + __IO uint32_t DMATPDR; + __IO uint32_t DMARPDR; + __IO uint32_t DMARDLAR; + __IO uint32_t DMATDLAR; + __IO uint32_t DMASR; + __IO uint32_t DMAOMR; + __IO uint32_t DMAIER; + __IO uint32_t DMAMFBOCR; + uint32_t RESERVED10[9]; + __IO uint32_t DMACHTDR; + __IO uint32_t DMACHRDR; + __IO uint32_t DMACHTBAR; + __IO uint32_t DMACHRBAR; +} ETH_Typedef; + +/* USB Power Delivery */ +typedef struct +{ + union + { + __IO uint32_t CONFIG_R32; + struct + { + __IO uint16_t CONFIG; + __IO uint16_t BMC_CLK_CNT; + }; + }; + union + { + __IO uint32_t CONTROL_R32; + struct + { + union + { + __IO uint16_t CONTROL_R16; + struct + { + __IO uint8_t CONTROL; + __IO uint8_t TX_SEL; + }; + }; + __IO uint16_t BMC_TX_SZ; + }; + }; + union + { + __IO uint32_t STATUS_R32; + struct + { + union + { + __IO uint16_t STATUS_16; + struct + { + __IO uint8_t DATA_BUF; + __IO uint8_t STATUS; + }; + }; + __IO uint16_t BMC_BYTE_CNT; + }; + }; + union + { + __IO uint32_t PORT_R32; + struct + { + __IO uint16_t PORT_CC1; + __IO uint16_t PORT_CC2; + }; + }; + union + { + __IO uint32_t DMA_R32; + struct + { + __IO uint16_t DMA; + uint16_t RESERVED0; + }; + }; +} USBPD_Typedef; + +/* USB High-Speed Device */ +typedef struct +{ + __IO uint8_t CONTROL; + __IO uint8_t BASE_MODE; + __IO uint8_t INT_EN; + __IO uint8_t DEV_AD; + __IO uint8_t WAKE_CR; + __IO uint8_t TEST_MODE; + __IO uint16_t LPM_DATA; + __IO uint8_t INT_FG; + __IO uint8_t INT_ST; + __IO uint8_t MIS_ST; + __IO uint8_t reserve1; + __IO uint16_t FRAME_NO; + __IO uint16_t USB_BUS; + __IO uint16_t UEP_TX_EN; + __IO uint16_t UEP_RX_EN; + __IO uint16_t UEP_T_TOG_AUTO; + __IO uint16_t UEP_R_TOG_AUTO; + __IO uint16_t UEP_T_BURST; + __IO uint16_t UEP_R_BURST; + __IO uint32_t UEP_AF_MODE; + __IO uint32_t UEP0_DMA; + __IO uint32_t UEP1_RX_DMA; + __IO uint32_t UEP2_RX_DMA; + __IO uint32_t UEP3_RX_DMA; + __IO uint32_t UEP4_RX_DMA; + __IO uint32_t UEP5_RX_DMA; + __IO uint32_t UEP6_RX_DMA; + __IO uint32_t UEP7_RX_DMA; + __IO uint32_t UEP1_TX_DMA; + __IO uint32_t UEP2_TX_DMA; + __IO uint32_t UEP3_TX_DMA; + __IO uint32_t UEP4_TX_DMA; + __IO uint32_t UEP5_TX_DMA; + __IO uint32_t UEP6_TX_DMA; + __IO uint32_t UEP7_TX_DMA; + __IO uint32_t UEP0_MAX_LEN; + __IO uint32_t UEP1_MAX_LEN; + __IO uint32_t UEP2_MAX_LEN; + __IO uint32_t UEP3_MAX_LEN; + __IO uint32_t UEP4_MAX_LEN; + __IO uint32_t UEP5_MAX_LEN; + __IO uint32_t UEP6_MAX_LEN; + __IO uint32_t UEP7_MAX_LEN; + __IO uint16_t UEP0_RX_LEN; + __IO uint16_t UEP0_RX_SIZE; + __IO uint16_t UEP1_RX_LEN; + __IO uint16_t UEP1_RX_SIZE; + __IO uint16_t UEP2_RX_LEN; + __IO uint16_t UEP2_RX_SIZE; + __IO uint16_t UEP3_RX_LEN; + __IO uint16_t UEP3_RX_SIZE; + __IO uint16_t UEP4_RX_LEN; + __IO uint16_t UEP4_RX_SIZE; + __IO uint16_t UEP5_RX_LEN; + __IO uint16_t UEP5_RX_SIZE; + __IO uint16_t UEP6_RX_LEN; + __IO uint16_t UEP6_RX_SIZE; + __IO uint16_t UEP7_RX_LEN; + __IO uint16_t UEP7_RX_SIZE; + __IO uint16_t UEP0_TX_LEN; + __IO uint8_t UEP0_TX_CTRL; + __IO uint8_t UEP0_RX_CTRL; + __IO uint16_t UEP1_TX_LEN; + __IO uint8_t UEP1_TX_CTRL; + __IO uint8_t UEP1_RX_CTRL; + __IO uint16_t UEP2_TX_LEN; + __IO uint8_t UEP2_TX_CTRL; + __IO uint8_t UEP2_RX_CTRL; + __IO uint16_t UEP3_TX_LEN; + __IO uint8_t UEP3_TX_CTRL; + __IO uint8_t UEP3_RX_CTRL; + __IO uint16_t UEP4_TX_LEN; + __IO uint8_t UEP4_TX_CTRL; + __IO uint8_t UEP4_RX_CTRL; + __IO uint16_t UEP5_TX_LEN; + __IO uint8_t UEP5_TX_CTRL; + __IO uint8_t UEP5_RX_CTRL; + __IO uint16_t UEP6_TX_LEN; + __IO uint8_t UEP6_TX_CTRL; + __IO uint8_t UEP6_RX_CTRL; + __IO uint16_t UEP7_TX_LEN; + __IO uint8_t UEP7_TX_CTRL; + __IO uint8_t UEP7_RX_CTRL; + __IO uint16_t UEP_TX_ISO; + __IO uint16_t UEP_RX_ISO; +} USBHSD_TypeDef; + +typedef struct +{ + __IO uint8_t CFG; + __IO uint8_t RESERVE1; + __IO uint8_t INT_EN; + __IO uint8_t DEV_AD; + __IO uint32_t CONTROL; + __IO uint8_t INT_FG; + __IO uint8_t INT_ST; + __IO uint8_t MIS_ST; + __IO uint8_t RESERVE2; + __IO uint32_t LPM; + __IO uint32_t SPLIT; + __IO uint32_t FRAME; + __IO uint32_t HOST_TX_LEN; + __IO uint32_t RX_LEN; + __IO uint32_t HOST_RX_MAX_LEN; + __IO uint32_t HOST_RX_DMA; + __IO uint32_t HOST_TX_DMA; + __IO uint32_t PORT_CTRL; + __IO uint8_t PORT_CFG; + __IO uint8_t RESERVE3; + __IO uint8_t PORT_INT_EN; + __IO uint8_t PORT_TEST_CT; + __IO uint16_t PORT_STATUS; + __IO uint8_t PORT_STATUS_CHG; + __IO uint32_t RESERVE4; + __IO uint32_t ROOT_BC_CR; +} USBHSH_TypeDef; + +typedef struct +{ + __IO uint32_t CAL_CR; +} USBHSI_TypeDef; + +/* Expansion Registers */ +typedef struct +{ + __IO uint32_t CTLR0; + uint32_t RESERVED0[3]; + __IO uint32_t CTLR1; + uint32_t RESERVED1[5]; + __IO uint32_t CTLR2; +} EXTEN_Typedef; + +/* Flash Registers */ +typedef struct +{ + __IO uint8_t DATA; + uint8_t RESERVED0; + __IO uint8_t CTRL; + __IO uint16_t FLASHA_KEY_BUF; +} FLASH_Typedef; + +/* Debug Registers */ +typedef struct +{ + __IO uint32_t CR; +} DBG_Typedef; + +#define RCC_BASE ((uint32_t)0x40400000) +#define GPIOA_BASE ((uint32_t)0x40400080) +#define GPIOB_BASE ((uint32_t)0x404000A0) +#define GPIOD_BASE ((uint32_t)0x404000C0) +#define AFIO_BASE ((uint32_t)0x40400140) +#define EXTIA_BASE ((uint32_t)0x40400050) +#define EXTIB_BASE ((uint32_t)0x40400060) +#define EXTID_BASE ((uint32_t)0x40400070) +#define TIM0_BASE ((uint32_t)0x40408000) +#define TIM1_BASE ((uint32_t)0x40408400) +#define TIM2_BASE ((uint32_t)0x40408800) +#define TIM3_BASE ((uint32_t)0x40408C00) +#define ADC_BASE ((uint32_t)0x4040A000) +#define UART0_BASE ((uint32_t)0x4040D000) +#define UART1_BASE ((uint32_t)0x4040D800) +#define UART2_BASE ((uint32_t)0x40409000) +#define UART3_BASE ((uint32_t)0x40409800) +#define I2C_BASE ((uint32_t)0x4040F000) +#define SPI0_BASE ((uint32_t)0x4040C000) +#define SPI1_BASE ((uint32_t)0x4040C800) +#define SLV_BASE ((uint32_t)0x40400014) +#define XBUS_BASE ((uint32_t)0x40400010) +#define ETH_BASE ((uint32_t)0x40406000) +#define USBPD_BASE ((uint32_t)0x4040E000) +#define USBHSD_BASE ((uint32_t)0x40404000) +#define USBHSH_BASE ((uint32_t)0x40404800) +#define USB_HSI_BASE ((uint32_t)0x40005000) +#define EXTEN_BASE ((uint32_t)0x40400144) +#define FLASH_BASE ((uint32_t)0x40400018) + +#define RCC ((RCC_Typedef *)RCC_BASE) +#define GPIOA ((GPIO_Typedef *)GPIOA_BASE) +#define GPIOB ((GPIO_Typedef *)GPIOB_BASE) +#define GPIOD ((GPIO_Typedef *)GPIOD_BASE) +#define AFIO ((AFIO_Typedef *)AFIO_BASE) +#define EXTIA ((EXTI_Typedef *)EXTIA_BASE) +#define EXTIB ((EXTI_Typedef *)EXTIB_BASE) +#define EXTID ((EXTI_Typedef *)EXTID_BASE) +#define TIM0 ((TIM_Typedef *)TIM0_BASE) +#define TIM1 ((TIM_Typedef *)TIM1_BASE) +#define TIM2 ((TIM_Typedef *)TIM2_BASE) +#define TIM3 ((TIM_Typedef *)TIM3_BASE) +#define ADC ((ADC_Typedef *)ADC_BASE) +#define UART0 ((UART_Typedef *)UART0_BASE) +#define UART1 ((UART_Typedef *)UART1_BASE) +#define UART2 ((UART_Typedef *)UART2_BASE) +#define UART3 ((UART_Typedef *)UART3_BASE) +#define I2C ((I2C_Typedef *)I2C_BASE) +#define SPI0 ((SPI_Typedef *)SPI0_BASE) +#define SPI1 ((SPI_Typedef *)SPI1_BASE) +#define SLV ((SLV_Typedef *)SLV_BASE) +#define XBUS ((XBUS_Typedef *)XBUS_BASE) +#define ETH ((ETH_Typedef *)ETH_BASE) +#define USBPD ((USBPD_Typedef *)USBPD_BASE) +#define USBHSD ((USBHSD_TypeDef *) USBHSD_BASE) +#define USBHSH ((USBHSH_TypeDef *) USBHSH_BASE) +#define USB_HSI ((USBHSI_TypeDef *) USB_HSI_BASE) +#define EXTEN ((EXTEN_Typedef *)EXTEN_BASE) +#define FLASH ((FLASH_Typedef *)FLASH_BASE) +#define DBG ((DBG_Typedef *)DBG_BASE) + +/* Standard Peripheral Library old definitions (maintained for legacy purpose) */ +#define HSI_Value HSI_VALUE +#define HSE_Value HSE_VALUE + + +/******************************************************************************/ + +// Address Space +// CODE: 00000000H - 000FFFFFH, 1MB +// SFR: 00400000H - 0040FFFFH, 64KB +// DATA: 00808000H - 0081FFFFH, 96KB/64KB/32KB +// XBUS: 00C00000H - 00CFFFFFH, 1MB +// OTHER: 00E00000H - FFFFFFFFH, undefined +// +// SFR: 00400000H - 0040FFFFH, 64KB +// SYS: +1000H - 1FFFH, include base config, interrupt, GPIO, etc... +// USB: +4000H - 5FFFH +// ETH: +6000H - 7FFFH +// TMR0: +8000H - 83FFH +// TMR1: +8400H - 87FFH +// TMR2: +8800H - 8BFFH +// TMR3: +8C00H - 8FFFH +// ADC: +A000H - AFFFH +// SPI0: +C000H - C7FFH +// SPI1: +C800H - CFFFH +// UART0: +D000H - D7FFH +// UART1: +D800H - DFFFH + +// Register Bit Attribute / Bit Access Type +// RF: Read only for Fixed value +// RO: Read Only (internal change) +// RZ: Read only with auto clear Zero +// WO: Write Only (read zero or different) +// WA: Write only under safe Accessing mode (read zero or different) +// WZ: Write only with auto clear Zero +// RW: Read / Write +// RWA: Read / Write under safe Accessing mode +// RW1: Read / Write 1 to Clear + +/* Register name rule: +R32_* for 32 bits register (UINT32,ULONG) +R16_* for 16 bits register (UINT16,USHORT) +R8_* for 8 bits register (UINT8,UCHAR) +RB_* for bit or bit mask of 8 bit register +BA_* for base address point +Others for register address offset */ + +/* ********************************************************************************************************************* */ +/* System: safe accessing register */ +#define R32_SAFE_ACCESS (*((volatile uint32_t *)0x40400000)) // RW, safe accessing +#define R8_SAFE_ACCESS_SIG (*((volatile uint8_t *)0x40400000)) // WO, safe accessing sign register, must write 0x57 then 0xA8 to enter safe accessing mode +#define RB_SAFE_ACC_MODE 0x03 // RO, current safe accessing mode: 11=safe/unlocked (SAM), other=locked (00..01..10..11) +#define RB_SAFE_ACC_TIMER 0x70 // RO, safe accessing timer bit mask (16*clock number) +#define R8_SAFE_ACCESS_ID (*((volatile uint8_t *)0x40400002)) // RF, safe accessing ID register, always 0x01 +#define R8_WDOG_CLEAR (*((volatile uint8_t *)0x40400003)) // WO, clear watch-dog + +/* System: global configuration register */ +#define R32_GLOBAL_CONFIG (*((volatile uint32_t *)0x40400004)) // RW, global configuration +#define R8_GLOB_MEM_CFG (*((volatile uint8_t *)0x40400004)) // RWA, global memory configuration, SAM and bit7:6 must write 1:0 +#define RB_GLOB_MEM_CFG 0x03 // RWA, global memory config: 10=C96K/D32K, 11=C32K/D96K, 00/01=C64K/D64K +#define RB_GLOB_CFG_FLAG 0x80 // RO, global config flag +#define R8_GLOB_LOCK_PORT (*((volatile uint8_t *)0x40400005)) // RWA, lock port configuration, SAM and bit7:6 must write 0:0 +#define RB_GLOB_LOCK_PA 0x01 // RWA, lock GPIO PA +#define RB_GLOB_LOCK_PB 0x02 // RWA, lock GPIO PB +#define RB_GLOB_LOCK_PD 0x08 // RWA, lock GPIO PD +#define R8_GLOB_RST_CFG (*((volatile uint8_t *)0x40400006)) // RWA, global reset configuration, SAM and bit7:6 must write 0:1 +#define RB_GLOB_FORCE_RST 0x01 // WA/WZ, force global reset, high action, auto clear +#define RB_GLOB_WDOG_EN 0x02 // RWA, watch-dog enable +#define R8_GLOB_RESET_KEEP (*((volatile uint8_t *)0x40400007)) // RW, value keeper during global reset + +/* System: PLL configuration register */ +#define R32_PLL_CONFIG (*((volatile uint32_t *)0x40400008)) // RWA, PLL configuration, SAM +#define R8_PLL_OUT_DIV (*((volatile uint8_t *)0x40400009)) // RWA, PLL output clock divider, SAM and bit7:6 must write 1:0 +#define RB_PLL_ETH_DIV 0x0F // RWA, PLL ethernet clock divider +#define RB_PLL_SYS_DIV 0x30 // RWA, PLL system clock divider + +/* System: sleep control register */ +#define R32_SLEEP_CONTROL (*((volatile uint32_t *)0x4040000C)) // RWA, sleep control, SAM +#define R8_SLP_CLK_OFF0 (*((volatile uint8_t *)0x4040000C)) // RWA, sleep clock off control byte 0, SAM +#define RB_SLP_CLK_TMR0 0x01 // RWA, sleep TMR0 clock +#define RB_SLP_CLK_TMR1 0x02 // RWA, sleep TMR1 clock +#define RB_SLP_CLK_TMR2 0x04 // RWA, sleep TMR2 clock +#define RB_SLP_CLK_TMR3 0x08 // RWA, sleep TMR3 clock +#define RB_SLP_CLK_SPI0 0x10 // RWA, sleep SPI0 clock +#define RB_SLP_CLK_SPI1 0x20 // RWA, sleep SPI1 clock +#define RB_SLP_CLK_UART0 0x40 // RWA, sleep UART0 clock +#define RB_SLP_CLK_UART1 0x80 // RWA, sleep UART1 clock +#define R8_SLP_CLK_OFF1 (*((volatile uint8_t *)0x4040000D)) // RWA, sleep clock off control byte 1, SAM +#define RB_SLP_CLK_UTMI 0x02 // RWA, sleep UTMI clock +#define RB_SLP_CLK_I2C 0x04 // RWA, sleep I2C clock +#define RB_SLP_CLK_USBPD 0x08 // RWA, sleep USBPD clock +#define RB_SLP_CLK_ADC 0x10 // RWA, sleep ADC clock +#define RB_SLP_CLK_GPIO 0x20 // RWA, sleep GPIO clock +#define RB_SLP_CLK_USB 0x40 // RWA, sleep USB clock +#define RB_SLP_CLK_ETH 0x80 // RWA, sleep Ethernet clock +#define R8_SLP_WAKE_CTRL (*((volatile uint8_t *)0x4040000E)) // RWA, wake control, SAM +#define RB_SLP_PA_WAKE 0x01 // RWA,enable PA waking +#define RB_SLP_PB_WAKE 0x02 // RWA,enable PB waking +#define RB_SLP_USBPD_WAKE 0x04 // RWA,enable USBPD waking +#define RB_SLP_PD_WAKE 0x08 // RWA,enable PD waking +#define RB_SLP_USB_WAKE 0x10 // RWA,enable USB waking +#define RB_SLP_WOL_WAKE 0x40 // RWA,enable Ethernet WOL waking +#define RB_SLP_ETH_PWR_DN 0x80 // RWA,Ethernet module power control +#define R8_SLP_CTRL_PLL (*((volatile uint8_t *)0x4040000F)) // WA, PLL sleep control, SAM and write 0x6A to sleep CPU or write 0x95 to sleep PLL +#define R8_SLP_STATUS (*((volatile uint8_t *)0x4040000F)) // RO, sleep status +#define RB_SLP_WOL_STATUS 0x01 // RO, current ethernet WOL status +#define RB_SLP_CLK_UART2 0x02 // RWA, sleep UART2 clock +#define RB_SLP_CLK_UART3 0x04 // RWA, sleep UART3 clock +/* System: external bus configuration register */ +#define R32_EXT_BUS_CFG (*((volatile uint32_t *)0x40400010)) // RW, external bus configuration +#define R8_XBUS_CONFIG (*((volatile uint8_t *)0x40400010)) // RW, external bus configuration +#define RB_XBUS_ENABLE 0x01 // RWA, external bus enable +#define RB_XBUS_EN_32BIT 0x02 // RW, enable 16bit or 32bit external bus +#define RB_XBUS_ADDR_OE 0x0C // RWA, bus address output enable: 00=none,01=PA[5:0],10=PA[11:0],11=PA[19:0] +#define R8_XBUS_CYCLE (*((volatile uint8_t *)0x40400012)) // RW, external bus total cycle (clock number), only low 5 bit +#define R8_XBUS_SETUP_HOLD (*((volatile uint8_t *)0x40400013)) // RW, external bus setup and hold config +#define RB_XBUS_HOLD 0x1F // RW, external bus hold time bit mask (clock number) +#define RB_XBUS_SETUP 0x80 // RW, external bus setup time: 0=1 clock, 1=2 clocks + +/* System: parallel slave configuration register */ +#define R32_PARA_SLV_CFG (*((volatile uint32_t *)0x40400014)) // RW, parallel slave configuration +#define R8_SLV_CONFIG (*((volatile uint8_t *)0x40400014)) // RWA, parallel slave configuration, SAM +#define RB_SLV_ENABLE 0x01 // RWA, parallel slave enable +#define RB_SLV_IE_CMD 0x02 // RWA, enable interrupt for slave writing command event +#define RB_SLV_IE_WR 0x04 // RWA, enable interrupt for slave writing event +#define RB_SLV_IE_RD 0x08 // RWA, enable interrupt for slave reading event +#define R8_SLV_DOUT (*((volatile uint8_t *)0x40400016)) // RW, parallel slave data to output +#define R8_SLV_STATUS (*((volatile uint8_t *)0x40400017)) // RW, parallel slave status to output, only low 7 bit + +/* Interrupt vector register */ +#define R32_INT_VEC_CTRL (*((volatile uint32_t *)0x40400020)) // RWA, interrupt vector control, SAM +#define R8_INT_VEC_IRQ (*((volatile uint8_t *)0x40400020)) // RWA, IRQ normal interrupt vector control, SAM +#define RB_IV_IRQ_TMR0 0x01 // RWA, TMR0 IRQ vector enable +#define RB_IV_IRQ_SPI0 0x02 // RWA, SPI0 IRQ vector enable +#define RB_IV_IRQ_PB 0x04 // RWA, GPIO PB IRQ vector enable +#define R8_INT_VEC_FIQ (*((volatile uint8_t *)0x40400021)) // RWA, FIQ fast interrupt vector control, SAM +#define RB_IV_FIQ_TMR0 0x01 // RWA, TMR0 FIQ vector enable +#define RB_IV_FIQ_SPI0 0x02 // RWA, SPI0 FIQ vector enable +#define RB_IV_FIQ_PB 0x04 // RWA, GPIO PB FIQ vector enable +#define R32_INT_VEC_TMR0 (*((volatile uint32_t *)0x40400024)) // RWA, interrupt vector for TMR0, SAM +#define R32_INT_VEC_SPI0 (*((volatile uint32_t *)0x40400028)) // RWA, interrupt vector for SPI0, SAM +#define R32_INT_VEC_PB (*((volatile uint32_t *)0x4040002C)) // RWA, interrupt vector for GPIO PB, SAM + +/* Interrupt flag register */ +#define R32_INT_FLAG (*((volatile uint32_t *)0x40400040)) // RW, interrupt flag +#define R8_INT_FLAG_0 (*((volatile uint8_t *)0x40400040)) // RO, interrupt flag byte 0 +#define RB_IF_TMR0 0x01 // RO, interrupt flag of TMR0 +#define RB_IF_TMR1 0x02 // RO, interrupt flag of TMR1 +#define RB_IF_TMR2 0x04 // RO, interrupt flag of TMR2 +#define RB_IF_TMR3 0x08 // RO, interrupt flag of TMR3 +#define RB_IF_SPI0 0x10 // RO, interrupt flag of SPI0 +#define RB_IF_SPI1 0x20 // RO, interrupt flag of SPI1 +#define RB_IF_UART0 0x40 // RO, interrupt flag of UART0 +#define RB_IF_UART1 0x80 // RO, interrupt flag of UART1 +#define R8_INT_FLAG_1 (*((volatile uint8_t *)0x40400041)) // RO, interrupt flag byte 1 +#define RB_IF_PA 0x01 // RO, interrupt flag of GPIO PA +#define RB_IF_PB 0x02 // RO, interrupt flag of GPIO PB +#define RB_INT_WOL_STATUS 0x04 // RO, current ethernet WOL status +#define RB_IF_PD 0x08 // RO, interrupt flag of GPIO PD +#define RB_IF_ADC 0x10 // RO, interrupt flag of ADC +#define RB_IF_SLV 0x20 // RO, interrupt flag of parallel slave +#define RB_IF_USB 0x40 // RO, interrupt flag of USB +#define RB_IF_ETH 0x80 // RO, interrupt flag of ethernet +#define R8_INT_FLAG_SLV (*((volatile uint8_t *)0x40400042)) // RW1, parallel slave interrupt flag +#define RB_IF_SLV_CMD0 0x10 // RO, parallel slave command raw flag +#define RB_IF_SLV_CMD 0x20 // RO, parallel slave command synchro flag +#define RB_IF_SLV_WR 0x40 // RW1, interrupt flag of parallel slave writing event +#define RB_IF_SLV_RD 0x80 // RW1, interrupt flag of parallel slave reading event +#define R8_INT_SLV_DIN (*((volatile uint8_t *)0x40400043)) // RO, parallel slave data input +/*SLV DMA enable register*/ +#define R8_DMA_EN_SLV (*((volatile uint8_t *)0x40400180)) //SLV DMA enable register +#define RB_DMA_EN_SLV 0x01 //SLV DMA mode enable control bit +#define RB_DMA_RESP_IE_SLV 0x02 //SLV DMA error transmission interrupts enable control bit +#define RB_DMA_END_IE_SLV 0x04 //SLV DMA error transmission end enable control bit +#define RB_DMA_LOOP_EN_SLV 0x08 //SLV DMA cyclic address mode control bits +#define RB_DMA_FIFO_OV_IE_SLV 0x10 //The FIFO full state interrupts the enable bit +#define RB_DMA_OTHER_IE_SLV 0x20 //when in compatibility mode, Transmission of non-DMA datastate interrupts the enable bit +#define RB_DMA_WR_8BIT 0x40 //selection of transfer data length for DMA write operations +/*SLV DMA mode control register*/ +#define R8_DMA_MODE_CTRL_SLV (*((volatile uint8_t *)0x40400181)) //SLV DMA mode control register +#define CMD0_WR_MODE 0x40 //DMA transfer command word 0 read and write type +#define CMD1_WR_MODE 0x80 //DMA transfer command word 1 read and write type +/*SLV DMA mode enable register*/ +#define R8_DMA_MODE_EN_SLV (*((volatile uint8_t *)0x40400182)) //SLV DMA mode enable register +#define CMD0_EN 0x01 //DMA transfer command word 0 control bit +#define CMD1_EN 0x02 //DMA transfer command word 1 control bit +#define DMA_CMD_MODE1 0x08 //DMA transfer command word mode1 +/*SLV DMA interrupt flag register*/ +#define R8_DMA_INT_FLAG_SLV (*((volatile uint8_t *)0x40400184)) //SLV DMA interrupt flag register +#define WR_DMA_END_IF 0x01 //DMA receive mode transmission end flag bit +#define WR_DMA_RESP_IF 0x02 //DMA receive mode transmission error flag bit +#define RD_DMA_END_IF 0x04 //DMA occurrence mode transmission end flag bit +#define RD_DMA_RESP_IF 0x08 //DMA occurrence mode transmission error flag bit +#define WR_DMA_OV_IF 0x10 //input FIFO full flag +#define WR_OTHER_IF 0x20 //data are written to the flag bit +#define DATA_IN_FIFO_EMPTY 0x40 //Whether DATA_IN_FIFO is empty +/*DMA receive mode start address register*/ +#define R32_WR_DMA_START_ADDR_SLV (*((volatile uint32_t *)0x40400188)) //DMA receive mode start address register +#define MASK_WR_DMA_START_ADDR_SLV 0x0003ffff //DMA receive mode start address +/*DMA receive mode end address register*/ +#define R32_WR_DMA_END_ADDR_SLV (*((volatile uint32_t *)0x4040018c)) //DMA receive mode end address register +#define MASK_WR_DMA_START_ADDR_SLV 0x0003ffff //DMA receive mode end address +/*DMA send mode start address register*/ +#define R32_RD_DMA_START_ADDR_SLV (*((volatile uint32_t *)0x40400194)) //DMA send mode start address register +#define MASK_RD_DMA_START_ADDR_SLV 0x0003ffff //DMA send mode start address +/*DMA send mode end address register*/ +#define R32_RD_DMA_END_ADDR_SLV (*((volatile uint32_t *)0x40400198)) //DMA send mode end address register +#define MASK_RD_DMA_START_ADDR_SLV 0x0003ffff //DMA send mode end address +/*DMA current address register*/ +#define R32_DMA_END_NOW_SLV (*((volatile uint32_t *)0x4040019c)) //DMA current address register +#define MASK_DMA_NOW_ADDR_SLV 0x0003ffff //DMA current address +/*DMA mode command word0 register*/ +#define R8_DMA_CMD0_SLV (*((volatile uint8_t *)0x404001a0)) //DMA mode command word0 register +/*DMA mode command word1 register*/ +#define R8_DMA_CMD1_SLV (*((volatile uint8_t *)0x404001a1)) //DMA mode command word1 register +/*DMA reset the command word register*/ +#define R8_SLV_RESET_CMD (*((volatile uint8_t *)0x404001a4)) //DMA reset the command word register +/*SLV busy flag register*/ +#define R8_SLV_BUSY (*((volatile uint8_t *)0x404001a5)) //SLV busy flag register +#define RB_SLV_BUSY 0x01 //SLV busy flag +/*Non-DMA writes to the data register*/ +#define R8_OTHER_DATA (*((volatile uint8_t *)0x404001b0)) //Non-DMA writes to the data register +/*DMA parses length register*/ +#define R16_DMA_DEC_LEN (*((volatile uint16_t *)0x404001b4)) //DMA parses length register +/*DMA resolves the offset address register*/ +#define R16_DMA_DEC_OFFSET (*((volatile uint16_t *)0x404001b6)) //DMA resolves the offset address register + + +/* GPIO PA interrupt register */ +#define R32_INT_STATUS_PA (*((volatile uint32_t *)0x40400050)) // RW1, GPIO PA interrupt flag +#define R8_INT_STATUS_PA_1 (*((volatile uint8_t *)0x40400051)) // RW1, GPIO PA interrupt flag byte 1 +#define R8_INT_STATUS_PA_2 (*((volatile uint8_t *)0x40400052)) // RW1, GPIO PA interrupt flag byte 2 +#define R32_INT_ENABLE_PA (*((volatile uint32_t *)0x40400054)) // RW, GPIO PA interrupt enable +#define R8_INT_ENABLE_PA_1 (*((volatile uint8_t *)0x40400055)) // RW, GPIO PA interrupt enable byte 1 +#define R8_INT_ENABLE_PA_2 (*((volatile uint8_t *)0x40400056)) // RW, GPIO PA interrupt enable byte 2 +#define R32_INT_MODE_PA (*((volatile uint32_t *)0x40400058)) // RW, GPIO PA interrupt mode: 0=level action, 1=edge action +#define R8_INT_MODE_PA_1 (*((volatile uint8_t *)0x40400059)) // RW, GPIO PA interrupt mode byte 1 +#define R8_INT_MODE_PA_2 (*((volatile uint8_t *)0x4040005A)) // RW, GPIO PA interrupt mode byte 2 +#define R32_INT_POLAR_PA (*((volatile uint32_t *)0x4040005C)) // RW, GPIO PA interrupt polarity: 0=normal/low level/fall edge, 1=invert/high level/rise edge +#define R8_INT_POLAR_PA_1 (*((volatile uint8_t *)0x4040005D)) // RW, GPIO PA interrupt polarity byte 1 +#define R8_INT_POLAR_PA_2 (*((volatile uint8_t *)0x4040005E)) // RW, GPIO PA interrupt polarity byte 2 + +/* GPIO PB interrupt register */ +#define R32_INT_STATUS_PB (*((volatile uint32_t *)0x40400060)) // RW1, GPIO PB interrupt flag +#define R8_INT_STATUS_PB_0 (*((volatile uint8_t *)0x40400060)) // RW1, GPIO PB interrupt flag byte 0 +#define R8_INT_STATUS_PB_1 (*((volatile uint8_t *)0x40400061)) // RW1, GPIO PB interrupt flag byte 1 +#define R8_INT_STATUS_PB_2 (*((volatile uint8_t *)0x40400062)) // RW1, GPIO PB interrupt flag byte 2 +#define R32_INT_ENABLE_PB (*((volatile uint32_t *)0x40400064)) // RW, GPIO PB interrupt enable +#define R8_INT_ENABLE_PB_0 (*((volatile uint8_t *)0x40400064)) // RW, GPIO PB interrupt enable byte 0 +#define R8_INT_ENABLE_PB_1 (*((volatile uint8_t *)0x40400065)) // RW, GPIO PB interrupt enable byte 1 +#define R8_INT_ENABLE_PB_2 (*((volatile uint8_t *)0x40400066)) // RW, GPIO PB interrupt enable byte 2 +#define R32_INT_MODE_PB (*((volatile uint32_t *)0x40400068)) // RW, GPIO PB interrupt mode: 0=level action, 1=edge action +#define R8_INT_MODE_PB_0 (*((volatile uint8_t *)0x40400068)) // RW, GPIO PB interrupt mode byte 0 +#define R8_INT_MODE_PB_1 (*((volatile uint8_t *)0x40400069)) // RW, GPIO PB interrupt mode byte 1 +#define R8_INT_MODE_PB_2 (*((volatile uint8_t *)0x4040006A)) // RW, GPIO PB interrupt mode byte 2 +#define R32_INT_POLAR_PB (*((volatile uint32_t *)0x4040006C)) // RW, GPIO PB interrupt polarity: 0=normal/low level/fall edge, 1=invert/high level/rise edge +#define R8_INT_POLAR_PB_0 (*((volatile uint8_t *)0x4040006C)) // RW, GPIO PB interrupt polarity byte 0 +#define R8_INT_POLAR_PB_1 (*((volatile uint8_t *)0x4040006D)) // RW, GPIO PB interrupt polarity byte 1 +#define R8_INT_POLAR_PB_2 (*((volatile uint8_t *)0x4040006E)) // RW, GPIO PB interrupt polarity byte 2 + +/* GPIO PD interrupt register */ +#define R32_INT_STATUS_PD (*((volatile uint32_t *)0x40400070)) // RW1, GPIO PD interrupt flag +#define R8_INT_STATUS_PD_0 (*((volatile uint8_t *)0x40400070)) // RW1, GPIO PD interrupt flag byte 0 +#define R8_INT_STATUS_PD_3 (*((volatile uint8_t *)0x40400073)) // RW1, GPIO PD interrupt flag byte 3 +#define R32_INT_ENABLE_PD (*((volatile uint32_t *)0x40400074)) // RW, GPIO PD interrupt enable +#define R8_INT_ENABLE_PD_0 (*((volatile uint8_t *)0x40400074)) // RW, GPIO PD interrupt enable byte 0 +#define R8_INT_ENABLE_PD_3 (*((volatile uint8_t *)0x40400077)) // RW, GPIO PD interrupt enable byte 3 +#define R32_INT_MODE_PD (*((volatile uint32_t *)0x40400078)) // RW, GPIO PD interrupt mode: 0=level action, 1=edge action +#define R8_INT_MODE_PD_0 (*((volatile uint8_t *)0x40400078)) // RW, GPIO PD interrupt mode byte 0 +#define R8_INT_MODE_PD_3 (*((volatile uint8_t *)0x4040007B)) // RW, GPIO PD interrupt mode byte 3 +#define R32_INT_POLAR_PD (*((volatile uint32_t *)0x4040007C)) // RW, GPIO PD interrupt polarity: 0=normal/low level/fall edge, 1=invert/high level/rise edge +#define R8_INT_POLAR_PD_0 (*((volatile uint8_t *)0x4040007C)) // RW, GPIO PD interrupt polarity byte 0 +#define R8_INT_POLAR_PD_3 (*((volatile uint8_t *)0x4040007F)) // RW, GPIO PD interrupt polarity byte 3 + +/* GPIO interrupt register address offset and bit define */ +#define BA_INT_PA ((volatile uint8_t *)0x40400050) // point GPIO PA interrupt base address +#define BA_INT_PB ((volatile uint8_t *)0x40400060) // point GPIO PB interrupt base address +#define BA_INT_PD ((volatile uint8_t *)0x40400070) // point GPIO PD interrupt base address +#define INT_GPIO_STATUS 0x00 +#define INT_GPIO_STATUS_0 0x00 +#define INT_GPIO_STATUS_1 0x01 +#define INT_GPIO_STATUS_2 0x02 +#define INT_GPIO_ENABLE 0x04 +#define INT_GPIO_ENABLE_0 0x04 +#define INT_GPIO_ENABLE_1 0x05 +#define INT_GPIO_ENABLE_2 0x06 +#define INT_GPIO_MODE 0x08 +#define INT_GPIO_MODE_0 0x08 +#define INT_GPIO_MODE_1 0x09 +#define INT_GPIO_MODE_2 0x0A +#define INT_GPIO_POLAR 0x0C +#define INT_GPIO_POLAR_0 0x0C +#define INT_GPIO_POLAR_1 0x0D +#define INT_GPIO_POLAR_2 0x0E + +/* GPIO PA register */ +#define R32_PA_DIR (*((volatile uint32_t *)0x40400080)) // RW, GPIO PA I/O direction: 0=in, 1=out +#define R8_PA_DIR_0 (*((volatile uint8_t *)0x40400080)) // RW, GPIO PA I/O direction byte 0 +#define R8_PA_DIR_1 (*((volatile uint8_t *)0x40400081)) // RW, GPIO PA I/O direction byte 1 +#define R8_PA_DIR_2 (*((volatile uint8_t *)0x40400082)) // RW, GPIO PA I/O direction byte 2 +#define R32_PA_PIN (*((volatile uint32_t *)0x40400084)) // RO, GPIO PA input +#define R8_PA_PIN_0 (*((volatile uint8_t *)0x40400084)) // RO, GPIO PA input byte 0 +#define R8_PA_PIN_1 (*((volatile uint8_t *)0x40400085)) // RO, GPIO PA input byte 1 +#define R8_PA_PIN_2 (*((volatile uint8_t *)0x40400086)) // RO, GPIO PA input byte 2 +#define R32_PA_OUT (*((volatile uint32_t *)0x40400088)) // RW, GPIO PA output +#define R8_PA_OUT_0 (*((volatile uint8_t *)0x40400088)) // RW, GPIO PA output byte 0 +#define R8_PA_OUT_1 (*((volatile uint8_t *)0x40400089)) // RW, GPIO PA output byte 1 +#define R8_PA_OUT_2 (*((volatile uint8_t *)0x4040008A)) // RW, GPIO PA output byte 2 +#define R32_PA_CLR (*((volatile uint32_t *)0x4040008C)) // WZ, GPIO PA clear output: 0=keep, 1=clear +#define R8_PA_CLR_0 (*((volatile uint8_t *)0x4040008C)) // WZ, GPIO PA clear output byte 0 +#define R8_PA_CLR_1 (*((volatile uint8_t *)0x4040008D)) // WZ, GPIO PA clear output byte 1 +#define R8_PA_CLR_2 (*((volatile uint8_t *)0x4040008E)) // WZ, GPIO PA clear output byte 2 +#define R32_PA_PU (*((volatile uint32_t *)0x40400090)) // RW, GPIO PA pullup resistance enable +#define R8_PA_PU_0 (*((volatile uint8_t *)0x40400090)) // RW, GPIO PA pullup resistance enable byte 0 +#define R8_PA_PU_1 (*((volatile uint8_t *)0x40400091)) // RW, GPIO PA pullup resistance enable byte 1 +#define R8_PA_PU_2 (*((volatile uint8_t *)0x40400092)) // RW, GPIO PA pullup resistance enable byte 2 +#define R32_PA_PD (*((volatile uint32_t *)0x40400094)) // RW, GPIO PA output open-drain & input pulldown resistance enable +#define R8_PA_PD_0 (*((volatile uint8_t *)0x40400094)) // RW, GPIO PA output open-drain & input pulldown resistance enable byte 0 +#define R8_PA_PD_1 (*((volatile uint8_t *)0x40400095)) // RW, GPIO PA output open-drain & input pulldown resistance enable byte 1 +#define R8_PA_PD_2 (*((volatile uint8_t *)0x40400096)) // RW, GPIO PA output open-drain & input pulldown resistance enable byte 2 + +/* GPIO PB register */ +#define R32_PB_DIR (*((volatile uint32_t *)0x404000A0)) // RW, GPIO PB I/O direction: 0=in, 1=out +#define R8_PB_DIR_0 (*((volatile uint8_t *)0x404000A0)) // RW, GPIO PB I/O direction byte 0 +#define R8_PB_DIR_1 (*((volatile uint8_t *)0x404000A1)) // RW, GPIO PB I/O direction byte 1 +#define R8_PB_DIR_2 (*((volatile uint8_t *)0x404000A2)) // RW, GPIO PB I/O direction byte 2 +#define R32_PB_PIN (*((volatile uint32_t *)0x404000A4)) // RO, GPIO PB input +#define R8_PB_PIN_0 (*((volatile uint8_t *)0x404000A4)) // RO, GPIO PB input byte 0 +#define R8_PB_PIN_1 (*((volatile uint8_t *)0x404000A5)) // RO, GPIO PB input byte 1 +#define R8_PB_PIN_2 (*((volatile uint8_t *)0x404000A6)) // RO, GPIO PB input byte 2 +#define R32_PB_OUT (*((volatile uint32_t *)0x404000A8)) // RW, GPIO PB output +#define R8_PB_OUT_0 (*((volatile uint8_t *)0x404000A8)) // RW, GPIO PB output byte 0 +#define R8_PB_OUT_1 (*((volatile uint8_t *)0x404000A9)) // RW, GPIO PB output byte 1 +#define R8_PB_OUT_2 (*((volatile uint8_t *)0x404000AA)) // RW, GPIO PB output byte 2 +#define R32_PB_CLR (*((volatile uint32_t *)0x404000AC)) // WZ, GPIO PB clear output: 0=keep, 1=clear +#define R8_PB_CLR_0 (*((volatile uint8_t *)0x404000AC)) // WZ, GPIO PB clear output byte 0 +#define R8_PB_CLR_1 (*((volatile uint8_t *)0x404000AD)) // WZ, GPIO PB clear output byte 1 +#define R8_PB_CLR_2 (*((volatile uint8_t *)0x404000AE)) // WZ, GPIO PB clear output byte 2 +#define R32_PB_PU (*((volatile uint32_t *)0x404000B0)) // RW, GPIO PB pullup resistance enable +#define R8_PB_PU_0 (*((volatile uint8_t *)0x404000B0)) // RW, GPIO PB pullup resistance enable byte 0 +#define R8_PB_PU_1 (*((volatile uint8_t *)0x404000B1)) // RW, GPIO PB pullup resistance enable byte 1 +#define R8_PB_PU_2 (*((volatile uint8_t *)0x404000B2)) // RW, GPIO PB pullup resistance enable byte 2 +#define R32_PB_PD (*((volatile uint32_t *)0x404000B4)) // RW, GPIO PB output open-drain & input pulldown resistance enable +#define R8_PB_PD_0 (*((volatile uint8_t *)0x404000B4)) // RW, GPIO PB output open-drain & input pulldown resistance enable byte 0 +#define R8_PB_PD_1 (*((volatile uint8_t *)0x404000B5)) // RW, GPIO PB output open-drain & input pulldown resistance enable byte 1 +#define R8_PB_PD_2 (*((volatile uint8_t *)0x404000B6)) // RW, GPIO PB output open-drain & input pulldown resistance enable byte 2 + +/* GPIO PD register */ +#define R32_PD_DIR (*((volatile uint32_t *)0x404000C0)) // RW, GPIO PD I/O direction: 0=in, 1=out +#define R8_PD_DIR_0 (*((volatile uint8_t *)0x404000C0)) // RW, GPIO PD I/O direction byte 0 +#define R8_PD_DIR_1 (*((volatile uint8_t *)0x404000C1)) // RW, GPIO PD I/O direction byte 1 +#define R8_PD_DIR_2 (*((volatile uint8_t *)0x404000C2)) // RW, GPIO PD I/O direction byte 2 +#define R8_PD_DIR_3 (*((volatile uint8_t *)0x404000C3)) // RW, GPIO PD I/O direction byte 3 +#define R32_PD_PIN (*((volatile uint32_t *)0x404000C4)) // RO, GPIO PD input +#define R8_PD_PIN_0 (*((volatile uint8_t *)0x404000C4)) // RO, GPIO PD input byte 0 +#define R8_PD_PIN_1 (*((volatile uint8_t *)0x404000C5)) // RO, GPIO PD input byte 1 +#define R8_PD_PIN_2 (*((volatile uint8_t *)0x404000C6)) // RO, GPIO PD input byte 2 +#define R8_PD_PIN_3 (*((volatile uint8_t *)0x404000C7)) // RO, GPIO PD input byte 3 +#define R32_PD_OUT (*((volatile uint32_t *)0x404000C8)) // RW, GPIO PD output +#define R8_PD_OUT_0 (*((volatile uint8_t *)0x404000C8)) // RW, GPIO PD output byte 0 +#define R8_PD_OUT_1 (*((volatile uint8_t *)0x404000C9)) // RW, GPIO PD output byte 1 +#define R8_PD_OUT_2 (*((volatile uint8_t *)0x404000CA)) // RW, GPIO PD output byte 2 +#define R8_PD_OUT_3 (*((volatile uint8_t *)0x404000CB)) // RW, GPIO PD output byte 3 +#define R32_PD_PU (*((volatile uint32_t *)0x404000D0)) // RW, GPIO PD pullup resistance enable +#define R8_PD_PU_0 (*((volatile uint8_t *)0x404000D0)) // RW, GPIO PD pullup resistance enable 0 +#define R8_PD_PU_1 (*((volatile uint8_t *)0x404000D1)) // RW, GPIO PD pullup resistance enable 1 +#define R8_PD_PU_2 (*((volatile uint8_t *)0x404000D2)) // RW, GPIO PD pullup resistance enable 2 +#define R8_PD_PU_3 (*((volatile uint8_t *)0x404000D3)) // RW, GPIO PD pullup resistance enable 3 +#define R32_PD_PD (*((volatile uint32_t *)0x404000D4)) // RW, GPIO PD pulldown resistance enable +#define R8_PD_PD_0 (*((volatile uint8_t *)0x404000D4)) // RW, GPIO PD pulldown resistance enable 0 +#define R8_PD_PD_1 (*((volatile uint8_t *)0x404000D5)) // RW, GPIO PD pulldown resistance enable 1 +#define R8_PD_PD_2 (*((volatile uint8_t *)0x404000D6)) // RW, GPIO PD pulldown resistance enable 2 +#define R8_PD_PD_3 (*((volatile uint8_t *)0x404000D7)) // RW, GPIO PD pulldown resistance enable 3 + +/* GPIO register address offset and bit define */ +#define BA_PA ((volatile uint8_t *)0x40400080) // point GPIO PA base address +#define BA_PB ((volatile uint8_t *)0x404000A0) // point GPIO PB base address +#define BA_PD ((volatile uint8_t *)0x404000C0) // point GPIO PD base address +#define GPIO_DIR 0x00 +#define GPIO_DIR_0 0x00 +#define GPIO_DIR_1 0x01 +#define GPIO_DIR_2 0x02 +#define GPIO_DIR_3 0x03 +#define GPIO_PIN 0x04 +#define GPIO_PIN_0 0x04 +#define GPIO_PIN_1 0x05 +#define GPIO_PIN_2 0x06 +#define GPIO_PIN_3 0x07 +#define GPIO_OUT 0x08 +#define GPIO_OUT_0 0x08 +#define GPIO_OUT_1 0x09 +#define GPIO_OUT_2 0x0A +#define GPIO_OUT_3 0x0B +#define GPIO_CLR 0x0C +#define GPIO_CLR_0 0x0C +#define GPIO_CLR_1 0x0D +#define GPIO_CLR_2 0x0E +#define GPIO_CLR_3 0x0F +#define GPIO_PU 0x10 +#define GPIO_PU_0 0x10 +#define GPIO_PU_1 0x11 +#define GPIO_PU_2 0x12 +#define GPIO_PU_3 0x13 +#define GPIO_PD 0x14 +#define GPIO_PD_0 0x14 +#define GPIO_PD_1 0x15 +#define GPIO_PD_2 0x16 +#define GPIO_PD_3 0x17 +#define RB_PD_15_8 0x01 // RW, GPIO PD[15:8] pullup resistance enable together +#define RB_PD_23_16 0x01 // RW, GPIO PD[23:16] pullup resistance enable together +#define RB_PD_31_24 0x01 // RW, GPIO PD[31:24] pullup resistance enable together + +/*AF remap and debug I/O configuration register (AFIO_PCFR1)*/ +#define R32_AFIO_PCFR1 (*((volatile uint32_t *)0x40400140)) //AF remap and debug I/O configuration register (AFIO_PCFR1) +#define MASK_LINK_LED_RM 0xc0000000 //LINK LED remapping +#define MASK_SLV_RW_RM 0x30000000 //SLV remapping +#define MASK_SLV_DATA_RM 0x0c000000 //SLV data remapping +#define MASK_SLV_ADDR1_RM 0x03000000 //SLV address1 remapping +#define MASK_SLV_ADDR_RM 0x00c00000 //SLV command data selection input pin remapping +#define MASK_SLV_CS_RM 0x00300000 //SLV piece selection pin remapping +#define MASK_SLV_INTERRUPT_RM 0x000c0000 //SLV interrupt pin remapping +#define MASK_I2C_RM 0x00030000 //I2C remapping +#define MASK_UART2_MODEM_RM 0x0000c000 //UART2 MODEM remapping +#define MASK_UART1_MODEM_RM 0x00003000 //UART1 MODEM remapping +#define MASK_UART0_MODEM_RM 0x00000c00 //UART0 MODEM remapping +#define MASK_UART3_RM 0x00000300 //UART3 remapping +#define MASK_UART2_RM 0x000000c0 //UART2 remapping +#define MASK_UART1_RM 0x00000030 //UART1 remapping +#define MASK_UART0_RM 0x0000000c //UART0 remapping +#define MASK_SPI0_RM 0x00000003 //SPI0 remapping +/*AF remap and debug I/O configuration register (AFIO_PCFR2)*/ +#define R32_AFIO_PCFR2 (*((volatile uint32_t *)0x40400160)) //AF remap and debug I/O configuration register (AFIO_PCFR2) +#define UART3_MODEM 0x000c0000 //UART3 MODEM remapping +#define TNOW3_RM 0x00030000 //TNOW3 remapping +#define TNOW2_RM 0x0000c000 //TNOW2 remapping +#define TNOW1_RM 0x00003000 //TNOW1 remapping +#define TNOW0_RM 0x00000c00 //TNOW0 remapping +#define SPI1_RM 0x00000300 //UART3 remapping +#define BUSY_RM 0x00000040 //BUSY remapping +#define TIMER1_RM 0x00000020 //TIMER1 remapping +#define TIMER0_RM 0x00000010 //TIMER0 remapping +#define RST_RM 0x0000000c //reset pin remapping +#define ACT_LED_RM 0x00000003 //active led remapping + +/*Configure the extended control register 0*/ +#define R32_EXTEN_CTLR0 (*((volatile uint32_t *)0x40400144)) //Configure the extended control register 0 +#define RB_CORE_PROT_STATUS 0x40000000 //Core protected moed status bit +#define RB_CORE_HALT_INT_EN 0x02000000 //Kernel error interrupt enabled +#define RB_RST_DLEAY_EN 0x01000000 //reset time extension control bit +#define RB_XI_STATUS 0x00800000 //XI STATUS +#define RB_USBPLLON 0x00400000 //USBPLL clock enable bit +#define RB_FLASH_PRE_EN 0x00200000 //flash clock pre-divisor enable +#define RB_ETHRST 0x00080000 //ethernet reset control +#define RB_DIG_ETH_PHY_RST 0x00020000 //ethernet phy digital module reset control +#define RB_ANA_ETH_PHY_RST 0x00010000 //ethernet phy analog module reset control +#define RB_USBPLLCLK 0x0000c000 //USBPLL input clock frequency selection +#define RB_RST_CMD_EN 0x00002000 //global reset enabled +#define RB_BUSY_EN 0x00001000 //the busy signal output of spi and slv enabled +#define RB_TNOW3_EN 0x00000800 //the TNOW signal output of the UART3 is enabled +#define RB_TNOW2_EN 0x00000400 //the TNOW signal output of the UART2 is enabled +#define RB_TNOW1_EN 0x00000200 //the TNOW signal output of the UART1 is enabled +#define RB_TNOW0_EN 0x00000100 //the TNOW signal output of the UART0 is enabled +#define RB_SW 0x00000080 //select the systemitem clock source +#define RB_USBPLLSRC 0x00000060 //USBPLL reference clock source +#define RB_SW_CFG 0x00000001 //Serial wire JTAG configuration +/*Configure the extended control register 1*/ +#define R32_EXTEN_CTLR1 (*((volatile uint32_t *)0x40400154)) //Configure the extended control register 1 +#define RB_VIO_PWN_INT_EN 0x00800000 //Enables an outage when the VIO power is down +#define RB_VIO_PWN_RST_EN 0x00400000 //Enable system reset when the VIO power is down +#define RB_VIO_PWN_IO_EN 0x00200000 //Enable the IO port of the peripheral to input a high levelwhen the VIO power is down +#define RB_LDO_SLP_EN 0x00100000 //Enable the LDO to go into sleep mode when the VIO power isdown +#define RB_CLKSEL 0x00080000 //Clock signal selection +#define RB_HSE_STATUS 0x00008000 //External crystal current level status +#define RB_VIO_RDY 0x00000080 //VIO status +#define RB_HSION 0x00000040 //Internal High Speed clock enable +#define RB_HSEON 0x00000020 //External High Speed clock enable +/*Configure the extended control register 2*/ +#define R32_EXTEN_CTLR2 (*((volatile uint32_t *)0x4040016c)) //Configure the extended control register 2 +#define RB_XIXO_GPIO_EN 0x02000000 //XI/XO pin open-drain_ouput control bit +#define RB_XO_OE 0x01000000 //XO ouput enable bit +#define RB_XI_OE 0x00800000 //XI ouput enable bit +#define RB_USBPD_IN_HVT1 0x00000002 //PD PIN PB19 high threshold input mode +#define RB_USBPD_IN_HVT0 0x00000001 //PD PIN PB18 high threshold input mode + +/*flash data manipulation register */ +#define R8_SPI_FLASH_DATA (*((volatile uint8_t *)0x40400018)) //flash data manipulation register +/*Flash control register*/ +#define R8_SPI_FLASH_CTRL (*((volatile uint8_t *)0x4040001a)) //Flash control register +#define RB_FLASH_RD_EN 0x04 //The software reads the FLASH function enable bit +#define RB_FLASH_OE 0x02 //Flash output enable +#define RB_FLASH_CS 0x01 //Flash slice bit selection was enabled +/*CodeFlash key buffer register*/ +#define R16_FLASHA_KEY_BUF (*((volatile uint16_t *)0x40400168)) //CodeFlash key buffer register +#define R16_FLASHB_KEY_BUF (*((volatile uint16_t *)0x4040016A)) //CodeFlash key buffer register + +/* GPIO alias name */ +#define TWP0 (1 << 4) // PA4 +#define TWP1 (1 << 5) // PA5 +#define TACK (1 << 6) // PA6 +#define TDO (1 << 7) // PA7 +#define TRST (1 << 9) // PA9 +#define TDI (1 << 13) // PA13 +#define TCK (1 << 14) // PA14 +#define TMS (1 << 15) // PA15 +#define UID (1 << 8) // PA8 +#define SLVI (1 << 9) // PA9 +#define PIN_PARA_A0 (1 << 10) // PA10 +#define PIN_PARA_PCS (1 << 11) // PA11 +#define TNOW0 (1 << 7) // PA7 +#define DTR0 (1 << 7) // PA7 +#define RTS0 (1 << 8) // PA8 +#define CTS0 (1 << 12) // PA12 +#define DSR0 (1 << 13) // PA13 +#define RI0 (1 << 14) // PA14 +#define DCD0 (1 << 15) // PA15 +#define CTS1 (1 << 16) // PA16 +#define RTS1 (1 << 17) // PA17 +#define TNOW1 (1 << 17) // PA17 +#define ELED (1 << 13) // PA13 +#define ELINK (1 << 18) // PA18 +#define VBUS (1 << 19) // PA19 +#define PRD (1 << 20) // PA20 +#define PIN_PARA_RD (1 << 20) +#define PWR_314 (1 << 21) // PA21 +#define PIN_PARA_WR (1 << 21) +#define CTS0X (1 << 0) // PB0 +#define DSR0X (1 << 1) // PB1 +#define RI0X (1 << 2) // PB2 +#define DCD0X (1 << 3) // PB3 +#define DTR0X (1 << 4) // PB4 +#define RTS0X (1 << 5) // PB5 +#define TRAN0 (1 << 0) // PB0 +#define RECV0 (1 << 1) // PB1 +#define TRAN1 (1 << 2) // PB2 +#define RECV1 (1 << 3) // PB3 +#define PWM0 (1 << 0) // PB0 +#define CAT0 (1 << 1) // PB1 +/* note: PB1/CAT0 will input from PECL if RB_MISC_PECL_EN=1 and TMR0.RB_TMR_OUT_EN=1 */ +#define PWM1 (1 << 2) // PB2 +#define CAT1 (1 << 3) // PB3 +#define PWM2 (1 << 4) // PB4 +#define CAT2 (1 << 5) // PB5 +#define PWM3 (1 << 6) // PB6 +#define CAT3 (1 << 6) // PB6 +#define RXD0 (1 << 8) // PB8 +#define TXD0 (1 << 9) // PB9 +#define RXD1 (1 << 10) // PB10 +/* note: PB10/RXD1 will input from PECL if RB_MISC_PECL_EN=1 and TMR0.RB_TMR_OUT_EN=0 */ +#define RXTX1 (1 << 10) // PB10 +#define TXD1 (1 << 11) // PB11 + +#define SCS (1 << 12) // PB12 +#define SCK0 (1 << 13) // PB13 +#define MOSI (1 << 14) // PB14 +#define MISO (1 << 15) // PB15 +#define SDX0 (1 << 15) // PB15 +#define ADCS (1 << 16) // PB16 +#define SCK1 (1 << 17) // PB17 +#define SDO (1 << 18) // PB18 +#define SDI (1 << 19) // PB19 +#define SDX1 (1 << 19) // PB19 +#define RXD2 (1 << 28) // PD28 +#define TXD2 (1 << 29) // PD29 +#define RXD3 (1 << 22) // PD22 +#define TXD3 (1 << 23) + +/* ADC register */ +#define R32_ADC_CONTROL (*((volatile uint32_t *)0x4040A000)) // RW, ADC control +#define R8_ADC_CTRL_MOD (*((volatile uint8_t *)0x4040A000)) // RW, ADC mode control +#define R8_ADC_CTRL_DMA (*((volatile uint8_t *)0x4040A001)) // RW, ADC DMA control and etc. +#define R8_ADC_INTER_EN (*((volatile uint8_t *)0x4040A002)) // RW, ADC interrupt enable +#define R8_ADC_CLOCK_DIV (*((volatile uint8_t *)0x4040A003)) // RW, ADC clock divisor +#define R32_ADC_STATUS (*((volatile uint32_t *)0x4040A004)) // RW, ADC status +#define R16_ADC_DATA (*((volatile uint16_t *)0x4040A004)) // RO, ADC result data +#define R8_ADC_INT_FLAG (*((volatile uint8_t *)0x4040A006)) // RW1, ADC interrupt flag +#define R8_ADC_FIFO_COUNT (*((volatile uint8_t *)0x4040A007)) // RO, ADC FIFO count status +#define R32_ADC_CTRL (*((volatile uint32_t *)0x4040A008)) // RO, ADC control register +#define R16_ADC_CMP_VALUE (*((volatile uint16_t *)0x4040A00C)) // RW, ADC comparison reference value +#define R16_ADC_FIFO (*((volatile uint16_t *)0x4040A010)) // RO, ADC FIFO register +#define R32_ADC_DMA_NOW (*((volatile uint32_t *)0x4040A014)) // RW, ADC DMA current address +#define R32_ADC_DMA_BEG (*((volatile uint32_t *)0x4040A018)) // RW, ADC DMA begin address +#define R32_ADC_DMA_END (*((volatile uint32_t *)0x4040A01C)) // RW, ADC DMA end address + +/* ADC register address offset and bit define */ +#define ADC_FIFO_SIZE 8 // ADC FIFO size (depth) +#define BA_ADC ((volatile uint8_t *)0x4040A000) // point ADC base address +#define ADC_CTRL_MOD 0 +#define RB_ADC_CYCLE_CLK 0x0F // RW, ADC cycle bit mask (clock number): 0=manual sample, other=set cycle for auto sample +#define RB_ADC_CHAN_MOD 0x30 // RW, ADC channel control mode: 00=0#, 01=1#, 10=2#, 11=auto flip 0#/1# +#define RB_ADC_SAMPLE_WID 0x40 // RW, ADC sample pulse width: 0=1 clock, 1=2 clock +#define RB_ADC_POWER_ON 0x80 // RW, ADC module enable +#define ADC_CTRL_DMA 1 +#define RB_ADC_DMA_ENABLE 0x01 // RW, ADC DMA enable +#define RB_ADC_DMA_BURST 0x02 // RW, ADC DMA burst enable +#define RB_ADC_DMA_LOOP 0x04 // RW, ADC DMA address loop enable +#define RB_ADC_CHAN_OE 0x40 // WO, ADC channel control output enable +#define RB_ADC_MAN_SAMPLE 0x80 // RW, ADC manual sample control, high action +#define ADC_INTER_EN 2 +#define RB_ADC_IE_ADC_CMP 0x01 // RW, enable interrupt for current ADC comparison action +#define RB_ADC_IE_ADC_END 0x02 // RW, enable interrupt for current ADC end +#define RB_ADC_IE_FIFO_HF 0x04 // RW, enable interrupt for ADC FIFO half +#define RB_ADC_IE_DMA_END 0x08 // RW, enable interrupt for ADC DMA completion +#define RB_ADC_IE_FIFO_OV 0x10 // RW, enable interrupt for ADC FIFO overflow +#define RB_ADC_IE_DMA_ERR 0x20 // RW, enable interrupt for ADC DMA respond error +#define RB_ADC_CMP_MOD_EQ 0x40 // RW, ADC equal comparison enable: 0=exclude equal, 1=include equal +#define RB_ADC_CMP_MOD_GT 0x80 // RW, ADC comparison mode: 0=less action, 1=great action +#define ADC_CLOCK_DIV 3 +#define ADC_DATA 4 +#define ADC_INT_FLAG 6 +#define RB_ADC_IF_ADC_CMP 0x01 // RW1, interrupt flag for current ADC comparison action +#define RB_ADC_IF_ADC_END 0x02 // RW1, interrupt flag for current ADC end +#define RB_ADC_IF_FIFO_HF 0x04 // RW1, interrupt flag for ADC FIFO half +#define RB_ADC_IF_DMA_END 0x08 // RW1, interrupt flag for ADC DMA completion +#define RB_ADC_IF_FIFO_OV 0x10 // RW1, interrupt flag for ADC FIFO overflow +#define RB_ADC_IF_DMA_ERR 0x20 // RW1, interrupt flag for ADC DMA respond error +#define RB_ADC_EOC_FLAG 0x40 // RO, current ADC converter end indicator +#define RB_ADC_CHAN_INDEX 0x80 // RO, current ADC channel number for auto flip: 0=0#/2#, 1=1# +#define ADC_FIFO_COUNT 7 +#define ADC_CTRL 8 +#define MASK_ADC_CTL_MOD1 0x0000000f //Corresponding channel +#define MASK_ADC_SMAPLE_TIME 0x01fffff0 //ADC sampling and calibration time +#define MASK_ADC_CYCLE_BIT_4_6 0x0e000000 //Position 4-6 of the automatic sampling period +#define MASK_ADC_BIT_MODE 0x10000000 //ADC resolution selection bit +#define ADC_CMP_VALUE 0x0C +#define ADC_FIFO 0x10 +#define MASK_ADC_DMA_ADDR 0x0003ffff + +/* UART0 register */ +#define R8_UART0_RBR (*((volatile uint8_t *)0x4040D000)) // RO, UART0 receiver buffer, receiving byte +#define R8_UART0_THR (*((volatile uint8_t *)0x4040D000)) // WO, UART0 transmitter holding, transmittal byte +#define R8_UART0_IER (*((volatile uint8_t *)0x4040D001)) // RW, UART0 interrupt enable +#define R8_UART0_IIR (*((volatile uint8_t *)0x4040D002)) // RO, UART0 interrupt identification +#define R8_UART0_FCR (*((volatile uint8_t *)0x4040D002)) // WO, UART0 FIFO control +#define R8_UART0_LCR (*((volatile uint8_t *)0x4040D003)) // RW, UART0 line control +#define R8_UART0_MCR (*((volatile uint8_t *)0x4040D004)) // RW, UART0 modem control +#define R8_UART0_LSR (*((volatile uint8_t *)0x4040D005)) // RO, UART0 line status +#define R8_UART0_MSR (*((volatile uint8_t *)0x4040D006)) // RO, UART0 modem status +#define R8_UART0_DIV (*((volatile uint8_t *)0x4040D007)) // RW, UART0 pre-divisor latch byte, only low 7 bit, from 1 to 0/128 +#define R8_UART0_DMA_CTRL (*((volatile uint8_t *)0x4040d008)) // RW, DMA Control register +#define R8_UART0_DMA_IF (*((volatile uint8_t *)0x4040d009)) // RW, DMA status register +#define R32_UART0_DMA_WR_NOW_ADDR (*((volatile uint32_t *)0x4040d00c)) //DMA receive mode current address register +#define R32_UART0_DMA_WR_START_ADDR (*((volatile uint32_t *)0x4040d010)) //DMA receive mode start address register +#define R32_UART0_DMA_WR_END_ADDR (*((volatile uint32_t *)0x4040d014)) //DMA received mode end address register +#define R32_UART0_DMA_RD_NOW_ADDR (*((volatile uint32_t *)0x4040d018)) //DMA send mode current address register +#define R32_UART0_DMA_RD_START_ADDR (*((volatile uint32_t *)0x4040d01c)) //DMA send mode start address register +#define R32_UART0_DMA_RD_END_ADDR (*((volatile uint32_t *)0x4040d020)) //DMA send mode end address register +#define R8_UART0_DLL (*((volatile uint8_t *)0x4040D000)) // RW, UART0 divisor latch LSB byte +#define R8_UART0_DLM (*((volatile uint8_t *)0x4040D001)) // RW, UART0 divisor latch MSB byte + +/* UART1 register */ +#define R8_UART1_RBR (*((volatile uint8_t *)0x4040D800)) // RO, UART1 receiver buffer, receiving byte +#define R8_UART1_THR (*((volatile uint8_t *)0x4040D800)) // WO, UART1 transmitter holding, transmittal byte +#define R8_UART1_IER (*((volatile uint8_t *)0x4040D801)) // RW, UART1 interrupt enable +#define R8_UART1_IIR (*((volatile uint8_t *)0x4040D802)) // RO, UART1 interrupt identification +#define R8_UART1_FCR (*((volatile uint8_t *)0x4040D802)) // WO, UART1 FIFO control +#define R8_UART1_LCR (*((volatile uint8_t *)0x4040D803)) // RW, UART1 line control +#define R8_UART1_MCR (*((volatile uint8_t *)0x4040D804)) // RW, UART1 modem control +#define R8_UART1_LSR (*((volatile uint8_t *)0x4040D805)) // RO, UART1 line status +#define R8_UART1_MSR (*((volatile uint8_t *)0x4040D806)) // RO, UART1 modem status +#define R8_UART1_DIV (*((volatile uint8_t *)0x4040D807)) // RW, UART1 pre-divisor latch byte, only low 7 bit, from 1 to 0/128 +#define R8_UART1_DMA_CTRL (*((volatile uint8_t *)0x4040d808)) // RW, DMA Control register +#define R8_UART1_DMA_IF (*((volatile uint8_t *)0x4040d809)) // RW, DMA status register +#define R32_UART1_DMA_WR_NOW_ADDR (*((volatile uint32_t *)0x4040d80c)) //DMA receive mode current address register +#define R32_UART1_DMA_WR_START_ADDR (*((volatile uint32_t *)0x4040d810)) //DMA receive mode start address register +#define R32_UART1_DMA_WR_END_ADDR (*((volatile uint32_t *)0x4040d814)) //DMA received mode end address register +#define R32_UART1_DMA_RD_NOW_ADDR (*((volatile uint32_t *)0x4040d818)) //DMA send mode current address register +#define R32_UART1_DMA_RD_START_ADDR (*((volatile uint32_t *)0x4040d81c)) //DMA send mode start address register +#define R32_UART1_DMA_RD_END_ADDR (*((volatile uint32_t *)0x4040d820)) //DMA send mode end address register +#define R8_UART1_DLL (*((volatile uint8_t *)0x4040D800)) // RW, UART1 divisor latch LSB byte +#define R8_UART1_DLM (*((volatile uint8_t *)0x4040D801)) // RW, UART1 divisor latch MSB byte + +/* UART2 register */ +#define R8_UART2_RBR (*((volatile uint8_t *)0x40409000)) // RO, UART2 receiver buffer, receiving byte +#define R8_UART2_THR (*((volatile uint8_t *)0x40409000)) // WO, UART2 transmitter holding, transmittal byte +#define R8_UART2_IER (*((volatile uint8_t *)0x40409001)) // RW, UART2 interrupt enable +#define R8_UART2_IIR (*((volatile uint8_t *)0x40409002)) // RO, UART2 interrupt identification +#define R8_UART2_FCR (*((volatile uint8_t *)0x40409002)) // WO, UART2 FIFO control +#define R8_UART2_LCR (*((volatile uint8_t *)0x40409003)) // RW, UART2 line control +#define R8_UART2_MCR (*((volatile uint8_t *)0x40409004)) // RW, UART2 modem control +#define R8_UART2_LSR (*((volatile uint8_t *)0x40409005)) // RO, UART2 line status +#define R8_UART2_MSR (*((volatile uint8_t *)0x40409006)) // RO, UART2 modem status +#define R8_UART2_DIV (*((volatile uint8_t *)0x40409007)) // RW, UART2 pre-divisor latch byte, only low 7 bit, from 1 to 0/128 +#define R8_UART2_DMA_CTRL (*((volatile uint8_t *)0x40409008)) // RW, DMA Control register +#define R8_UART2_DMA_IF (*((volatile uint8_t *)0x40409009)) // RW, DMA status register +#define R32_UART2_DMA_WR_NOW_ADDR (*((volatile uint32_t *)0x4040900c)) //DMA receive mode current address register +#define R32_UART2_DMA_WR_START_ADDR (*((volatile uint32_t *)0x40409010)) //DMA receive mode start address register +#define R32_UART2_DMA_WR_END_ADDR (*((volatile uint32_t *)0x40409014)) //DMA received mode end address register +#define R32_UART2_DMA_RD_NOW_ADDR (*((volatile uint32_t *)0x40409018)) //DMA send mode current address register +#define R32_UART2_DMA_RD_START_ADDR (*((volatile uint32_t *)0x4040901c)) //DMA send mode start address register +#define R32_UART2_DMA_RD_END_ADDR (*((volatile uint32_t *)0x40409020)) //DMA send mode end address register +#define R8_UART2_DLL (*((volatile uint8_t *)0x40409000)) // RW, UART2 divisor latch LSB byte +#define R8_UART2_DLM (*((volatile uint8_t *)0x40409001)) // RW, UART2 divisor latch MSB byte + + +/* UART3 register */ +#define R8_UART3_RBR (*((volatile uint8_t *)0x40409800)) // RO, UART3 receiver buffer, receiving byte +#define R8_UART3_THR (*((volatile uint8_t *)0x40409800)) // WO, UART3 transmitter holding, transmittal byte +#define R8_UART3_IER (*((volatile uint8_t *)0x40409801)) // RW, UART3 interrupt enable +#define R8_UART3_IIR (*((volatile uint8_t *)0x40409802)) // RO, UART3 interrupt identification +#define R8_UART3_FCR (*((volatile uint8_t *)0x40409802)) // WO, UART3 FIFO control +#define R8_UART3_LCR (*((volatile uint8_t *)0x40409803)) // RW, UART3 line control +#define R8_UART3_MCR (*((volatile uint8_t *)0x40409804)) // RW, UART3 modem control +#define R8_UART3_LSR (*((volatile uint8_t *)0x40409805)) // RO, UART3 line status +#define R8_UART3_MSR (*((volatile uint8_t *)0x40409806)) // RO, UART3 modem status +#define R8_UART3_DIV (*((volatile uint8_t *)0x40409807)) // RW, UART3 pre-divisor latch byte, only low 7 bit, from 1 to 0/128 +#define R8_UART3_DMA_CTRL (*((volatile uint8_t *)0x40409808)) // RW, DMA Control register +#define R8_UART3_DMA_IF (*((volatile uint8_t *)0x40409809)) // RW, DMA status register +#define R32_UART3_DMA_WR_NOW_ADDR (*((volatile uint32_t *)0x4040980c)) //DMA receive mode current address register +#define R32_UART3_DMA_WR_START_ADDR (*((volatile uint32_t *)0x40409810)) //DMA receive mode start address register +#define R32_UART3_DMA_WR_END_ADDR (*((volatile uint32_t *)0x40409814)) //DMA received mode end address register +#define R32_UART3_DMA_RD_NOW_ADDR (*((volatile uint32_t *)0x40409818)) //DMA send mode current address register +#define R32_UART3_DMA_RD_START_ADDR (*((volatile uint32_t *)0x4040981c)) //DMA send mode start address register +#define R32_UART3_DMA_RD_END_ADDR (*((volatile uint32_t *)0x40409820)) //DMA send mode end address register +#define R8_UART3_DLL (*((volatile uint8_t *)0x40409800)) // RW, UART3 divisor latch LSB byte +#define R8_UART3_DLM (*((volatile uint8_t *)0x40409801)) // RW, UART3 divisor latch MSB byte + + +/* UART register address offset and bit define */ +#define UART_FIFO_SIZE 16 // UART0 FIFO size (depth) +#define UART_RECV_RDY_SZ 14 // the max FIFO trigger level for UART0 receiver data available +#define BA_UART0 ((volatile uint8_t *)0x4040D000) // point UART0 base address +#define BA_UART1 ((volatile uint8_t *)0x4040D800) // point UART1 base address +#define BA_UART2 ((volatile uint8_t *)0x40409000) // point UART2 base address +#define BA_UART3 ((volatile uint8_t *)0x40409800) // point UART3 base address +#define UART_RBR 0 +#define UART_THR 0 +#define UART_IER 1 +#define RB_IER_RECV_RDY 0x01 // RW, UART interrupt enable for receiver data ready +#define RB_IER_THR_EMPTY 0x02 // RW, UART interrupt enable for THR empty +#define RB_IER_LINE_STAT 0x04 // RW, UART interrupt enable for receiver line status +#define RB_IER_MODEM_CHG 0x08 // RW, UART interrupt enable for modem status change +#define RB_IER_MODEM_IO 0x10 // RW, UART0 modem pin selection: 0=from/to GPIO PA, 1=from/to GPIO PB +#define RB_IER_IRDA_MOD 0x10 // RW, UART1 IrDA mode enable +#define RB_IER_MOUT_EN 0x20 // RW, UART modem output pin enable +#define RB_IER_TXD_EN 0x40 // RW, UART TXD pin enable +#define RB_IER_RESET 0x80 // WZ, UART software reset control, high action, auto clear +#define UART_IIR 2 +#define RB_IIR_NO_INT 0x01 // RO, UART no interrupt flag: 0=interrupt action, 1=no interrupt +#define RB_IIR_INT_MASK 0x0F // RO, UART interrupt flag bit mask +#define RB_IIR_FIFO_ID 0xC0 // RO, UART FIFO enabled flag +#define UART_FCR 2 +#define RB_FCR_FIFO_EN 0x01 // WO, UART FIFO enable +#define RB_FCR_RX_FIFO_CLR 0x02 // WZ, clear UART receiver FIFO, high action, auto clear +#define RB_FCR_TX_FIFO_CLR 0x04 // WZ, clear UART transmitter FIFO, high action, auto clear +#define RB_FCR_FIFO_TRIG 0xC0 // WO, UART0/1 receiver FIFO trigger level: 00-1byte, 01-4/8bytes, 10-8/16bytes, 11-14/28bytes +#define UART_LCR 3 +#define RB_LCR_WORD_SZ 0x03 // RW, UART word bit length: 00-5bit, 01-6bit, 10-7bit, 11-8bit +#define RB_LCR_STOP_BIT 0x04 // RW, UART stop bit length: 0-1bit, 1-2bit +#define RB_LCR_PAR_EN 0x08 // RW, UART parity enable +#define RB_LCR_PAR_MOD 0x30 // RW, UART pariry mode: 00-odd, 01-even, 10-mark, 11-space +#define RB_LCR_BREAK_EN 0x40 // RW, UART break control enable +#define RB_LCR_DLAB 0x80 // RW, UART divisor latch access bit +#define UART_MCR 4 +#define RB_MCR_DTR 0x01 // RW, UART control DTR +#define RB_MCR_RTS 0x02 // RW, UART control RTS +#define RB_MCR_OUT1 0x04 // RW, UART control OUT1 +#define RB_MCR_OUT2 0x08 // RW, UART control OUT2 +#define RB_MCR_LOOP 0x10 // RW, UART0 enable local loop back +#define RB_MCR_RXTX 0x10 // RW, UART1 enable RXTX for half-duplex (TXD auto three-state output on RXD pin) +#define RB_MCR_AU_FLOW_EN 0x20 // RW, UART enable autoflow control +#define RB_MCR_TNOW 0x40 // RW, UART enable TNOW output on DTR or RTS pin +#define RB_MCR_HALF 0x80 // RW, UART enable half-duplex +#define UART_LSR 5 +#define RB_LSR_DATA_RDY 0x01 // RO, UART receiver fifo data ready status +#define RB_LSR_OVER_ERR 0x02 // RZ, UART receiver overrun error +#define RB_LSR_PAR_ERR 0x04 // RZ, UART receiver parity error +#define RB_LSR_FRAME_ERR 0x08 // RZ, UART receiver frame error +#define RB_LSR_BREAK_ERR 0x10 // RZ, UART receiver break error +#define RB_LSR_TX_FIFO_EMP 0x20 // RO, UART transmitter fifo empty status +#define RB_LSR_TX_ALL_EMP 0x40 // RO, UART transmitter all empty status +#define RB_LSR_ERR_RX_FIFO 0x80 // RO, error in UART receiver fifo +#define UART_MSR 6 +#define RB_MSR_CTS_CHG 0x01 // RZ, UART CTS changed status, high action +#define RB_MSR_DSR_CHG 0x02 // RZ, UART DSR changed status, high action +#define RB_MSR_RI_CHG 0x04 // RZ, UART RI changed status, high action +#define RB_MSR_DCD_CHG 0x08 // RZ, UART DCD changed status, high action +#define RB_MSR_CTS 0x10 // RO, UART CTS action status +#define RB_MSR_DSR 0x20 // RO, UART DSR action status +#define RB_MSR_RI 0x40 // RO, UART RI action status +#define RB_MSR_DCD 0x80 // RO, UART DCD action status +#define UART_ADR 7 +#define UART_DIV 7 +#define UART0_DMA_CTRL 8 +#define RB_DMA_WR_EN 0x01 //DMA enabled when receiving data +#define RB_DMA_WR_LOOP_EN 0x02 //DMA loop mode enabled when receiving data +#define RB_DMA_WR_END_EN 0x04 //the end of DMA interrupt when receiving data is enabled +#define RB_DMA_RD_EN 0x10 //DMA enabled when sending data +#define RB_DMA_RD_LOOP_EN 0x20 //DMA loop mode enabled when sending data +#define RB_DMA_RD_END_EN 0x40 //the end of DMA interrupt when sending data is enabled +#define UART0_DMA_IF 9 +#define RB_DMA_IF_PAR_ERR 0x02 //DMA parity error flag +#define RB_DMA_IF_TX_END 0x04 //DMA end flag when data is sended +#define RB_DMA_IF_FRAME_ERR 0x02 //DMA frame error flag +#define RB_DMA_IF_RX_END 0x01 //DMA end flag when data is received +#define UART_DLL 0 +#define UART_DLM 1 +#define MASK_UART_DMA_ADDR 0x0003ffff + +/* UART interrupt identification values for IIR bits 3:0 */ +#define UART_II_SLV_ADDR 0x0E // RO, UART1 slave address match +#define UART_II_LINE_STAT 0x06 // RO, UART interrupt by receiver line status +#define UART_II_RECV_RDY 0x04 // RO, UART interrupt by receiver data available +#define UART_II_RECV_TOUT 0x0C // RO, UART interrupt by receiver fifo timeout +#define UART_II_THR_EMPTY 0x02 // RO, UART interrupt by THR empty +#define UART_II_MODEM_CHG 0x00 // RO, UART interrupt by modem status change +#define UART_II_NO_INTER 0x01 // RO, no UART interrupt is pending + +/* SPI0 register */ +#define R32_SPI0_CONTROL (*((volatile uint32_t *)0x4040C000)) // RW, SPI0 control +#define R8_SPI0_CTRL_MOD (*((volatile uint8_t *)0x4040C000)) // RW, SPI0 mode control +#define R8_SPI0_CTRL_DMA (*((volatile uint8_t *)0x4040C001)) // RW, SPI0 DMA control +#define R8_SPI0_INTER_EN (*((volatile uint8_t *)0x4040C002)) // RW, SPI0 interrupt enable +#define R8_SPI0_CLOCK_DIV (*((volatile uint8_t *)0x4040C003)) // RW, SPI0 master clock divisor +#define R8_SPI0_SLAVE_PRE (*((volatile uint8_t *)0x4040C003)) // RW, SPI0 slave preset value +#define R32_SPI0_STATUS (*((volatile uint32_t *)0x4040C004)) // RW, SPI0 status +#define R8_SPI0_BUFFER (*((volatile uint8_t *)0x4040C004)) // RW, SPI0 data buffer +#define R8_SPI0_RUN_FLAG (*((volatile uint8_t *)0x4040C005)) // RO, SPI0 work flag +#define R8_SPI0_INT_FLAG (*((volatile uint8_t *)0x4040C006)) // RW1, SPI0 interrupt flag +#define R8_SPI0_FIFO_COUNT (*((volatile uint8_t *)0x4040C007)) // RO, SPI0 FIFO count status +#define R8_SPI0_RESET_CMD (*((volatile uint8_t *)0x4040c008)) //SPI0 reset command word register +#define R16_SPI0_TOTAL_CNT (*((volatile uint16_t *)0x4040C00C)) // RW, SPI0 total byte count, only low 12 bit +#define R32_SPI0_FIFO (*((volatile uint32_t *)0x4040C010)) // RW, SPI0 FIFO register +#define R8_SPI0_FIFO (*((volatile uint8_t *)0x4040C010)) // RO/WO, SPI0 FIFO register +#define R8_SPI0_FIFO_COUNT1 (*((volatile uint8_t *)0x4040C013)) // RO, SPI0 FIFO count status +#define R32_SPI0_DMA_NOW (*((volatile uint32_t *)0x4040C014)) // RW, SPI0 DMA current address +#define R32_SPI0_DMA_BEG (*((volatile uint32_t *)0x4040C018)) // RW, SPI0 DMA begin address +#define R32_SPI0_DMA_END (*((volatile uint32_t *)0x4040C01C)) // RW, SPI0 DMA end address + +/* SPI1 register */ +#define R32_SPI1_CONTROL (*((volatile uint32_t *)0x4040C800)) // RW, SPI1 control +#define R8_SPI1_CTRL_MOD (*((volatile uint8_t *)0x4040C800)) // RW, SPI1 mode control +#define R8_SPI1_CTRL_DMA (*((volatile uint8_t *)0x4040C801)) // RW, SPI1 DMA control +#define R8_SPI1_INTER_EN (*((volatile uint8_t *)0x4040C802)) // RW, SPI1 interrupt enable +#define R8_SPI1_CLOCK_DIV (*((volatile uint8_t *)0x4040C803)) // RW, SPI1 master clock divisor +#define R32_SPI1_STATUS (*((volatile uint32_t *)0x4040C804)) // RW, SPI1 status +#define R8_SPI1_BUFFER (*((volatile uint8_t *)0x4040C804)) // RW, SPI1 data buffer +#define R8_SPI1_RUN_FLAG (*((volatile uint8_t *)0x4040C805)) // RO, SPI1 work flag +#define R8_SPI1_INT_FLAG (*((volatile uint8_t *)0x4040C806)) // RW1, SPI1 interrupt flag +#define R8_SPI1_FIFO_COUNT (*((volatile uint8_t *)0x4040C807)) // RO, SPI1 FIFO count status +#define R16_SPI1_TOTAL_CNT (*((volatile uint16_t *)0x4040C80C)) // RW, SPI1 total byte count, only low 12 bit +#define R32_SPI1_FIFO (*((volatile uint32_t *)0x4040C810)) // RW, SPI1 FIFO register +#define R8_SPI1_FIFO (*((volatile uint8_t *)0x4040C810)) // RO/WO, SPI1 FIFO register +#define R8_SPI1_FIFO_COUNT1 (*((volatile uint8_t *)0x4040C813)) // RO, SPI1 FIFO count status + +/* SPI register address offset and bit define */ +#define SPI0_FIFO_SIZE 32 // SPI0 FIFO size (depth) +#define SPI1_FIFO_SIZE 16 // SPI1 FIFO size (depth) +#define BA_SPI0 ((volatile uint8_t *)0x4040C000) // point SPI0 base address +#define BA_SPI1 ((volatile uint8_t *)0x4040C800) // point SPI1 base address +#define SPI_CTRL_MOD 0 +#define RB_SPI_MODE_SLAVE 0x01 // RW, SPI slave mode: 0=master/host, 1=slave/device +#define RB_SPI_ALL_CLEAR 0x02 // RW, force clear SPI FIFO and count +#define RB_SPI_2WIRE_MOD 0x04 // RW, SPI enable 2 wire mode: 0=3wire(SCK,MOSI,MISO), 1=2wire(SCK,MISO=SDX) +#define RB_SPI_MST_SCK_MOD 0x08 // RW, SPI master clock mode: 0=mode 0, 1=mode 3 +#define RB_SPI_SLV_CMD_MOD 0x08 // RW, SPI slave command mode: 0=byte stream, 1=first byte command +#define RB_SPI_FIFO_DIR 0x10 // RW, SPI FIFO direction: 0=out(write @master mode), 1=in(read @master mode) +#define RB_SPI_SCK_OE 0x20 // RW, SPI SCK output enable +#define RB_SPI_MOSI_OE 0x40 // RW, SPI MOSI output enable +#define RB_SPI1_SDO_OE 0x40 // RW, SPI1 SDO output enable +#define RB_SPI_MISO_OE 0x80 // RW, SPI MISO output enable +#define RB_SPI1_SDI_OE 0x80 // RW, SPI1 SDI output enable, SPI1 enable 2 wire mode: 0=3wire(SCK1,SDO,SDI), 1=2wire(SCK1,SDX1) +#define SPI_CTRL_DMA 1 +#define RB_SPI_DMA_ENABLE 0x01 // RW, SPI DMA enable +#define RB_SPI_DMA_BURST 0x02 // RW, SPI DMA burst enable +#define RB_SPI_DMA_LOOP 0x04 // RW, SPI DMA address loop enable +#define RB_SPI_HS_HOST 0x80 // RW, High speed host receive mode control bit +#define SPI_INTER_EN 2 +#define RB_SPI_IE_CNT_END 0x01 // RW, enable interrupt for SPI total byte count end +#define RB_SPI_IE_BYTE_END 0x02 // RW, enable interrupt for SPI byte exchanged +#define RB_SPI_IE_FIFO_HF 0x04 // RW, enable interrupt for SPI FIFO half +#define RB_SPI_IE_DMA_END 0x08 // RW, enable interrupt for SPI DMA completion +#define RB_SPI_IE_FIFO_OV 0x10 // RW, enable interrupt for SPI FIFO overflow +#define RB_SPI_IE_DMA_ERR 0x20 // RW, enable interrupt for SPI DMA respond error +#define RB_SPI_IE_FST_BYTE 0x80 // RW, enable interrupt for SPI slave mode first byte received +#define SPI_CLOCK_DIV 3 +#define SPI_SLAVE_PRESET 3 +#define SPI_BUFFER 4 +#define SPI_RUN_FLAG 5 +#define RB_SPI_SLV_CMD_ACT 0x10 // RO, SPI slave command flag +#define RB_SPI_FIFO_READY 0x20 // RO, SPI FIFO ready status +#define RB_SPI_SLV_CS_LOAD 0x40 // RO, SPI slave chip-select loading status +#define RB_SPI_SLV_SELECT 0x80 // RO, SPI slave selection status +#define SPI_INT_FLAG 6 +#define RB_SPI_IF_CNT_END 0x01 // RW1, interrupt flag for SPI total byte count end +#define RB_SPI_IF_BYTE_END 0x02 // RW1, interrupt flag for SPI byte exchanged +#define RB_SPI_IF_FIFO_HF 0x04 // RW1, interrupt flag for SPI FIFO half +#define RB_SPI_IF_DMA_END 0x08 // RW1, interrupt flag for SPI DMA completion +#define RB_SPI_IF_FIFO_OV 0x10 // RW1, interrupt flag for SPI FIFO overflow +#define RB_SPI_IF_DMA_ERR 0x20 // RW1, interrupt flag for SPI DMA respond error +#define RB_SPI_FREE 0x40 // RO, current SPI free status +#define RB_SPI_IF_FST_BYTE 0x80 // RW1, interrupt flag for SPI slave mode first byte received +#define SPI_FIFO_COUNT 7 +#define SPI_TOTAL_CNT 0x0C +#define SPI_FIFO 0x10 +#define SPI0_DMA_NOW 20 +#define MASK_SPI0_DMA_ADDR 0x0003ffff //SPI DMA current address + +/* Timer0 register */ +#define R32_TMR0_CONTROL (*((volatile uint32_t *)0x40408000)) // RW, TMR0 control +#define R8_TMR0_CTRL_MOD (*((volatile uint8_t *)0x40408000)) // RW, TMR0 mode control +#define R8_TMR0_CTRL_DMA (*((volatile uint8_t *)0x40408001)) // RW, TMR0 DMA control +#define R8_TMR0_INTER_EN (*((volatile uint8_t *)0x40408002)) // RW, TMR0 interrupt enable +#define R32_TMR0_STATUS (*((volatile uint32_t *)0x40408004)) // RW, TMR0 status +#define R8_TMR0_INT_FLAG (*((volatile uint8_t *)0x40408006)) // RW1, TMR0 interrupt flag +#define R8_TMR0_FIFO_COUNT (*((volatile uint8_t *)0x40408007)) // RO, TMR0 FIFO count status +#define R32_TMR0_COUNT (*((volatile uint32_t *)0x40408008)) // RO, TMR0 current count +#define R16_TMR0_COUNT (*((volatile uint16_t *)0x40408008)) // RO, TMR0 current count +#define R8_TMR0_COUNT (*((volatile uint8_t *)0x40408008)) // RO, TMR0 current count +#define R32_TMR0_CNT_END (*((volatile uint32_t *)0x4040800C)) // RW, TMR0 end count value, only low 28 bit +#define R32_TMR0_FIFO (*((volatile uint32_t *)0x40408010)) // RO/WO, TMR0 FIFO register, only low 28 bit +#define R16_TMR0_FIFO (*((volatile uint16_t *)0x40408010)) // RO/WO, TMR0 FIFO register +#define R8_TMR0_FIFO (*((volatile uint8_t *)0x40408010)) // RO/WO, TMR0 FIFO register +#define R32_TMR0_DMA_NOW (*((volatile uint32_t *)0x40408014)) // RW, TMR0 DMA current address +#define R32_TMR0_DMA_BEG (*((volatile uint32_t *)0x40408018)) // RW, TMR0 DMA begin address +#define R32_TMR0_DMA_END (*((volatile uint32_t *)0x4040801C)) // RW, TMR0 DMA end address + +/* Timer1 register */ +#define R32_TMR1_CONTROL (*((volatile uint32_t *)0x40408400)) // RW, TMR1 control +#define R8_TMR1_CTRL_MOD (*((volatile uint8_t *)0x40408400)) // RW, TMR1 mode control +#define R8_TMR1_CTRL_DMA (*((volatile uint8_t *)0x40408401)) // RW, TMR1 DMA control +#define R8_TMR1_INTER_EN (*((volatile uint8_t *)0x40408402)) // RW, TMR1 interrupt enable +#define R8_TMR1_NRZI_CK_DIV (*((volatile uint8_t *)0x40408403)) // RW, TMR1 NRZI clock divisor, only low 4 bit, from 0 to 15 +#define R32_TMR1_STATUS (*((volatile uint32_t *)0x40408404)) // RW, TMR1 status +#define R8_TMR1_NRZI_STATUS (*((volatile uint8_t *)0x40408404)) // RO, TMR1 NRZI status +#define R8_TMR1_INT_FLAG (*((volatile uint8_t *)0x40408406)) // RW1, TMR1 interrupt flag +#define R8_TMR1_FIFO_COUNT (*((volatile uint8_t *)0x40408407)) // RO, TMR1 FIFO count status +#define R32_TMR1_COUNT (*((volatile uint32_t *)0x40408408)) // RO, TMR1 current count +#define R16_TMR1_COUNT (*((volatile uint16_t *)0x40408408)) // RO, TMR1 current count +#define R8_TMR1_COUNT (*((volatile uint8_t *)0x40408408)) // RO, TMR1 current count +#define R32_TMR1_CNT_END (*((volatile uint32_t *)0x4040840C)) // RW, TMR1 end count value, only low 28 bit +#define R32_TMR1_FIFO (*((volatile uint32_t *)0x40408410)) // RO/WO, TMR1 FIFO register, only low 28 bit +#define R16_TMR1_FIFO (*((volatile uint16_t *)0x40408410)) // RO/WO, TMR1 FIFO register +#define R8_TMR1_FIFO (*((volatile uint8_t *)0x40408410)) // RO/WO, TMR1 FIFO register +#define R32_TMR1_DMA_NOW (*((volatile uint32_t *)0x40408414)) // RW, TMR1 DMA current address +#define R32_TMR1_DMA_BEG (*((volatile uint32_t *)0x40408418)) // RW, TMR1 DMA begin address +#define R32_TMR1_DMA_END (*((volatile uint32_t *)0x4040841C)) // RW, TMR1 DMA end address + +/* Timer2 register */ +#define R32_TMR2_CONTROL (*((volatile uint32_t *)0x40408800)) // RW, TMR2 control +#define R8_TMR2_CTRL_MOD (*((volatile uint8_t *)0x40408800)) // RW, TMR2 mode control +#define R8_TMR2_CTRL_DMA (*((volatile uint8_t *)0x40408801)) // RW, TMR2 DMA control +#define R8_TMR2_INTER_EN (*((volatile uint8_t *)0x40408802)) // RW, TMR2 interrupt enable +#define R32_TMR2_STATUS (*((volatile uint32_t *)0x40408804)) // RW, TMR2 status +#define R8_TMR2_INT_FLAG (*((volatile uint8_t *)0x40408806)) // RW1, TMR2 interrupt flag +#define R8_TMR2_FIFO_COUNT (*((volatile uint8_t *)0x40408807)) // RO, TMR2 FIFO count status +#define R32_TMR2_COUNT (*((volatile uint32_t *)0x40408808)) // RO, TMR2 current count +#define R16_TMR2_COUNT (*((volatile uint16_t *)0x40408808)) // RO, TMR2 current count +#define R8_TMR2_COUNT (*((volatile uint8_t *)0x40408808)) // RO, TMR2 current count +#define R32_TMR2_CNT_END (*((volatile uint32_t *)0x4040880C)) // RW, TMR2 end count value, only low 28 bit +#define R32_TMR2_FIFO (*((volatile uint32_t *)0x40408810)) // RO/WO, TMR2 FIFO register, only low 28 bit +#define R16_TMR2_FIFO (*((volatile uint16_t *)0x40408810)) // RO/WO, TMR2 FIFO register +#define R8_TMR2_FIFO (*((volatile uint8_t *)0x40408810)) // RO/WO, TMR2 FIFO register +#define R32_TMR2_DMA_NOW (*((volatile uint32_t *)0x40408814)) // RW, TMR2 DMA current address +#define R32_TMR2_DMA_BEG (*((volatile uint32_t *)0x40408818)) // RW, TMR2 DMA begin address +#define R32_TMR2_DMA_END (*((volatile uint32_t *)0x4040881C)) // RW, TMR2 DMA end address + +/* Timer3 register */ +#define R32_TMR3_CONTROL (*((volatile uint32_t *)0x40408C00)) // RW, TMR3 control +#define R8_TMR3_CTRL_MOD (*((volatile uint8_t *)0x40408C00)) // RW, TMR3 mode control +#define R8_TMR3_INTER_EN (*((volatile uint8_t *)0x40408C02)) // RW, TMR3 interrupt enable +#define R32_TMR3_STATUS (*((volatile uint32_t *)0x40408C04)) // RW, TMR3 status +#define R8_TMR3_INT_FLAG (*((volatile uint8_t *)0x40408C06)) // RW1, TMR3 interrupt flag +#define R8_TMR3_FIFO_COUNT (*((volatile uint8_t *)0x40408C07)) // RO, TMR3 FIFO count status +#define R32_TMR3_COUNT (*((volatile uint32_t *)0x40408C08)) // RO, TMR3 current count +#define R16_TMR3_COUNT (*((volatile uint16_t *)0x40408C08)) // RO, TMR3 current count +#define R8_TMR3_COUNT (*((volatile uint8_t *)0x40408C08)) // RO, TMR3 current count +#define R32_TMR3_CNT_END (*((volatile uint32_t *)0x40408C0C)) // RW, TMR3 end count value, only low 28 bit +#define R32_TMR3_FIFO (*((volatile uint32_t *)0x40408C10)) // RO/WO, TMR3 FIFO register, only low 28 bit +#define R16_TMR3_FIFO (*((volatile uint16_t *)0x40408C10)) // RO/WO, TMR3 FIFO register +#define R8_TMR3_FIFO (*((volatile uint8_t *)0x40408C10)) // RO/WO, TMR3 FIFO register + +/* Timer register address offset and bit define */ +#define TMR_FIFO_SIZE 8 // timer FIFO size (depth) +#define BA_TMR0 ((volatile uint8_t *)0x40408000) // point TMR0 base address +#define BA_TMR1 ((volatile uint8_t *)0x40408400) // point TMR1 base address +#define BA_TMR2 ((volatile uint8_t *)0x40408800) // point TMR2 base address +#define BA_TMR3 ((volatile uint8_t *)0x40408C00) // point TMR3 base address +#define TMR_CTRL_MOD 0 +#define RB_TMR_MODE_IN 0x01 // RW, timer in mode: 0=timer/PWM/count/NRZI encode, 1=catcher/NRZI decode +#define RB_TMR_ALL_CLEAR 0x02 // RW, force clear timer FIFO and count +#define RB_TMR_COUNT_EN 0x04 // RW, timer count enable +#define RB_TMR_OUT_EN 0x08 // RW, timer output enable +#define RB_TMR_OUT_POLAR 0x10 // RW, timer PWM/NRZI encode output polarity: 0=high action, 1=low action +#define RB_TMR_CAT_WIDTH 0x10 // RW, timer catcher input pulse min width selection: 0=16*clock, 1=8*clock +#define RB_TMR_MODE_NRZI 0x20 // RW, TMR0/TMR1 NRZI mode: 0=timer/PWM/catcher, 1=NRZI encode/decode +#define RB_TMR3_MODE_COUNT 0x20 // RW, TMR3 count mode: 0=timer/PWM/catcher/NRZI, 1=count +#define RB_TMR_PWM_REPEAT 0xC0 // RW, timer PWM repeat mode: 00=1, 01=4, 10=8, 11-16 +#define RB_TMR_CATCH_EDGE 0xC0 // RW, timer catcher edge mode: 00=disable, 01=edge change, 10=fall to fall, 11-rise to rise +#define TMR_CTRL_DMA 1 +#define RB_TMR_DMA_ENABLE 0x01 // RW, timer DMA enable +#define RB_TMR_DMA_BURST 0x02 // RW, timer DMA burst enable +#define RB_TMR_DMA_LOOP 0x04 // RW, timer DMA address loop enable +#define TMR_INTER_EN 2 +#define RB_TMR_IE_CYC_END 0x01 // RW, enable interrupt for timer catcher count timeout or PWM cycle end +#define RB_TMR_IE_DATA_ACT 0x02 // RW, enable interrupt for timer catcher input action or PWM trigger or NRZI recv packet end/tran packet end +#define RB_TMR_IE_FIFO_HF 0x04 // RW, enable interrupt for timer FIFO half +#define RB_TMR_IE_DMA_END 0x08 // RW, enable interrupt for timer DMA completion +#define RB_TMR_IE_FIFO_OV 0x10 // RW, enable interrupt for timer FIFO overflow +#define RB_TMR_IE_DMA_ERR 0x20 // RW, enable interrupt for timer DMA respond error +#define RB_TMR3_FORCE_EN 0x80 // RW, TMR3 force together timer0/1/2 count enable, independent of RB_TMR_COUNT_EN +#define TMR_NRZI_CK_DIV 3 +#define TMR_NRZI_STATUS 4 +#define RB_TMR_RECV_FREE 0x01 // RO, timer NRZI receiver free status, 0->1 then RB_TMR_IF_DATA_ACT for recv +#define RB_TMR_RECV_ERR 0x02 // RO, timer NRZI receiving error status, 0->1 then RB_TMR_IF_NRZI_AUX for recv +#define RB_TMR_TRAN_END 0x10 // RO, timer NRZI transmittal end status, 0->1 then RB_TMR_IF_DATA_ACT for tran +#define RB_TMR_TRAN_DOE 0x20 // RO, timer NRZI transmitter encode output enable status, 0->1 then RB_TMR_IF_NRZI_AUX for tran +#define TMR_INT_FLAG 6 +#define RB_TMR_IF_CYC_END 0x01 // RW1, interrupt flag for timer catcher count timeout or PWM cycle end +#define RB_TMR_IF_DATA_ACT 0x02 // RW1, interrupt flag for timer catcher input action or PWM trigger or NRZI recv packet end/tran packet end +#define RB_TMR_IF_FIFO_HF 0x04 // RW1, interrupt flag for timer FIFO half +#define RB_TMR_IF_DMA_END 0x08 // RW1, interrupt flag for timer DMA completion +#define RB_TMR_IF_FIFO_OV 0x10 // RW1, interrupt flag for timer FIFO overflow +#define RB_TMR_IF_DMA_ERR 0x20 // RW1, interrupt flag for timer DMA respond error +#define TMR_FIFO_COUNT 7 +#define TMR_COUNT 0x08 +#define TMR_CNT_END 0x0C +#define TMR_FIFO 0x10 +#define TMR_DMA_NOW 0x14 +#define TMR_DMA_BEG 0x18 +#define TMR_DMA_END 0x1C +#define MASK_TMR_DMA_ADDR 0x0003ffff + +#define BA_XBUS ((uint32_t *)0x60C00000) // point XBUS base address +#define SZ_XBUS 0x00100000 // XBUS size + +#include +#include +#include "ISP564.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BITS_CFG(REGISTER,bit,en) ((en) == ENABLE ? (REGISTER |= (uint32_t)(bit)) : (REGISTER &= (uint32_t)~(bit))) + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_adc.h b/Peripheral/inc/ch564_adc.h new file mode 100644 index 0000000..3e42e6b --- /dev/null +++ b/Peripheral/inc/ch564_adc.h @@ -0,0 +1,283 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_adc.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * ADC firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_ADC_H +#define __CH564_ADC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +typedef enum +{ + ADC_Channel0 = 0x00, + ADC_Channel1, + ADC_Channel2, + ADC_Channel0_1, + ADC_Channel3, + ADC_Channel4, + ADC_Channel5, + ADC_Channel6, + ADC_ChannelREF, + ADC_ChannelCN +} ADCChannelTypedef; +/*********************************************************************************** + * @fn ADC_CMD + * + * @brief ADC Enable/Disable + * + * @param en + * - ENABLE + * - DISABLE + */ +#define ADC_CMD(en) \ + { \ + (en) == ENABLE ? (R8_ADC_CTRL_MOD |= RB_ADC_POWER_ON) : (R8_ADC_CTRL_MOD &= ~RB_ADC_POWER_ON); \ + } +/*********************************************************************************** + * @fn ADC_SET_SAMPLE_WIDTH_2CLK + * + * @brief ADC Sample time 2clk enable + * + * @param en + * - ENABLE + * - DISABLE + * @return none + */ +#define ADC_SET_SAMPLE_WIDTH_2CLK(en) \ + { \ + (en) == ENABLE ? (R8_ADC_CTRL_MOD |= RB_ADC_SAMPLE_WID) : (R8_ADC_CTRL_MOD &= RB_ADC_SAMPLE_WID); \ + } +/*********************************************************************************** + * @fn ADC_SET_SAMPLE_CYCLE + * + * @brief Config ADC sample cycle. + * + * @param val + * - val = 0:Manual Control + * - val = 0b000001 - 0b111111:Sampling every val clock + * @return none + */ +#define ADC_SET_SAMPLE_CYCLE(val) \ + ({ \ + R8_ADC_CTRL_MOD &= ~RB_ADC_CYCLE_CLK; \ + R8_ADC_CTRL_MOD |= (val) & RB_ADC_CYCLE_CLK; \ + R32_ADC_CTRL &= ~MASK_ADC_CYCLE_BIT_4_6; \ + R32_ADC_CTRL |= (((val) >> 4) << 25) & MASK_ADC_CYCLE_BIT_4_6; \ + }) +/*********************************************************************************** + * @fn ADC_DMA_CMD + * + * @brief Config the ADC DMA control and etc. + * + * @param RB_ADC_IE + * - RB_ADC_IE_ADC_CMP + * - RB_ADC_DMA_ENABLE + * - RB_ADC_DMA_BURST + * - RB_ADC_DMA_LOOP + * - RB_ADC_CHAN_OE + * - RB_ADC_MAN_SAMPLE + * + * en + * - ENABLE + * - DISABLE + * @return none + */ +#define ADC_DMA_CMD(RB_ADC_DMA, en) \ + ({ (en) == ENABLE ? (R8_ADC_CTRL_DMA |= (RB_ADC_DMA)) : (R8_ADC_CTRL_DMA &= ~(RB_ADC_DMA)); }) +/*********************************************************************************** + * @fn ADC_IT_CONFIG + * + * @brief ADC interrupt enable + * + * @param RB_ADC_IE + * - RB_ADC_IE_ADC_CMP + * - RB_ADC_IE_ADC_END + * - RB_ADC_IE_FIFO_HF + * - RB_ADC_IE_DMA_END + * - RB_ADC_IE_FIFO_OV + * - RB_ADC_IE_DMA_ERR + * - RB_ADC_CMP_MOD_EQ + * - RB_ADC_CMP_MOD_GT + * en + * - ENABLE + * - DISABLE + * @return none + */ +#define ADC_IT_CONFIG(RB_ADC_IE, en) \ + ({ (en) == ENABLE ? (R8_ADC_INTER_EN |= (RB_ADC_IE)) : (R8_ADC_INTER_EN &= ~(RB_ADC_IE)); }) +/*********************************************************************************** + * @fn ADC_SET_12BITRESOLUTION + * + * @brief ADC 12bit resolution enable + * + * @param en + * - ENABLE + * - DISABLE + * @return none + */ +#define ADC_SET_12BITRESOLUTION(en) \ + ({ (en) == ENABLE ? (R32_ADC_CTRL |= MASK_ADC_BIT_MODE) : (R32_ADC_CTRL &= ~MASK_ADC_BIT_MODE); }) +/*********************************************************************************** + * @fn ADC_SET_SAMPLE_TIME + * + * @brief Config ADC sample calibration time. + * + * @param val + * - ADC sample calibration time + * @return none + */ +#define ADC_SET_SAMPLE_TIME(val) \ + ({ \ + R32_ADC_CTRL &= ~MASK_ADC_SMAPLE_TIME; \ + R32_ADC_CTRL |= MASK_ADC_SMAPLE_TIME & ((val) << 4); \ + }) +/*********************************************************************************** + * @fn ADC_DMA_SET_RANGE + * + * @brief Config ADC DMA transport range + * + * @param startAddress + * - ADC DMA Handling Start Address + * endAddress + * - ADC DMA Handling End Address + * @return none + */ +#define ADC_DMA_SET_RANGE(startAddress, endAddress) \ + ({ \ + R32_ADC_DMA_BEG = (uint32_t)(startAddress) & MASK_ADC_DMA_ADDR; \ + R32_ADC_DMA_END = (uint32_t)(endAddress) & MASK_ADC_DMA_ADDR; \ + }) +/*********************************************************************************** + * @fn ADC_DMA_GET_CURRENT + * + * @brief Get ADC DMA current transport address + * + * @return R32_ADC_DMA_NOW + */ +#define ADC_DMA_GET_CURRENT() (R32_ADC_DMA_NOW & MASK_ADC_DMA_ADDR) +/*********************************************************************************** + * @fn ADC_DMA_GET_BEGIN + * + * @brief Get ADC DMA start transport address + * + * @return R32_ADC_DMA_BEG + */ +#define ADC_DMA_GET_BEGIN() (R32_ADC_DMA_BEG & MASK_ADC_DMA_ADDR) +/*********************************************************************************** + * @fn ADC_DMA_GET_END + * + * @brief Get ADC DMA end transport address + * + * @return R32_ADC_DMA_END + */ +#define ADC_DMA_GET_END() (R32_ADC_DMA_END & MASK_ADC_DMA_ADDR) +/*********************************************************************************** + * @fn ADC_GET_FIFO + * + * @brief Get ADC's FIFO content + * + * @return R16_ADC_FIFO + */ +#define ADC_GET_FIFO() (R16_ADC_FIFO) +/*********************************************************************************** + * @fn ADC_SET_COMPARE_VAL + * + * @brief Config ADC comparison reference value + * + * @param val + * - ADC comparison reference value + * @return none + */ +#define ADC_SET_COMPARE_VAL(val) ({ R16_ADC_CMP_VALUE = ADC_CMP_VALUE & (val); }) +/*********************************************************************************** + * @fn ADC_GET_FIFO_CNT + * + * @brief Get ADC's FIFO count + * + * @return R8_ADC_FIFO_COUNT + */ +#define ADC_GET_FIFO_CNT() (R8_ADC_FIFO_COUNT) +/*********************************************************************************** + * @fn ADC_GET_VAL + * + * @brief Get ADC's converted value + * + * @return R16_ADC_DATA + */ +#define ADC_GET_VAL() (R16_ADC_DATA) +/*********************************************************************************** + * @fn ADC_SET_DIV + * + * @brief Config ADC crossover coefficients + * + * @param val + * - ADC crossover coefficients + * @return none + */ +#define ADC_SET_DIV(value) ({ R8_ADC_CLOCK_DIV = (value); }) +/*********************************************************************************** + * @fn ADC_CLEAR_IT + * + * @brief Config ADC crossover coefficients + * + * @param RB_ADC_IF + * - RB_ADC_IF_ADC_CMP + * - RB_ADC_IF_ADC_END + * - RB_ADC_IF_FIFO_HF + * - RB_ADC_IF_DMA_END + * - RB_ADC_IF_FIFO_OV + * - RB_ADC_IF_DMA_ERR + * - RB_ADC_EOC_FLAG + * - RB_ADC_CHAN_INDEX + * en + * - ENABLE + * - DISABLE + */ +#define ADC_CLEAR_IT(RB_ADC_IF) ({ R8_ADC_INT_FLAG |= (RB_ADC_IF); }) +/*********************************************************************************** + * @fn ADC_GET_IT + * + * @brief Config ADC crossover coefficients + * + * @param RB_ADC_IF + * - RB_ADC_IF_ADC_CMP + * - RB_ADC_IF_ADC_END + * - RB_ADC_IF_FIFO_HF + * - RB_ADC_IF_DMA_END + * - RB_ADC_IF_FIFO_OV + * - RB_ADC_IF_DMA_ERR + * - RB_ADC_EOC_FLAG + * - RB_ADC_CHAN_INDEX + * @return 0:No Interrupt or interrupt flag + * + */ +#define ADC_GET_IT(RB_ADC_IF) (R8_ADC_INT_FLAG & (RB_ADC_IF)) +/*********************************************************************************** + * @fn ADC_MEASURE + * + * @brief Manually initiated measurements + * + * @return none + */ +#define ADC_MEASURE() ({ R8_ADC_CTRL_DMA |= RB_ADC_MAN_SAMPLE; }) + +void ADC_SelectChannel(ADCChannelTypedef adcChannel); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_eth.h b/Peripheral/inc/ch564_eth.h new file mode 100644 index 0000000..545477a --- /dev/null +++ b/Peripheral/inc/ch564_eth.h @@ -0,0 +1,1446 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_eth.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * ETH firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_ETH_H +#define __CH564_ETH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "ch564.h" + +#define PHY_10BASE_T_LINKED 1 +#define PHY_10BASE_T_NOT_LINKED 0 + +#define DMA_TPS_Mask ((unsigned int)0x00700000) +#define DMA_RPS_Mask ((unsigned int)0x000E0000) + +/* ETH Init structure definition */ +typedef struct { + uint32_t ETH_Watchdog; /* Selects or not the Watchdog timer + When enabled, the MAC allows no more then 2048 bytes to be received. + When disabled, the MAC can receive up to 16384 bytes. + This parameter can be a value of @ref ETH_watchdog */ + + uint32_t ETH_Jabber; /* Selects or not Jabber timer + When enabled, the MAC allows no more then 2048 bytes to be sent. + When disabled, the MAC can send up to 16384 bytes. + This parameter can be a value of @ref ETH_Jabber */ + + uint32_t ETH_InterFrameGap; /* Selects the minimum IFG between frames during transmission + This parameter can be a value of @ref ETH_Inter_Frame_Gap */ + + uint32_t ETH_ChecksumOffload; /* Selects or not the IPv4 checksum checking for received frame payloads' TCP/UDP/ICMP headers. + This parameter can be a value of @ref ETH_Checksum_Offload */ + + uint32_t ETH_AutomaticPadCRCStrip; /* Selects or not the Automatic MAC Pad/CRC Stripping + This parameter can be a value of @ref ETH_Automatic_Pad_CRC_Strip */ + + uint32_t ETH_DeferralCheck; /* Selects or not the deferral check function (Half-Duplex mode) + This parameter can be a value of @ref ETH_Deferral_Check */ + + uint32_t ETH_ReceiveAll; /* Selects or not all frames reception by the MAC (No fitering) + This parameter can be a value of @ref ETH_Receive_All */ + + uint32_t ETH_SourceAddrFilter; /* Selects the Source Address Filter mode + This parameter can be a value of @ref ETH_Source_Addr_Filter */ + + uint32_t ETH_PassControlFrames; /* Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) + This parameter can be a value of @ref ETH_Pass_Control_Frames */ + + uint32_t ETH_BroadcastFramesReception; /* Selects or not the reception of Broadcast Frames + This parameter can be a value of @ref ETH_Broadcast_Frames_Reception */ + + uint32_t ETH_DestinationAddrFilter; /* Sets the destination filter mode for both unicast and multicast frames + This parameter can be a value of @ref ETH_Destination_Addr_Filter */ + + uint32_t ETH_PromiscuousMode; /* Selects or not the Promiscuous Mode + This parameter can be a value of @ref ETH_Promiscuous_Mode */ + + uint32_t ETH_MulticastFramesFilter; /* Selects the Multicast Frames filter mode: None/HashTableFilter/PerfectFilter/PerfectHashTableFilter + This parameter can be a value of @ref ETH_Multicast_Frames_Filter */ + + uint32_t ETH_UnicastFramesFilter; /* Selects the Unicast Frames filter mode: HashTableFilter/PerfectFilter/PerfectHashTableFilter + This parameter can be a value of @ref ETH_Unicast_Frames_Filter */ + + uint32_t ETH_HashTableHigh; /* This field holds the higher 32 bits of Hash table. */ + + uint32_t ETH_HashTableLow; /* This field holds the lower 32 bits of Hash table. */ + + uint32_t ETH_PauseTime; /* This field holds the value to be used in the Pause Time field in the + transmit control frame */ + + uint32_t ETH_UnicastPauseFrameDetect; /* Selects or not the MAC detection of the Pause frames (with MAC Address0 + unicast address and unique multicast address) + This parameter can be a value of @ref ETH_Unicast_Pause_Frame_Detect */ + + uint32_t ETH_ReceiveFlowControl; /* Enables or disables the MAC to decode the received Pause frame and + disable its transmitter for a specified time (Pause Time) + This parameter can be a value of @ref ETH_Receive_Flow_Control */ + + uint32_t ETH_TransmitFlowControl; /* Enables or disables the MAC to transmit Pause frames (Full-Duplex mode) + or the MAC back-pressure operation (Half-Duplex mode) + This parameter can be a value of @ref ETH_Transmit_Flow_Control */ + + uint32_t ETH_VLANTagComparison; /* Selects the 12-bit VLAN identifier or the complete 16-bit VLAN tag for + comparison and filtering + This parameter can be a value of @ref ETH_VLAN_Tag_Comparison */ + + uint32_t ETH_VLANTagIdentifier; /* Holds the VLAN tag identifier for receive frames */ + + uint32_t ETH_DropTCPIPChecksumErrorFrame; /* Selects or not the Dropping of TCP/IP Checksum Error Frames + This parameter can be a value of @ref ETH_Drop_TCP_IP_Checksum_Error_Frame */ + + uint32_t ETH_FlushReceivedFrame; /* Enables or disables the flushing of received frames + This parameter can be a value of @ref ETH_Flush_Received_Frame */ + + uint32_t ETH_TransmitStoreForward; /* Enables or disables Transmit store and forward mode + This parameter can be a value of @ref ETH_Transmit_Store_Forward */ + + uint32_t ETH_ForwardErrorFrames; /* Selects or not the forward to the DMA of erroneous frames + This parameter can be a value of @ref ETH_Forward_Error_Frames */ + + uint32_t ETH_ForwardUndersizedGoodFrames; /* Enables or disables the Rx FIFO to forward Undersized frames (frames with no Error + and length less than 64 bytes) including pad-bytes and CRC) + This parameter can be a value of @ref ETH_Forward_Undersized_Good_Frames */ +}ETH_InitTypeDef; + +/* ETH delay.Just for Ethernet */ +#define _eth_delay_ ETH_Delay /* Default _eth_delay_ function with less precise timing */ + +/* definition for Ethernet frame */ +#define ETH_MAX_PACKET_SIZE 1536 /* ETH_HEADER + ETH_EXTRA + MAX_ETH_PAYLOAD + ETH_CRC */ +#define ETH_HEADER 14 /* 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ +#define ETH_CRC 4 /* Ethernet CRC */ +#define ETH_EXTRA 2 /* Extra bytes in some cases */ +#define VLAN_TAG 4 /* optional 802.1q VLAN Tag */ +#define MIN_ETH_PAYLOAD 46 /* Minimum Ethernet payload size */ +#define MAX_ETH_PAYLOAD 1500 /* Maximum Ethernet payload size */ +#define JUMBO_FRAME_PAYLOAD 9000 /* Jumbo frame payload size */ + +/* ETH DMA structure definition */ +typedef struct +{ + uint32_t volatile Status; /* Status */ + uint32_t ControlBufferSize; /* Control and Buffer1, Buffer2 lengths */ + uint32_t Buffer1Addr; /* Buffer1 address pointer */ + uint32_t Buffer2NextDescAddr; /* Buffer2 or next descriptor address pointer */ +} ETH_DMADESCTypeDef; + +/** + DMA Tx Desciptor + ----------------------------------------------------------------------------------------------- + TDES0 | OWN(31) | CTRL[30:26] | Reserved[25:24] | CTRL[23:20] | Reserved[19:17] | Status[16:0] | + ----------------------------------------------------------------------------------------------- + TDES1 | Reserved[31:29] | Buffer2 ByteCount[28:16] | Reserved[15:13] | Buffer1 ByteCount[12:0] | + ----------------------------------------------------------------------------------------------- + TDES2 | Buffer1 Address [31:0] | + ----------------------------------------------------------------------------------------------- + TDES3 | Buffer2 Address [31:0] / Next Desciptor Address [31:0] | + ------------------------------------------------------------------------------------------------ +*/ + + +/* Bit or field definition of TDES0 register (DMA Tx descriptor status register)*/ +#define ETH_DMATxDesc_OWN ((unsigned int)0x80000000) /* OWN bit: descriptor is owned by DMA engine */ +#define ETH_DMATxDesc_IC ((unsigned int)0x40000000) /* Interrupt on Completion */ +#define ETH_DMATxDesc_LS ((unsigned int)0x20000000) /* Last Segment */ +#define ETH_DMATxDesc_FS ((unsigned int)0x10000000) /* First Segment */ +#define ETH_DMATxDesc_DC ((unsigned int)0x08000000) /* Disable CRC */ +#define ETH_DMATxDesc_DP ((unsigned int)0x04000000) /* Disable Padding */ +#define ETH_DMATxDesc_TTSE ((unsigned int)0x02000000) /* Transmit Time Stamp Enable */ +#define ETH_DMATxDesc_CIC ((unsigned int)0x00C00000) /* Checksum Insertion Control: 4 cases */ +#define ETH_DMATxDesc_CIC_ByPass ((unsigned int)0x00000000) /* Do Nothing: Checksum Engine is bypassed */ +#define ETH_DMATxDesc_CIC_IPV4Header ((unsigned int)0x00400000) /* IPV4 header Checksum Insertion */ +#define ETH_DMATxDesc_CIC_TCPUDPICMP_Segment ((unsigned int)0x00800000) /* TCP/UDP/ICMP Checksum Insertion calculated over segment only */ +#define ETH_DMATxDesc_CIC_TCPUDPICMP_Full ((unsigned int)0x00C00000) /* TCP/UDP/ICMP Checksum Insertion fully calculated */ +#define ETH_DMATxDesc_TER ((unsigned int)0x00200000) /* Transmit End of Ring */ +#define ETH_DMATxDesc_TCH ((unsigned int)0x00100000) /* Second Address Chained */ +#define ETH_DMATxDesc_TTSS ((unsigned int)0x00020000) /* Tx Time Stamp Status */ +#define ETH_DMATxDesc_IHE ((unsigned int)0x00010000) /* IP Header Error */ +#define ETH_DMATxDesc_ES ((unsigned int)0x00008000) /* Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ +#define ETH_DMATxDesc_JT ((unsigned int)0x00004000) /* Jabber Timeout */ +#define ETH_DMATxDesc_FF ((unsigned int)0x00002000) /* Frame Flushed: DMA/MTL flushed the frame due to SW flush */ +#define ETH_DMATxDesc_PCE ((unsigned int)0x00001000) /* Payload Checksum Error */ +#define ETH_DMATxDesc_LCA ((unsigned int)0x00000800) /* Loss of Carrier: carrier lost during tramsmission */ +#define ETH_DMATxDesc_NC ((unsigned int)0x00000400) /* No Carrier: no carrier signal from the tranceiver */ +#define ETH_DMATxDesc_LCO ((unsigned int)0x00000200) /* Late Collision: transmission aborted due to collision */ +#define ETH_DMATxDesc_EC ((unsigned int)0x00000100) /* Excessive Collision: transmission aborted after 16 collisions */ +#define ETH_DMATxDesc_VF ((unsigned int)0x00000080) /* VLAN Frame */ +#define ETH_DMATxDesc_CC ((unsigned int)0x00000078) /* Collision Count */ +#define ETH_DMATxDesc_ED ((unsigned int)0x00000004) /* Excessive Deferral */ +#define ETH_DMATxDesc_UF ((unsigned int)0x00000002) /* Underflow Error: late data arrival from the memory */ +#define ETH_DMATxDesc_DB ((unsigned int)0x00000001) /* Deferred Bit */ + +/* Field definition of TDES1 register */ +#define ETH_DMATxDesc_TBS2 ((unsigned int)0x1FFF0000) /* Transmit Buffer2 Size */ +#define ETH_DMATxDesc_TBS1 ((unsigned int)0x00001FFF) /* Transmit Buffer1 Size */ + +/* Field definition of TDES2 register */ +#define ETH_DMATxDesc_B1AP ((unsigned int)0xFFFFFFFF) /* Buffer1 Address Pointer */ + +/* Field definition of TDES3 register */ +#define ETH_DMATxDesc_B2AP ((unsigned int)0xFFFFFFFF) /* Buffer2 Address Pointer */ + +/** + DMA Rx Desciptor + --------------------------------------------------------------------------------------------------------------------- + RDES0 | OWN(31) | Status [30:0] | + --------------------------------------------------------------------------------------------------------------------- + RDES1 | CTRL(31) | Reserved[30:29] | Buffer2 ByteCount[28:16] | CTRL[15:14] | Reserved(13) | Buffer1 ByteCount[12:0] | + --------------------------------------------------------------------------------------------------------------------- + RDES2 | Buffer1 Address [31:0] | + --------------------------------------------------------------------------------------------------------------------- + RDES3 | Buffer2 Address [31:0] / Next Desciptor Address [31:0] | + ---------------------------------------------------------------------------------------------------------------------- +*/ + +/* Bit or field definition of RDES0 register (DMA Rx descriptor status register) */ +#define ETH_DMARxDesc_OWN ((unsigned int)0x80000000) /* OWN bit: descriptor is owned by DMA engine */ +#define ETH_DMARxDesc_AFM ((unsigned int)0x40000000) /* DA Filter Fail for the rx frame */ +#define ETH_DMARxDesc_FL ((unsigned int)0x3FFF0000) /* Receive descriptor frame length */ +#define ETH_DMARxDesc_ES ((unsigned int)0x00008000) /* Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ +#define ETH_DMARxDesc_DE ((unsigned int)0x00004000) /* Desciptor error: no more descriptors for receive frame */ +#define ETH_DMARxDesc_SAF ((unsigned int)0x00002000) /* SA Filter Fail for the received frame */ +#define ETH_DMARxDesc_LE ((unsigned int)0x00001000) /* Frame size not matching with length field */ +#define ETH_DMARxDesc_OE ((unsigned int)0x00000800) /* Overflow Error: Frame was damaged due to buffer overflow */ +#define ETH_DMARxDesc_VLAN ((unsigned int)0x00000400) /* VLAN Tag: received frame is a VLAN frame */ +#define ETH_DMARxDesc_FS ((unsigned int)0x00000200) /* First descriptor of the frame */ +#define ETH_DMARxDesc_LS ((unsigned int)0x00000100) /* Last descriptor of the frame */ +#define ETH_DMARxDesc_IPV4HCE ((unsigned int)0x00000080) /* IPC Checksum Error: Rx Ipv4 header checksum error */ +#define ETH_DMARxDesc_LC ((unsigned int)0x00000040) /* Late collision occurred during reception */ +#define ETH_DMARxDesc_FT ((unsigned int)0x00000020) /* Frame type - Ethernet, otherwise 802.3 */ +#define ETH_DMARxDesc_RWT ((unsigned int)0x00000010) /* Receive Watchdog Timeout: watchdog timer expired during reception */ +#define ETH_DMARxDesc_RE ((unsigned int)0x00000008) /* Receive error: error reported by MII interface */ +#define ETH_DMARxDesc_DBE ((unsigned int)0x00000004) /* Dribble bit error: frame contains non int multiple of 8 bits */ +#define ETH_DMARxDesc_CE ((unsigned int)0x00000002) /* CRC error */ +#define ETH_DMARxDesc_MAMPCE ((unsigned int)0x00000001) /* Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ + +/* Bit or field definition of RDES1 register */ +#define ETH_DMARxDesc_DIC ((unsigned int)0x80000000) /* Disable Interrupt on Completion */ +#define ETH_DMARxDesc_RBS2 ((unsigned int)0x1FFF0000) /* Receive Buffer2 Size */ +#define ETH_DMARxDesc_RER ((unsigned int)0x00008000) /* Receive End of Ring */ +#define ETH_DMARxDesc_RCH ((unsigned int)0x00004000) /* Second Address Chained */ +#define ETH_DMARxDesc_RBS1 ((unsigned int)0x00001FFF) /* Receive Buffer1 Size */ + +/* Field definition of RDES2 register */ +#define ETH_DMARxDesc_B1AP ((unsigned int)0xFFFFFFFF) /* Buffer1 Address Pointer */ + +/* Field definition of RDES3 register */ +#define ETH_DMARxDesc_B2AP ((unsigned int)0xFFFFFFFF) /* Buffer2 Address Pointer */ + +/* Timeout threshold of Reading or writing PHY registers */ +#define PHY_READ_TO ((unsigned int)0x004FFFFF) +#define PHY_WRITE_TO ((unsigned int)0x0004FFFF) + +/* Delay time after reset PHY */ +#define PHY_ResetDelay ((unsigned int)0x000FFFFF) + +/* Delay time after configure PHY */ +#define PHY_ConfigDelay ((unsigned int)0x00FFFFFF) + +/********************* MACCR *********************/ + +/* MAC watchdog enable or disable */ +#define ETH_Watchdog_Enable ((unsigned int)0x00000000) +#define ETH_Watchdog_Disable ((unsigned int)0x00800000) + +/* Bit description - MAC jabber enable or disable */ +#define ETH_Jabber_Enable ((unsigned int)0x00000000) +#define ETH_Jabber_Disable ((unsigned int)0x00400000) + +/* Value of minimum IFG between frames during transmission */ +#define ETH_InterFrameGap_96Bit ((unsigned int)0x00000000) /* minimum IFG between frames during transmission is 96Bit */ +#define ETH_InterFrameGap_88Bit ((unsigned int)0x00020000) /* minimum IFG between frames during transmission is 88Bit */ +#define ETH_InterFrameGap_80Bit ((unsigned int)0x00040000) /* minimum IFG between frames during transmission is 80Bit */ +#define ETH_InterFrameGap_72Bit ((unsigned int)0x00060000) /* minimum IFG between frames during transmission is 72Bit */ +#define ETH_InterFrameGap_64Bit ((unsigned int)0x00080000) /* minimum IFG between frames during transmission is 64Bit */ +#define ETH_InterFrameGap_56Bit ((unsigned int)0x000A0000) /* minimum IFG between frames during transmission is 56Bit */ +#define ETH_InterFrameGap_48Bit ((unsigned int)0x000C0000) /* minimum IFG between frames during transmission is 48Bit */ +#define ETH_InterFrameGap_40Bit ((unsigned int)0x000E0000) /* minimum IFG between frames during transmission is 40Bit */ + +/* MAC carrier sense enable or disable */ +#define ETH_CarrierSense_Enable ((unsigned int)0x00000000) +#define ETH_CarrierSense_Disable ((unsigned int)0x00010000) + +/* MAC speed */ +#define ETH_Speed_Mask ((unsigned int)0x00004000) + +/* MAC receive own */ +#define ETH_ReceiveOwn_Mask ((unsigned int)0x00002000) + +/* MAC Duplex Mode*/ +#define ETH_Duplex_Mode_Mask ((unsigned int)0x00000800) + +/* MAC offload checksum enable or disable */ +#define ETH_ChecksumOffload_Enable ((unsigned int)0x00000400) +#define ETH_ChecksumOffload_Disable ((unsigned int)0x00000000) + +/* MAC transmission retry enable or disable */ +#define ETH_RetryTransmission_Enable ((unsigned int)0x00000000) +#define ETH_RetryTransmission_Disable ((unsigned int)0x00000200) + +/* MAC automatic pad CRC strip enable or disable */ +#define ETH_AutomaticPadCRCStrip_Enable ((unsigned int)0x00000080) +#define ETH_AutomaticPadCRCStrip_Disable ((unsigned int)0x00000000) + +/* MAC backoff limitation */ +#define ETH_BackOffLimit_10 ((unsigned int)0x00000000) +#define ETH_BackOffLimit_8 ((unsigned int)0x00000020) +#define ETH_BackOffLimit_4 ((unsigned int)0x00000040) +#define ETH_BackOffLimit_1 ((unsigned int)0x00000060) + +/* MAC deferral check enable or disable */ +#define ETH_DeferralCheck_Enable ((unsigned int)0x00000010) +#define ETH_DeferralCheck_Disable ((unsigned int)0x00000000) + +/********************* MACFFR *********************/ + +/* Bit description : MAC receive all frame enable or disable */ +#define ETH_ReceiveAll_Enable ((unsigned int)0x80000000) +#define ETH_ReceiveAll_Disable ((unsigned int)0x00000000) + +/* MAC backoff limitation */ +#define ETH_SourceAddrFilter_Normal_Enable ((unsigned int)0x00000200) +#define ETH_SourceAddrFilter_Inverse_Enable ((unsigned int)0x00000300) +#define ETH_SourceAddrFilter_Disable ((unsigned int)0x00000000) + +/* MAC Pass control frames */ +#define ETH_PassControlFrames_BlockAll ((unsigned int)0x00000040) /* MAC filters all control frames from reaching the application */ +#define ETH_PassControlFrames_ForwardAll ((unsigned int)0x00000080) /* MAC forwards all control frames to application even if they fail the Address Filter */ +#define ETH_PassControlFrames_ForwardPassedAddrFilter ((unsigned int)0x000000C0) /* MAC forwards control frames that pass the Address Filter. */ + +/* MAC broadcast frames reception */ +#define ETH_BroadcastFramesReception_Enable ((unsigned int)0x00000000) +#define ETH_BroadcastFramesReception_Disable ((unsigned int)0x00000020) + +/* MAC destination address filter */ +#define ETH_DestinationAddrFilter_Normal ((unsigned int)0x00000000) +#define ETH_DestinationAddrFilter_Inverse ((unsigned int)0x00000008) + +/* MAC Promiscuous mode enable or disable */ +#define ETH_PromiscuousMode_Enable ((unsigned int)0x00000001) +#define ETH_PromiscuousMode_Disable ((unsigned int)0x00000000) + +/* MAC multicast frames filter */ +#define ETH_MulticastFramesFilter_PerfectHashTable ((unsigned int)0x00000404) +#define ETH_MulticastFramesFilter_HashTable ((unsigned int)0x00000004) +#define ETH_MulticastFramesFilter_Perfect ((unsigned int)0x00000000) +#define ETH_MulticastFramesFilter_None ((unsigned int)0x00000010) + +/* MAC unicast frames filter */ +#define ETH_UnicastFramesFilter_PerfectHashTable ((unsigned int)0x00000402) +#define ETH_UnicastFramesFilter_HashTable ((unsigned int)0x00000002) +#define ETH_UnicastFramesFilter_Perfect ((unsigned int)0x00000000) + +/* Bit description : MAC zero quanta pause */ +#define ETH_ZeroQuantaPause_Enable ((unsigned int)0x00000000) +#define ETH_ZeroQuantaPause_Disable ((unsigned int)0x00000080) + +/* Field description : MAC pause low threshold */ +#define ETH_PauseLowThreshold_Minus4 ((unsigned int)0x00000000) /* Pause time minus 4 slot times */ +#define ETH_PauseLowThreshold_Minus28 ((unsigned int)0x00000010) /* Pause time minus 28 slot times */ +#define ETH_PauseLowThreshold_Minus144 ((unsigned int)0x00000020) /* Pause time minus 144 slot times */ +#define ETH_PauseLowThreshold_Minus256 ((unsigned int)0x00000030) /* Pause time minus 256 slot times */ + +/* MAC unicast pause frame detect enable or disable*/ +#define ETH_UnicastPauseFrameDetect_Enable ((unsigned int)0x00000008) +#define ETH_UnicastPauseFrameDetect_Disable ((unsigned int)0x00000000) + +/* MAC receive flow control frame enable or disable */ +#define ETH_ReceiveFlowControl_Enable ((unsigned int)0x00000004) +#define ETH_ReceiveFlowControl_Disable ((unsigned int)0x00000000) + +/* MAC transmit flow control enable or disable */ +#define ETH_TransmitFlowControl_Enable ((unsigned int)0x00000002) +#define ETH_TransmitFlowControl_Disable ((unsigned int)0x00000000) + +/* MAC VLAN tag comparison */ +#define ETH_VLANTagComparison_12Bit ((unsigned int)0x00010000) +#define ETH_VLANTagComparison_16Bit ((unsigned int)0x00000000) + +/* MAC flag */ +#define ETH_MAC_FLAG_TST ((unsigned int)0x00000200) /* Time stamp trigger flag (on MAC) */ +#define ETH_MAC_FLAG_MMCT ((unsigned int)0x00000040) /* MMC transmit flag */ +#define ETH_MAC_FLAG_MMCR ((unsigned int)0x00000020) /* MMC receive flag */ +#define ETH_MAC_FLAG_MMC ((unsigned int)0x00000010) /* MMC flag (on MAC) */ +#define ETH_MAC_FLAG_PMT ((unsigned int)0x00000008) /* PMT flag (on MAC) */ + +/* MAC interrupt */ +#define ETH_MAC_IT_TST ((unsigned int)0x00000200) /* Time stamp trigger interrupt (on MAC) */ +#define ETH_MAC_IT_MMCT ((unsigned int)0x00000040) /* MMC transmit interrupt */ +#define ETH_MAC_IT_MMCR ((unsigned int)0x00000020) /* MMC receive interrupt */ +#define ETH_MAC_IT_MMC ((unsigned int)0x00000010) /* MMC interrupt (on MAC) */ +#define ETH_MAC_IT_PMT ((unsigned int)0x00000008) /* PMT interrupt (on MAC) */ + +/* MAC address */ +#define ETH_MAC_Address0 ((unsigned int)0x00000000) +#define ETH_MAC_Address1 ((unsigned int)0x00000008) +#define ETH_MAC_Address2 ((unsigned int)0x00000010) +#define ETH_MAC_Address3 ((unsigned int)0x00000018) + +/* MAC address filter select */ +#define ETH_MAC_AddressFilter_SA ((unsigned int)0x00000000) +#define ETH_MAC_AddressFilter_DA ((unsigned int)0x00000008) + +/* MAC address mask */ +#define ETH_MAC_AddressMask_Byte6 ((unsigned int)0x20000000) /* Mask MAC Address high reg bits [15:8] */ +#define ETH_MAC_AddressMask_Byte5 ((unsigned int)0x10000000) /* Mask MAC Address high reg bits [7:0] */ +#define ETH_MAC_AddressMask_Byte4 ((unsigned int)0x08000000) /* Mask MAC Address low reg bits [31:24] */ +#define ETH_MAC_AddressMask_Byte3 ((unsigned int)0x04000000) /* Mask MAC Address low reg bits [23:16] */ +#define ETH_MAC_AddressMask_Byte2 ((unsigned int)0x02000000) /* Mask MAC Address low reg bits [15:8] */ +#define ETH_MAC_AddressMask_Byte1 ((unsigned int)0x01000000) /* Mask MAC Address low reg bits [70] */ + + +/******************************************************************************/ +/* */ +/* MAC Descriptor Register */ +/* */ +/******************************************************************************/ + +/* DMA descriptor segment */ +#define ETH_DMATxDesc_LastSegment ((unsigned int)0x40000000) /* Last Segment */ +#define ETH_DMATxDesc_FirstSegment ((unsigned int)0x20000000) /* First Segment */ + +/* DMA descriptor checksum setting */ +#define ETH_DMATxDesc_ChecksumByPass ((unsigned int)0x00000000) /* Checksum engine bypass */ +#define ETH_DMATxDesc_ChecksumIPV4Header ((unsigned int)0x00400000) /* IPv4 header checksum insertion */ +#define ETH_DMATxDesc_ChecksumTCPUDPICMPSegment ((unsigned int)0x00800000) /* TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ +#define ETH_DMATxDesc_ChecksumTCPUDPICMPFull ((unsigned int)0x00C00000) /* TCP/UDP/ICMP checksum fully in hardware including pseudo header */ + +/* DMA RX & TX buffer */ +#define ETH_DMARxDesc_Buffer1 ((unsigned int)0x00000000) /* DMA Rx Desc Buffer1 */ +#define ETH_DMARxDesc_Buffer2 ((unsigned int)0x00000001) /* DMA Rx Desc Buffer2 */ + + +/******************************************************************************/ +/* */ +/* ETH DMA Register */ +/* */ +/******************************************************************************/ + +/* DMA drop TCPIP checksum error frame enable or disable */ +#define ETH_DropTCPIPChecksumErrorFrame_Enable ((unsigned int)0x00000000) +#define ETH_DropTCPIPChecksumErrorFrame_Disable ((unsigned int)0x04000000) + +/* DMA receive store forward enable or disable */ +#define ETH_ReceiveStoreForward_Enable ((unsigned int)0x02000000) +#define ETH_ReceiveStoreForward_Disable ((unsigned int)0x00000000) + +/* DMA flush received frame enable or disable */ +#define ETH_FlushReceivedFrame_Enable ((unsigned int)0x00000000) +#define ETH_FlushReceivedFrame_Disable ((unsigned int)0x01000000) + +/* DMA transmit store forward enable or disable */ +#define ETH_TransmitStoreForward_Enable ((unsigned int)0x00200000) +#define ETH_TransmitStoreForward_Disable ((unsigned int)0x00000000) + +/* DMA transmit threshold control */ +#define ETH_TransmitThresholdControl_64Bytes ((unsigned int)0x00000000) /* threshold level of the MTL Transmit FIFO is 64 Bytes */ +#define ETH_TransmitThresholdControl_128Bytes ((unsigned int)0x00004000) /* threshold level of the MTL Transmit FIFO is 128 Bytes */ +#define ETH_TransmitThresholdControl_192Bytes ((unsigned int)0x00008000) /* threshold level of the MTL Transmit FIFO is 192 Bytes */ +#define ETH_TransmitThresholdControl_256Bytes ((unsigned int)0x0000C000) /* threshold level of the MTL Transmit FIFO is 256 Bytes */ +#define ETH_TransmitThresholdControl_40Bytes ((unsigned int)0x00010000) /* threshold level of the MTL Transmit FIFO is 40 Bytes */ +#define ETH_TransmitThresholdControl_32Bytes ((unsigned int)0x00014000) /* threshold level of the MTL Transmit FIFO is 32 Bytes */ +#define ETH_TransmitThresholdControl_24Bytes ((unsigned int)0x00018000) /* threshold level of the MTL Transmit FIFO is 24 Bytes */ +#define ETH_TransmitThresholdControl_16Bytes ((unsigned int)0x0001C000) /* threshold level of the MTL Transmit FIFO is 16 Bytes */ + +/* DMA forward error frames */ +#define ETH_ForwardErrorFrames_Enable ((unsigned int)0x00000080) +#define ETH_ForwardErrorFrames_Disable ((unsigned int)0x00000000) + +/* DMA forward undersized good frames enable or disable */ +#define ETH_ForwardUndersizedGoodFrames_Enable ((unsigned int)0x00000040) +#define ETH_ForwardUndersizedGoodFrames_Disable ((unsigned int)0x00000000) + +/* DMA receive threshold control */ +#define ETH_ReceiveThresholdControl_64Bytes ((unsigned int)0x00000000) /* threshold level of the MTL Receive FIFO is 64 Bytes */ +#define ETH_ReceiveThresholdControl_32Bytes ((unsigned int)0x00000008) /* threshold level of the MTL Receive FIFO is 32 Bytes */ +#define ETH_ReceiveThresholdControl_96Bytes ((unsigned int)0x00000010) /* threshold level of the MTL Receive FIFO is 96 Bytes */ +#define ETH_ReceiveThresholdControl_128Bytes ((unsigned int)0x00000018) /* threshold level of the MTL Receive FIFO is 128 Bytes */ + +/* DMA second frame operate enable or disable */ +#define ETH_SecondFrameOperate_Enable ((unsigned int)0x00000004) +#define ETH_SecondFrameOperate_Disable ((unsigned int)0x00000000) + +/* Address aligned beats enable or disable */ +#define ETH_AddressAlignedBeats_Enable ((unsigned int)0x02000000) +#define ETH_AddressAlignedBeats_Disable ((unsigned int)0x00000000) + +/* DMA Fixed burst enable or disable */ +#define ETH_FixedBurst_Enable ((unsigned int)0x00010000) +#define ETH_FixedBurst_Disable ((unsigned int)0x00000000) + + +/* RX DMA burst length */ +#define ETH_RxDMABurstLength_1Beat ((unsigned int)0x00020000) /* maximum number of beats to be transferred in one RxDMA transaction is 1 */ +#define ETH_RxDMABurstLength_2Beat ((unsigned int)0x00040000) /* maximum number of beats to be transferred in one RxDMA transaction is 2 */ +#define ETH_RxDMABurstLength_4Beat ((unsigned int)0x00080000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_RxDMABurstLength_8Beat ((unsigned int)0x00100000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_RxDMABurstLength_16Beat ((unsigned int)0x00200000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_RxDMABurstLength_32Beat ((unsigned int)0x00400000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_RxDMABurstLength_4xPBL_4Beat ((unsigned int)0x01020000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_RxDMABurstLength_4xPBL_8Beat ((unsigned int)0x01040000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_RxDMABurstLength_4xPBL_16Beat ((unsigned int)0x01080000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_RxDMABurstLength_4xPBL_32Beat ((unsigned int)0x01100000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_RxDMABurstLength_4xPBL_64Beat ((unsigned int)0x01200000) /* maximum number of beats to be transferred in one RxDMA transaction is 64 */ +#define ETH_RxDMABurstLength_4xPBL_128Beat ((unsigned int)0x01400000) /* maximum number of beats to be transferred in one RxDMA transaction is 128 */ + + +/* TX DMA burst length */ +#define ETH_TxDMABurstLength_1Beat ((unsigned int)0x00000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ +#define ETH_TxDMABurstLength_2Beat ((unsigned int)0x00000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ +#define ETH_TxDMABurstLength_4Beat ((unsigned int)0x00000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_TxDMABurstLength_8Beat ((unsigned int)0x00000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_TxDMABurstLength_16Beat ((unsigned int)0x00001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_TxDMABurstLength_32Beat ((unsigned int)0x00002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_TxDMABurstLength_4xPBL_4Beat ((unsigned int)0x01000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_TxDMABurstLength_4xPBL_8Beat ((unsigned int)0x01000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_TxDMABurstLength_4xPBL_16Beat ((unsigned int)0x01000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_TxDMABurstLength_4xPBL_32Beat ((unsigned int)0x01000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_TxDMABurstLength_4xPBL_64Beat ((unsigned int)0x01001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ +#define ETH_TxDMABurstLength_4xPBL_128Beat ((unsigned int)0x01002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ + +/* DMA arbitration_round robin */ +#define ETH_DMAArbitration_RoundRobin_RxTx_1_1 ((unsigned int)0x00000000) +#define ETH_DMAArbitration_RoundRobin_RxTx_2_1 ((unsigned int)0x00004000) +#define ETH_DMAArbitration_RoundRobin_RxTx_3_1 ((unsigned int)0x00008000) +#define ETH_DMAArbitration_RoundRobin_RxTx_4_1 ((unsigned int)0x0000C000) +#define ETH_DMAArbitration_RxPriorTx ((unsigned int)0x00000002) + +/* DMA interrupt FLAG */ +#define ETH_DMA_FLAG_TST ((unsigned int)0x20000000) /* Time-stamp trigger interrupt (on DMA) */ +#define ETH_DMA_FLAG_PMT ((unsigned int)0x10000000) /* PMT interrupt (on DMA) */ +#define ETH_DMA_FLAG_MMC ((unsigned int)0x08000000) /* MMC interrupt (on DMA) */ +#define ETH_DMA_FLAG_DataTransferError ((unsigned int)0x00800000) /* Error bits 0-Rx DMA, 1-Tx DMA */ +#define ETH_DMA_FLAG_ReadWriteError ((unsigned int)0x01000000) /* Error bits 0-write trnsf, 1-read transfr */ +#define ETH_DMA_FLAG_AccessError ((unsigned int)0x02000000) /* Error bits 0-data buffer, 1-desc. access */ +#define ETH_DMA_FLAG_NIS ((unsigned int)0x00010000) /* Normal interrupt summary flag */ +#define ETH_DMA_FLAG_AIS ((unsigned int)0x00008000) /* Abnormal interrupt summary flag */ +#define ETH_DMA_FLAG_ER ((unsigned int)0x00004000) /* Early receive flag */ +#define ETH_DMA_FLAG_FBE ((unsigned int)0x00002000) /* Fatal bus error flag */ +#define ETH_DMA_FLAG_PHYSR ((unsigned int)0x00000800) /* PHY interrupt flag */ +#define ETH_DMA_FLAG_ET ((unsigned int)0x00000400) /* Early transmit flag */ +#define ETH_DMA_FLAG_RWT ((unsigned int)0x00000200) /* Receive watchdog timeout flag */ +#define ETH_DMA_FLAG_RPS ((unsigned int)0x00000100) /* Receive process stopped flag */ +#define ETH_DMA_FLAG_RBU ((unsigned int)0x00000080) /* Receive buffer unavailable flag */ +#define ETH_DMA_FLAG_R ((unsigned int)0x00000040) /* Receive flag */ +#define ETH_DMA_FLAG_TU ((unsigned int)0x00000020) /* Underflow flag */ +#define ETH_DMA_FLAG_RO ((unsigned int)0x00000010) /* Overflow flag */ +#define ETH_DMA_FLAG_TJT ((unsigned int)0x00000008) /* Transmit jabber timeout flag */ +#define ETH_DMA_FLAG_TBU ((unsigned int)0x00000004) /* Transmit buffer unavailable flag */ +#define ETH_DMA_FLAG_TPS ((unsigned int)0x00000002) /* Transmit process stopped flag */ +#define ETH_DMA_FLAG_T ((unsigned int)0x00000001) /* Transmit flag */ + +/* DMA interrupt */ +#define ETH_DMA_IT_TST ((unsigned int)0x20000000) /* Time-stamp trigger interrupt (on DMA) */ +#define ETH_DMA_IT_PMT ((unsigned int)0x10000000) /* PMT interrupt (on DMA) */ +#define ETH_DMA_IT_MMC ((unsigned int)0x08000000) /* MMC interrupt (on DMA) */ +#define ETH_DMA_IT_NIS ((unsigned int)0x00010000) /* Normal interrupt summary */ +#define ETH_DMA_IT_AIS ((unsigned int)0x00008000) /* Abnormal interrupt summary */ +#define ETH_DMA_IT_ER ((unsigned int)0x00004000) /* Early receive interrupt */ +#define ETH_DMA_IT_FBE ((unsigned int)0x00002000) /* Fatal bus error interrupt */ +#define ETH_DMA_IT_PHYSR ((unsigned int)0x00000800) /* PHY interrupt */ +#define ETH_DMA_IT_ET ((unsigned int)0x00000400) /* Early transmit interrupt */ +#define ETH_DMA_IT_RWT ((unsigned int)0x00000200) /* Receive watchdog timeout interrupt */ +#define ETH_DMA_IT_RPS ((unsigned int)0x00000100) /* Receive process stopped interrupt */ +#define ETH_DMA_IT_RBU ((unsigned int)0x00000080) /* Receive buffer unavailable interrupt */ +#define ETH_DMA_IT_R ((unsigned int)0x00000040) /* Receive interrupt */ +#define ETH_DMA_IT_TU ((unsigned int)0x00000020) /* Underflow interrupt */ +#define ETH_DMA_IT_RO ((unsigned int)0x00000010) /* Overflow interrupt */ +#define ETH_DMA_IT_TJT ((unsigned int)0x00000008) /* Transmit jabber timeout interrupt */ +#define ETH_DMA_IT_TBU ((unsigned int)0x00000004) /* Transmit buffer unavailable interrupt */ +#define ETH_DMA_IT_TPS ((unsigned int)0x00000002) /* Transmit process stopped interrupt */ +#define ETH_DMA_IT_T ((unsigned int)0x00000001) /* Transmit interrupt */ + +/* DMA transmit process */ +#define ETH_DMA_TransmitProcess_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Tx Command issued */ +#define ETH_DMA_TransmitProcess_Fetching ((unsigned int)0x00100000) /* Running - fetching the Tx descriptor */ +#define ETH_DMA_TransmitProcess_Waiting ((unsigned int)0x00200000) /* Running - waiting for status */ +#define ETH_DMA_TransmitProcess_Reading ((unsigned int)0x00300000) /* Running - reading the data from host memory */ +#define ETH_DMA_TransmitProcess_Suspended ((unsigned int)0x00600000) /* Suspended - Tx Desciptor unavailabe */ +#define ETH_DMA_TransmitProcess_Closing ((unsigned int)0x00700000) /* Running - closing Rx descriptor */ + +/* DMA receive Process */ +#define ETH_DMA_ReceiveProcess_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Rx Command issued */ +#define ETH_DMA_ReceiveProcess_Fetching ((unsigned int)0x00020000) /* Running - fetching the Rx descriptor */ +#define ETH_DMA_ReceiveProcess_Waiting ((unsigned int)0x00060000) /* Running - waiting for packet */ +#define ETH_DMA_ReceiveProcess_Suspended ((unsigned int)0x00080000) /* Suspended - Rx Desciptor unavailable */ +#define ETH_DMA_ReceiveProcess_Closing ((unsigned int)0x000A0000) /* Running - closing descriptor */ +#define ETH_DMA_ReceiveProcess_Queuing ((unsigned int)0x000E0000) /* Running - queuing the recieve frame into host memory */ + +/* DMA overflow */ +#define ETH_DMA_Overflow_RxFIFOCounter ((unsigned int)0x10000000) /* Overflow bit for FIFO overflow counter */ +#define ETH_DMA_Overflow_MissedFrameCounter ((unsigned int)0x00010000) /* Overflow bit for missed frame counter */ + + +/********************************************************************************* +* Ethernet PMT defines +**********************************************************************************/ + +/* PMT flag */ +#define ETH_PMT_FLAG_WUFFRPR ((unsigned int)0x80000000) /* Wake-Up Frame Filter Register Poniter Reset */ +#define ETH_PMT_FLAG_WUFR ((unsigned int)0x00000040) /* Wake-Up Frame Received */ +#define ETH_PMT_FLAG_MPR ((unsigned int)0x00000020) /* Magic Packet Received */ + +/********************************************************************************* +* Ethernet MMC defines +**********************************************************************************/ + +/* MMC TX interrupt flag */ +#define ETH_MMC_IT_TGF ((unsigned int)0x00200000) /* When Tx good frame counter reaches half the maximum value */ +#define ETH_MMC_IT_TGFMSC ((unsigned int)0x00008000) /* When Tx good multi col counter reaches half the maximum value */ +#define ETH_MMC_IT_TGFSC ((unsigned int)0x00004000) /* When Tx good single col counter reaches half the maximum value */ + +/* MMC RX interrupt flag */ +#define ETH_MMC_IT_RGUF ((unsigned int)0x10020000) /* When Rx good unicast frames counter reaches half the maximum value */ +#define ETH_MMC_IT_RFAE ((unsigned int)0x10000040) /* When Rx alignment error counter reaches half the maximum value */ +#define ETH_MMC_IT_RFCE ((unsigned int)0x10000020) /* When Rx crc error counter reaches half the maximum value */ + + +/* MMC description */ +#define ETH_MMCCR ((unsigned int)0x00000100) /* MMC CR register */ +#define ETH_MMCRIR ((unsigned int)0x00000104) /* MMC RIR register */ +#define ETH_MMCTIR ((unsigned int)0x00000108) /* MMC TIR register */ +#define ETH_MMCRIMR ((unsigned int)0x0000010C) /* MMC RIMR register */ +#define ETH_MMCTIMR ((unsigned int)0x00000110) /* MMC TIMR register */ +#define ETH_MMCTGFSCCR ((unsigned int)0x0000014C) /* MMC TGFSCCR register */ +#define ETH_MMCTGFMSCCR ((unsigned int)0x00000150) /* MMC TGFMSCCR register */ +#define ETH_MMCTGFCR ((unsigned int)0x00000168) /* MMC TGFCR register */ +#define ETH_MMCRFCECR ((unsigned int)0x00000194) /* MMC RFCECR register */ +#define ETH_MMCRFAECR ((unsigned int)0x00000198) /* MMC RFAECR register */ +#define ETH_MMCRGUFCR ((unsigned int)0x000001C4) /* MMC RGUFCR register */ + + +/********************************************************************************* +* Ethernet PTP defines +**********************************************************************************/ + +/* PTP fine update method or coarse Update method */ +#define ETH_PTP_FineUpdate ((unsigned int)0x00000001) /* Fine Update method */ +#define ETH_PTP_CoarseUpdate ((unsigned int)0x00000000) /* Coarse Update method */ + + +/* PTP time stamp control */ +#define ETH_PTP_FLAG_TSARU ((unsigned int)0x00000020) /* Addend Register Update */ +#define ETH_PTP_FLAG_TSITE ((unsigned int)0x00000010) /* Time Stamp Interrupt Trigger */ +#define ETH_PTP_FLAG_TSSTU ((unsigned int)0x00000008) /* Time Stamp Update */ +#define ETH_PTP_FLAG_TSSTI ((unsigned int)0x00000004) /* Time Stamp Initialize */ + +/* PTP positive/negative time value */ +#define ETH_PTP_PositiveTime ((unsigned int)0x00000000) /* Positive time value */ +#define ETH_PTP_NegativeTime ((unsigned int)0x80000000) /* Negative time value */ + + +/******************************************************************************/ +/* */ +/* PTP Register */ +/* */ +/******************************************************************************/ +#define ETH_PTPTSCR ((unsigned int)0x00000700) /* PTP TSCR register */ +#define ETH_PTPSSIR ((unsigned int)0x00000704) /* PTP SSIR register */ +#define ETH_PTPTSHR ((unsigned int)0x00000708) /* PTP TSHR register */ +#define ETH_PTPTSLR ((unsigned int)0x0000070C) /* PTP TSLR register */ +#define ETH_PTPTSHUR ((unsigned int)0x00000710) /* PTP TSHUR register */ +#define ETH_PTPTSLUR ((unsigned int)0x00000714) /* PTP TSLUR register */ +#define ETH_PTPTSAR ((unsigned int)0x00000718) /* PTP TSAR register */ +#define ETH_PTPTTHR ((unsigned int)0x0000071C) /* PTP TTHR register */ +#define ETH_PTPTTLR ((unsigned int)0x00000720) /* PTP TTLR register */ + +#define ETH_DMASR_TSTS ((unsigned int)0x20000000) /* Time-stamp trigger status */ +#define ETH_DMASR_PMTS ((unsigned int)0x10000000) /* PMT status */ +#define ETH_DMASR_MMCS ((unsigned int)0x08000000) /* MMC status */ +#define ETH_DMASR_EBS ((unsigned int)0x03800000) /* Error bits status */ +#define ETH_DMASR_EBS_DescAccess ((unsigned int)0x02000000) /* Error bits 0-data buffer, 1-desc. access */ +#define ETH_DMASR_EBS_ReadTransf ((unsigned int)0x01000000) /* Error bits 0-write trnsf, 1-read transfr */ +#define ETH_DMASR_EBS_DataTransfTx ((unsigned int)0x00800000) /* Error bits 0-Rx DMA, 1-Tx DMA */ +#define ETH_DMASR_TPS ((unsigned int)0x00700000) /* Transmit process state */ +#define ETH_DMASR_TPS_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Tx Command issued */ +#define ETH_DMASR_TPS_Fetching ((unsigned int)0x00100000) /* Running - fetching the Tx descriptor */ +#define ETH_DMASR_TPS_Waiting ((unsigned int)0x00200000) /* Running - waiting for status */ +#define ETH_DMASR_TPS_Reading ((unsigned int)0x00300000) /* Running - reading the data from host memory */ +#define ETH_DMASR_TPS_Suspended ((unsigned int)0x00600000) /* Suspended - Tx Descriptor unavailabe */ +#define ETH_DMASR_TPS_Closing ((unsigned int)0x00700000) /* Running - closing Rx descriptor */ +#define ETH_DMASR_RPS ((unsigned int)0x000E0000) /* Receive process state */ +#define ETH_DMASR_RPS_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Rx Command issued */ +#define ETH_DMASR_RPS_Fetching ((unsigned int)0x00020000) /* Running - fetching the Rx descriptor */ +#define ETH_DMASR_RPS_Waiting ((unsigned int)0x00060000) /* Running - waiting for packet */ +#define ETH_DMASR_RPS_Suspended ((unsigned int)0x00080000) /* Suspended - Rx Descriptor unavailable */ +#define ETH_DMASR_RPS_Closing ((unsigned int)0x000A0000) /* Running - closing descriptor */ +#define ETH_DMASR_RPS_Queuing ((unsigned int)0x000E0000) /* Running - queuing the recieve frame into host memory */ +#define ETH_DMASR_NIS ((unsigned int)0x00010000) /* Normal interrupt summary */ +#define ETH_DMASR_AIS ((unsigned int)0x00008000) /* Abnormal interrupt summary */ +#define ETH_DMASR_ERS ((unsigned int)0x00004000) /* Early receive status */ +#define ETH_DMASR_FBES ((unsigned int)0x00002000) /* Fatal bus error status */ +#define ETH_DMASR_PHYSTAT ((unsigned int)0x00000800) /* PHY interrupt status */ +#define ETH_DMASR_ETS ((unsigned int)0x00000400) /* Early transmit status */ +#define ETH_DMASR_RWTS ((unsigned int)0x00000200) /* Receive watchdog timeout status */ +#define ETH_DMASR_RPSS ((unsigned int)0x00000100) /* Receive process stopped status */ +#define ETH_DMASR_RBUS ((unsigned int)0x00000080) /* Receive buffer unavailable status */ +#define ETH_DMASR_RS ((unsigned int)0x00000040) /* Receive status */ +#define ETH_DMASR_TUS ((unsigned int)0x00000020) /* Transmit underflow status */ +#define ETH_DMASR_ROS ((unsigned int)0x00000010) /* Receive overflow status */ +#define ETH_DMASR_TJTS ((unsigned int)0x00000008) /* Transmit jabber timeout status */ +#define ETH_DMASR_TBUS ((unsigned int)0x00000004) /* Transmit buffer unavailable status */ +#define ETH_DMASR_TPSS ((unsigned int)0x00000002) /* Transmit process stopped status */ +#define ETH_DMASR_TS ((unsigned int)0x00000001) /* Transmit status */ + + +/******************************************************************************/ +/* */ +/* ETH MAC Register */ +/* */ +/******************************************************************************/ +#define ETH_MACCR_WD ((unsigned int)0x00800000) /* Watchdog disable */ +#define ETH_MACCR_JD ((unsigned int)0x00400000) /* Jabber disable */ +#define ETH_MACCR_IFG ((unsigned int)0x000E0000) /* Inter-frame gap */ +#define ETH_MACCR_IFG_96Bit ((unsigned int)0x00000000) /* Minimum IFG between frames during transmission is 96Bit */ +#define ETH_MACCR_IFG_88Bit ((unsigned int)0x00020000) /* Minimum IFG between frames during transmission is 88Bit */ +#define ETH_MACCR_IFG_80Bit ((unsigned int)0x00040000) /* Minimum IFG between frames during transmission is 80Bit */ +#define ETH_MACCR_IFG_72Bit ((unsigned int)0x00060000) /* Minimum IFG between frames during transmission is 72Bit */ +#define ETH_MACCR_IFG_64Bit ((unsigned int)0x00080000) /* Minimum IFG between frames during transmission is 64Bit */ +#define ETH_MACCR_IFG_56Bit ((unsigned int)0x000A0000) /* Minimum IFG between frames during transmission is 56Bit */ +#define ETH_MACCR_IFG_48Bit ((unsigned int)0x000C0000) /* Minimum IFG between frames during transmission is 48Bit */ +#define ETH_MACCR_IFG_40Bit ((unsigned int)0x000E0000) /* Minimum IFG between frames during transmission is 40Bit */ +#define ETH_MACCR_CSD ((unsigned int)0x00010000) /* Carrier sense disable (during transmission) */ +#define ETH_MACCR_FES ((unsigned int)0x00004000) /* Fast ethernet speed */ +#define ETH_MACCR_ROD ((unsigned int)0x00002000) /* Receive own disable */ +#define ETH_MACCR_LM ((unsigned int)0x00001000) /* loopback mode */ +#define ETH_MACCR_DM ((unsigned int)0x00000800) /* Duplex mode */ +#define ETH_MACCR_IPCO ((unsigned int)0x00000400) /* IP Checksum offload */ +#define ETH_MACCR_RD ((unsigned int)0x00000200) /* Retry disable */ +#define ETH_MACCR_APCS ((unsigned int)0x00000080) /* Automatic Pad/CRC stripping */ +#define ETH_MACCR_BL ((unsigned int)0x00000060) /* Back-off limit: random integer number (r) of slot time delays before reschedulinga transmission attempt during retries after a collision: 0 =< r <2^k */ +#define ETH_MACCR_BL_10 ((unsigned int)0x00000000) /* k = min (n, 10) */ +#define ETH_MACCR_BL_8 ((unsigned int)0x00000020) /* k = min (n, 8) */ +#define ETH_MACCR_BL_4 ((unsigned int)0x00000040) /* k = min (n, 4) */ +#define ETH_MACCR_BL_1 ((unsigned int)0x00000060) /* k = min (n, 1) */ +#define ETH_MACCR_DC ((unsigned int)0x00000010) /* Defferal check */ +#define ETH_MACCR_TE ((unsigned int)0x00000008) /* Transmitter enable */ +#define ETH_MACCR_RE ((unsigned int)0x00000004) /* Receiver enable */ + +#define ETH_MACFFR_RA ((unsigned int)0x80000000) /* Receive all */ +#define ETH_MACFFR_HPF ((unsigned int)0x00000400) /* Hash or perfect filter */ +#define ETH_MACFFR_SAF ((unsigned int)0x00000200) /* Source address filter enable */ +#define ETH_MACFFR_SAIF ((unsigned int)0x00000100) /* SA inverse filtering */ +#define ETH_MACFFR_PCF ((unsigned int)0x000000C0) /* Pass control frames: 3 cases */ +#define ETH_MACFFR_PCF_BlockAll ((unsigned int)0x00000040) /* MAC filters all control frames from reaching the application */ +#define ETH_MACFFR_PCF_ForwardAll ((unsigned int)0x00000080) /* MAC forwards all control frames to application even if they fail the Address Filter */ +#define ETH_MACFFR_PCF_ForwardPassedAddrFilter ((unsigned int)0x000000C0) /* MAC forwards control frames that pass the Address Filter. */ +#define ETH_MACFFR_BFD ((unsigned int)0x00000020) /* Broadcast frame disable */ +#define ETH_MACFFR_PAM ((unsigned int)0x00000010) /* Pass all mutlicast */ +#define ETH_MACFFR_DAIF ((unsigned int)0x00000008) /* DA Inverse filtering */ +#define ETH_MACFFR_HM ((unsigned int)0x00000004) /* Hash multicast */ +#define ETH_MACFFR_HU ((unsigned int)0x00000002) /* Hash unicast */ +#define ETH_MACFFR_PM ((unsigned int)0x00000001) /* Promiscuous mode */ + +#define ETH_MACHTHR_HTH ((unsigned int)0xFFFFFFFF) /* Hash table high */ +#define ETH_MACHTLR_HTL ((unsigned int)0xFFFFFFFF) /* Hash table low */ + +#define ETH_MACMIIAR_PA ((unsigned int)0x0000F800) /* Physical layer address */ +#define ETH_MACMIIAR_MR ((unsigned int)0x000007C0) /* MII register in the selected PHY */ +#define ETH_MACMIIAR_CR ((unsigned int)0x0000001C) /* CR clock range: 6 cases */ +#define ETH_MACMIIAR_CR_Div42 ((unsigned int)0x00000000) /* HCLK:60-100 MHz; MDC clock= HCLK/42 */ +#define ETH_MACMIIAR_CR_Div16 ((unsigned int)0x00000008) /* HCLK:20-35 MHz; MDC clock= HCLK/16 */ +#define ETH_MACMIIAR_CR_Div26 ((unsigned int)0x0000000C) /* HCLK:35-60 MHz; MDC clock= HCLK/26 */ +#define ETH_MACMIIAR_MW ((unsigned int)0x00000002) /* MII write */ +#define ETH_MACMIIAR_MB ((unsigned int)0x00000001) /* MII busy */ +#define ETH_MACMIIDR_MD ((unsigned int)0x0000FFFF) /* MII data: read/write data from/to PHY */ +#define ETH_MACFCR_PT ((unsigned int)0xFFFF0000) /* Pause time */ +#define ETH_MACFCR_ZQPD ((unsigned int)0x00000080) /* Zero-quanta pause disable */ +#define ETH_MACFCR_PLT ((unsigned int)0x00000030) /* Pause low threshold: 4 cases */ +#define ETH_MACFCR_PLT_Minus4 ((unsigned int)0x00000000) /* Pause time minus 4 slot times */ +#define ETH_MACFCR_PLT_Minus28 ((unsigned int)0x00000010) /* Pause time minus 28 slot times */ +#define ETH_MACFCR_PLT_Minus144 ((unsigned int)0x00000020) /* Pause time minus 144 slot times */ +#define ETH_MACFCR_PLT_Minus256 ((unsigned int)0x00000030) /* Pause time minus 256 slot times */ +#define ETH_MACFCR_UPFD ((unsigned int)0x00000008) /* Unicast pause frame detect */ +#define ETH_MACFCR_RFCE ((unsigned int)0x00000004) /* Receive flow control enable */ +#define ETH_MACFCR_TFCE ((unsigned int)0x00000002) /* Transmit flow control enable */ +#define ETH_MACFCR_FCBBPA ((unsigned int)0x00000001) /* Flow control busy/backpressure activate */ + +#define ETH_MACVLANTR_VLANTC ((unsigned int)0x00010000) /* 12-bit VLAN tag comparison */ +#define ETH_MACVLANTR_VLANTI ((unsigned int)0x0000FFFF) /* VLAN tag identifier (for receive frames) */ + +#define ETH_MACRWUFFR_D ((unsigned int)0xFFFFFFFF) /* Wake-up frame filter register data */ +/* Eight sequential Writes to this address (offset 0x28) will write all Wake-UpFrame Filter Registers. +Eight sequential Reads from this address (offset 0x28) will read all Wake-UpFrame Filter Registers. */ + +/* +Wake-UpFrame Filter Reg0 : Filter 0 Byte Mask +Wake-UpFrame Filter Reg1 : Filter 1 Byte Mask +Wake-UpFrame Filter Reg2 : Filter 2 Byte Mask +Wake-UpFrame Filter Reg3 : Filter 3 Byte Mask +Wake-UpFrame Filter Reg4 : RSVD - Filter3 Command - RSVD - Filter2 Command - + RSVD - Filter1 Command - RSVD - Filter0 Command +Wake-UpFrame Filter Re5 : Filter3 Offset - Filter2 Offset - Filter1 Offset - Filter0 Offset +Wake-UpFrame Filter Re6 : Filter1 CRC16 - Filter0 CRC16 +Wake-UpFrame Filter Re7 : Filter3 CRC16 - Filter2 CRC16 */ + +#define ETH_MACPMTCSR_WFFRPR ((unsigned int)0x80000000) /* Wake-Up Frame Filter Register Pointer Reset */ +#define ETH_MACPMTCSR_GU ((unsigned int)0x00000200) /* Global Unicast */ +#define ETH_MACPMTCSR_WFR ((unsigned int)0x00000040) /* Wake-Up Frame Received */ +#define ETH_MACPMTCSR_MPR ((unsigned int)0x00000020) /* Magic Packet Received */ +#define ETH_MACPMTCSR_WFE ((unsigned int)0x00000004) /* Wake-Up Frame Enable */ +#define ETH_MACPMTCSR_MPE ((unsigned int)0x00000002) /* Magic Packet Enable */ +#define ETH_MACPMTCSR_PD ((unsigned int)0x00000001) /* Power Down */ + +#define ETH_MACSR_TSTS ((unsigned int)0x00000200) /* Time stamp trigger status */ +#define ETH_MACSR_MMCTS ((unsigned int)0x00000040) /* MMC transmit status */ +#define ETH_MACSR_MMMCRS ((unsigned int)0x00000020) /* MMC receive status */ +#define ETH_MACSR_MMCS ((unsigned int)0x00000010) /* MMC status */ +#define ETH_MACSR_PMTS ((unsigned int)0x00000008) /* PMT status */ + +#define ETH_MACIMR_TSTIM ((unsigned int)0x00000200) /* Time stamp trigger interrupt mask */ +#define ETH_MACIMR_PMTIM ((unsigned int)0x00000008) /* PMT interrupt mask */ + +#define ETH_MACA0HR_MACA0H ((unsigned int)0x0000FFFF) /* MAC address0 high */ +#define ETH_MACA0LR_MACA0L ((unsigned int)0xFFFFFFFF) /* MAC address0 low */ +#define ETH_MACA1HR_AE ((unsigned int)0x80000000) /* Address enable */ +#define ETH_MACA1HR_SA ((unsigned int)0x40000000) /* Source address */ +#define ETH_MACA1HR_MBC ((unsigned int)0x3F000000) /* Mask byte control: bits to mask for comparison of the MAC Address bytes */ +#define ETH_MACA1HR_MBC_HBits15_8 ((unsigned int)0x20000000) /* Mask MAC Address high reg bits [15:8] */ +#define ETH_MACA1HR_MBC_HBits7_0 ((unsigned int)0x10000000) /* Mask MAC Address high reg bits [7:0] */ +#define ETH_MACA1HR_MBC_LBits31_24 ((unsigned int)0x08000000) /* Mask MAC Address low reg bits [31:24] */ +#define ETH_MACA1HR_MBC_LBits23_16 ((unsigned int)0x04000000) /* Mask MAC Address low reg bits [23:16] */ +#define ETH_MACA1HR_MBC_LBits15_8 ((unsigned int)0x02000000) /* Mask MAC Address low reg bits [15:8] */ +#define ETH_MACA1HR_MBC_LBits7_0 ((unsigned int)0x01000000) /* Mask MAC Address low reg bits [7:0] */ +#define ETH_MACA1HR_MACA1H ((unsigned int)0x0000FFFF) /* MAC address1 high */ +#define ETH_MACA1LR_MACA1L ((unsigned int)0xFFFFFFFF) /* MAC address1 low */ + +#define ETH_MACA2HR_AE ((unsigned int)0x80000000) /* Address enable */ +#define ETH_MACA2HR_SA ((unsigned int)0x40000000) /* Source address */ +#define ETH_MACA2HR_MBC ((unsigned int)0x3F000000) /* Mask byte control */ +#define ETH_MACA2HR_MBC_HBits15_8 ((unsigned int)0x20000000) /* Mask MAC Address high reg bits [15:8] */ +#define ETH_MACA2HR_MBC_HBits7_0 ((unsigned int)0x10000000) /* Mask MAC Address high reg bits [7:0] */ +#define ETH_MACA2HR_MBC_LBits31_24 ((unsigned int)0x08000000) /* Mask MAC Address low reg bits [31:24] */ +#define ETH_MACA2HR_MBC_LBits23_16 ((unsigned int)0x04000000) /* Mask MAC Address low reg bits [23:16] */ +#define ETH_MACA2HR_MBC_LBits15_8 ((unsigned int)0x02000000) /* Mask MAC Address low reg bits [15:8] */ +#define ETH_MACA2HR_MBC_LBits7_0 ((unsigned int)0x01000000) /* Mask MAC Address low reg bits [70] */ +#define ETH_MACA2HR_MACA2H ((unsigned int)0x0000FFFF) /* MAC address1 high */ +#define ETH_MACA2LR_MACA2L ((unsigned int)0xFFFFFFFF) /* MAC address2 low */ + +#define ETH_MACA3HR_AE ((unsigned int)0x80000000) /* Address enable */ +#define ETH_MACA3HR_SA ((unsigned int)0x40000000) /* Source address */ +#define ETH_MACA3HR_MBC ((unsigned int)0x3F000000) /* Mask byte control */ +#define ETH_MACA3HR_MBC_HBits15_8 ((unsigned int)0x20000000) /* Mask MAC Address high reg bits [15:8] */ +#define ETH_MACA3HR_MBC_HBits7_0 ((unsigned int)0x10000000) /* Mask MAC Address high reg bits [7:0] */ +#define ETH_MACA3HR_MBC_LBits31_24 ((unsigned int)0x08000000) /* Mask MAC Address low reg bits [31:24] */ +#define ETH_MACA3HR_MBC_LBits23_16 ((unsigned int)0x04000000) /* Mask MAC Address low reg bits [23:16] */ +#define ETH_MACA3HR_MBC_LBits15_8 ((unsigned int)0x02000000) /* Mask MAC Address low reg bits [15:8] */ +#define ETH_MACA3HR_MBC_LBits7_0 ((unsigned int)0x01000000) /* Mask MAC Address low reg bits [70] */ +#define ETH_MACA3HR_MACA3H ((unsigned int)0x0000FFFF) /* MAC address3 high */ +#define ETH_MACA3LR_MACA3L ((unsigned int)0xFFFFFFFF) /* MAC address3 low */ + +/******************************************************************************/ +/* +/* ETH MMC Register +/* +/******************************************************************************/ +#define ETH_MMCCR_MCFHP ((unsigned int)0x00000020) /* MMC counter Full-Half preset */ +#define ETH_MMCCR_MCP ((unsigned int)0x00000010) /* MMC counter preset */ +#define ETH_MMCCR_MCF ((unsigned int)0x00000008) /* MMC Counter Freeze */ +#define ETH_MMCCR_ROR ((unsigned int)0x00000004) /* Reset on Read */ +#define ETH_MMCCR_CSR ((unsigned int)0x00000002) /* Counter Stop Rollover */ +#define ETH_MMCCR_CR ((unsigned int)0x00000001) /* Counters Reset */ + +#define ETH_MMCRIR_RGUFS ((unsigned int)0x00020000) /* Set when Rx good unicast frames counter reaches half the maximum value */ +#define ETH_MMCRIR_RFAES ((unsigned int)0x00000040) /* Set when Rx alignment error counter reaches half the maximum value */ +#define ETH_MMCRIR_RFCES ((unsigned int)0x00000020) /* Set when Rx crc error counter reaches half the maximum value */ + +#define ETH_MMCTIR_TGFS ((unsigned int)0x00200000) /* Set when Tx good frame count counter reaches half the maximum value */ +#define ETH_MMCTIR_TGFMSCS ((unsigned int)0x00008000) /* Set when Tx good multi col counter reaches half the maximum value */ +#define ETH_MMCTIR_TGFSCS ((unsigned int)0x00004000) /* Set when Tx good single col counter reaches half the maximum value */ + +#define ETH_MMCRIMR_RGUFM ((unsigned int)0x00020000) /* Mask the interrupt when Rx good unicast frames counter reaches half the maximum value */ +#define ETH_MMCRIMR_RFAEM ((unsigned int)0x00000040) /* Mask the interrupt when when Rx alignment error counter reaches half the maximum value */ +#define ETH_MMCRIMR_RFCEM ((unsigned int)0x00000020) /* Mask the interrupt when Rx crc error counter reaches half the maximum value */ + +#define ETH_MMCTIMR_TGFM ((unsigned int)0x00200000) /* Mask the interrupt when Tx good frame count counter reaches half the maximum value */ +#define ETH_MMCTIMR_TGFMSCM ((unsigned int)0x00008000) /* Mask the interrupt when Tx good multi col counter reaches half the maximum value */ +#define ETH_MMCTIMR_TGFSCM ((unsigned int)0x00004000) /* Mask the interrupt when Tx good single col counter reaches half the maximum value */ + +#define ETH_MMCTGFSCCR_TGFSCC ((unsigned int)0xFFFFFFFF) /* Number of successfully transmitted frames after a single collision in Half-duplex mode. */ +#define ETH_MMCTGFMSCCR_TGFMSCC ((unsigned int)0xFFFFFFFF) /* Number of successfully transmitted frames after more than a single collision in Half-duplex mode. */ +#define ETH_MMCTGFCR_TGFC ((unsigned int)0xFFFFFFFF) /* Number of good frames transmitted. */ +#define ETH_MMCRFCECR_RFCEC ((unsigned int)0xFFFFFFFF) /* Number of frames received with CRC error. */ +#define ETH_MMCRFAECR_RFAEC ((unsigned int)0xFFFFFFFF) /* Number of frames received with alignment (dribble) error */ +#define ETH_MMCRGUFCR_RGUFC ((unsigned int)0xFFFFFFFF) /* Number of good unicast frames received. */ + + +/******************************************************************************/ +/* +/* ETH Precise Clock Protocol Register +/* +/******************************************************************************/ +#define ETH_PTPTSCR_TSCNT ((unsigned int)0x00030000) /* Time stamp clock node type */ +#define ETH_PTPTSSR_TSSMRME ((unsigned int)0x00008000) /* Time stamp snapshot for message relevant to master enable */ +#define ETH_PTPTSSR_TSSEME ((unsigned int)0x00004000) /* Time stamp snapshot for event message enable */ +#define ETH_PTPTSSR_TSSIPV4FE ((unsigned int)0x00002000) /* Time stamp snapshot for IPv4 frames enable */ +#define ETH_PTPTSSR_TSSIPV6FE ((unsigned int)0x00001000) /* Time stamp snapshot for IPv6 frames enable */ +#define ETH_PTPTSSR_TSSPTPOEFE ((unsigned int)0x00000800) /* Time stamp snapshot for PTP over ethernet frames enable */ +#define ETH_PTPTSSR_TSPTPPSV2E ((unsigned int)0x00000400) /* Time stamp PTP packet snooping for version2 format enable */ +#define ETH_PTPTSSR_TSSSR ((unsigned int)0x00000200) /* Time stamp Sub-seconds rollover */ +#define ETH_PTPTSSR_TSSARFE ((unsigned int)0x00000100) /* Time stamp snapshot for all received frames enable */ + +#define ETH_PTPTSCR_TSARU ((unsigned int)0x00000020) /* Addend register update */ +#define ETH_PTPTSCR_TSITE ((unsigned int)0x00000010) /* Time stamp interrupt trigger enable */ +#define ETH_PTPTSCR_TSSTU ((unsigned int)0x00000008) /* Time stamp update */ +#define ETH_PTPTSCR_TSSTI ((unsigned int)0x00000004) /* Time stamp initialize */ +#define ETH_PTPTSCR_TSFCU ((unsigned int)0x00000002) /* Time stamp fine or coarse update */ +#define ETH_PTPTSCR_TSE ((unsigned int)0x00000001) /* Time stamp enable */ + +#define ETH_PTPSSIR_STSSI ((unsigned int)0x000000FF) /* System time Sub-second increment value */ +#define ETH_PTPTSHR_STS ((unsigned int)0xFFFFFFFF) /* System Time second */ +#define ETH_PTPTSLR_STPNS ((unsigned int)0x80000000) /* System Time Positive or negative time */ +#define ETH_PTPTSLR_STSS ((unsigned int)0x7FFFFFFF) /* System Time sub-seconds */ +#define ETH_PTPTSHUR_TSUS ((unsigned int)0xFFFFFFFF) /* Time stamp update seconds */ +#define ETH_PTPTSLUR_TSUPNS ((unsigned int)0x80000000) /* Time stamp update Positive or negative time */ +#define ETH_PTPTSLUR_TSUSS ((unsigned int)0x7FFFFFFF) /* Time stamp update sub-seconds */ +#define ETH_PTPTSAR_TSA ((unsigned int)0xFFFFFFFF) /* Time stamp addend */ +#define ETH_PTPTTHR_TTSH ((unsigned int)0xFFFFFFFF) /* Target time stamp high */ +#define ETH_PTPTTLR_TTSL ((unsigned int)0xFFFFFFFF) /* Target time stamp low */ +#define ETH_PTPTSSR_TSTTR ((unsigned int)0x00000020) /* Time stamp target time reached */ +#define ETH_PTPTSSR_TSSO ((unsigned int)0x00000010) /* Time stamp seconds overflow */ + +/******************************************************************************/ +/* +/* ETH DMA Register +/* +/******************************************************************************/ +#define ETH_DMABMR_AAB ((unsigned int)0x02000000) /* Address-Aligned beats */ +#define ETH_DMABMR_FPM ((unsigned int)0x01000000) /* 4xPBL mode */ +#define ETH_DMABMR_USP ((unsigned int)0x00800000) /* Use separate PBL */ +#define ETH_DMABMR_RDP ((unsigned int)0x007E0000) /* RxDMA PBL */ +#define ETH_DMABMR_RDP_1Beat ((unsigned int)0x00020000) /* maximum number of beats to be transferred in one RxDMA transaction is 1 */ +#define ETH_DMABMR_RDP_2Beat ((unsigned int)0x00040000) /* maximum number of beats to be transferred in one RxDMA transaction is 2 */ +#define ETH_DMABMR_RDP_4Beat ((unsigned int)0x00080000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_DMABMR_RDP_8Beat ((unsigned int)0x00100000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_DMABMR_RDP_16Beat ((unsigned int)0x00200000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_DMABMR_RDP_32Beat ((unsigned int)0x00400000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_DMABMR_RDP_4xPBL_4Beat ((unsigned int)0x01020000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_DMABMR_RDP_4xPBL_8Beat ((unsigned int)0x01040000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_DMABMR_RDP_4xPBL_16Beat ((unsigned int)0x01080000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_DMABMR_RDP_4xPBL_32Beat ((unsigned int)0x01100000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_DMABMR_RDP_4xPBL_64Beat ((unsigned int)0x01200000) /* maximum number of beats to be transferred in one RxDMA transaction is 64 */ +#define ETH_DMABMR_RDP_4xPBL_128Beat ((unsigned int)0x01400000) /* maximum number of beats to be transferred in one RxDMA transaction is 128 */ +#define ETH_DMABMR_FB ((unsigned int)0x00010000) /* Fixed Burst */ +#define ETH_DMABMR_RTPR ((unsigned int)0x0000C000) /* Rx Tx priority ratio */ +#define ETH_DMABMR_RTPR_1_1 ((unsigned int)0x00000000) /* Rx Tx priority ratio */ +#define ETH_DMABMR_RTPR_2_1 ((unsigned int)0x00004000) /* Rx Tx priority ratio */ +#define ETH_DMABMR_RTPR_3_1 ((unsigned int)0x00008000) /* Rx Tx priority ratio */ +#define ETH_DMABMR_RTPR_4_1 ((unsigned int)0x0000C000) /* Rx Tx priority ratio */ +#define ETH_DMABMR_PBL ((unsigned int)0x00003F00) /* Programmable burst length */ +#define ETH_DMABMR_PBL_1Beat ((unsigned int)0x00000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ +#define ETH_DMABMR_PBL_2Beat ((unsigned int)0x00000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ +#define ETH_DMABMR_PBL_4Beat ((unsigned int)0x00000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_DMABMR_PBL_8Beat ((unsigned int)0x00000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_DMABMR_PBL_16Beat ((unsigned int)0x00001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_DMABMR_PBL_32Beat ((unsigned int)0x00002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_DMABMR_PBL_4xPBL_4Beat ((unsigned int)0x01000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_DMABMR_PBL_4xPBL_8Beat ((unsigned int)0x01000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_DMABMR_PBL_4xPBL_16Beat ((unsigned int)0x01000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_DMABMR_PBL_4xPBL_32Beat ((unsigned int)0x01000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_DMABMR_PBL_4xPBL_64Beat ((unsigned int)0x01001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ +#define ETH_DMABMR_PBL_4xPBL_128Beat ((unsigned int)0x01002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ +#define ETH_DMABMR_EDE ((unsigned int)0x00000080) /* Enhanced Descriptor Enable */ +#define ETH_DMABMR_DSL ((unsigned int)0x0000007C) /* Descriptor Skip Length */ +#define ETH_DMABMR_DA ((unsigned int)0x00000002) /* DMA arbitration scheme */ +#define ETH_DMABMR_SR ((unsigned int)0x00000001) /* Software reset */ + +#define ETH_DMATPDR_TPD ((unsigned int)0xFFFFFFFF) /* Transmit poll demand */ +#define ETH_DMARPDR_RPD ((unsigned int)0xFFFFFFFF) /* Receive poll demand */ +#define ETH_DMARDLAR_SRL ((unsigned int)0xFFFFFFFF) /* Start of receive list */ +#define ETH_DMATDLAR_STL ((unsigned int)0xFFFFFFFF) /* Start of transmit list */ + +#define ETH_DMASR_TSTS ((unsigned int)0x20000000) /* Time-stamp trigger status */ +#define ETH_DMASR_PMTS ((unsigned int)0x10000000) /* PMT status */ +#define ETH_DMASR_MMCS ((unsigned int)0x08000000) /* MMC status */ +#define ETH_DMASR_EBS ((unsigned int)0x03800000) /* Error bits status */ +#define ETH_DMASR_EBS_DescAccess ((unsigned int)0x02000000) /* Error bits 0-data buffer, 1-desc. access */ +#define ETH_DMASR_EBS_ReadTransf ((unsigned int)0x01000000) /* Error bits 0-write trnsf, 1-read transfr */ +#define ETH_DMASR_EBS_DataTransfTx ((unsigned int)0x00800000) /* Error bits 0-Rx DMA, 1-Tx DMA */ +#define ETH_DMASR_TPS ((unsigned int)0x00700000) /* Transmit process state */ +#define ETH_DMASR_TPS_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Tx Command issued */ +#define ETH_DMASR_TPS_Fetching ((unsigned int)0x00100000) /* Running - fetching the Tx descriptor */ +#define ETH_DMASR_TPS_Waiting ((unsigned int)0x00200000) /* Running - waiting for status */ +#define ETH_DMASR_TPS_Reading ((unsigned int)0x00300000) /* Running - reading the data from host memory */ +#define ETH_DMASR_TPS_Suspended ((unsigned int)0x00600000) /* Suspended - Tx Descriptor unavailabe */ +#define ETH_DMASR_TPS_Closing ((unsigned int)0x00700000) /* Running - closing Rx descriptor */ +#define ETH_DMASR_RPS ((unsigned int)0x000E0000) /* Receive process state */ +#define ETH_DMASR_RPS_Stopped ((unsigned int)0x00000000) /* Stopped - Reset or Stop Rx Command issued */ +#define ETH_DMASR_RPS_Fetching ((unsigned int)0x00020000) /* Running - fetching the Rx descriptor */ +#define ETH_DMASR_RPS_Waiting ((unsigned int)0x00060000) /* Running - waiting for packet */ +#define ETH_DMASR_RPS_Suspended ((unsigned int)0x00080000) /* Suspended - Rx Descriptor unavailable */ +#define ETH_DMASR_RPS_Closing ((unsigned int)0x000A0000) /* Running - closing descriptor */ +#define ETH_DMASR_RPS_Queuing ((unsigned int)0x000E0000) /* Running - queuing the recieve frame into host memory */ +#define ETH_DMASR_NIS ((unsigned int)0x00010000) /* Normal interrupt summary */ +#define ETH_DMASR_AIS ((unsigned int)0x00008000) /* Abnormal interrupt summary */ +#define ETH_DMASR_ERS ((unsigned int)0x00004000) /* Early receive status */ +#define ETH_DMASR_FBES ((unsigned int)0x00002000) /* Fatal bus error status */ +#define ETH_DMASR_ETS ((unsigned int)0x00000400) /* Early transmit status */ +#define ETH_DMASR_RWTS ((unsigned int)0x00000200) /* Receive watchdog timeout status */ +#define ETH_DMASR_RPSS ((unsigned int)0x00000100) /* Receive process stopped status */ +#define ETH_DMASR_RBUS ((unsigned int)0x00000080) /* Receive buffer unavailable status */ +#define ETH_DMASR_RS ((unsigned int)0x00000040) /* Receive status */ +#define ETH_DMASR_TUS ((unsigned int)0x00000020) /* Transmit underflow status */ +#define ETH_DMASR_ROS ((unsigned int)0x00000010) /* Receive overflow status */ +#define ETH_DMASR_TJTS ((unsigned int)0x00000008) /* Transmit jabber timeout status */ +#define ETH_DMASR_TBUS ((unsigned int)0x00000004) /* Transmit buffer unavailable status */ +#define ETH_DMASR_TPSS ((unsigned int)0x00000002) /* Transmit process stopped status */ +#define ETH_DMASR_TS ((unsigned int)0x00000001) /* Transmit status */ + +#define ETH_DMAOMR_DTCEFD ((unsigned int)0x04000000) /* Disable Dropping of TCP/IP checksum error frames */ +#define ETH_DMAOMR_RSF ((unsigned int)0x02000000) /* Receive store and forward */ +#define ETH_DMAOMR_DFRF ((unsigned int)0x01000000) /* Disable flushing of received frames */ +#define ETH_DMAOMR_TSF ((unsigned int)0x00200000) /* Transmit store and forward */ +#define ETH_DMAOMR_FTF ((unsigned int)0x00100000) /* Flush transmit FIFO */ +#define ETH_DMAOMR_TTC ((unsigned int)0x0001C000) /* Transmit threshold control */ +#define ETH_DMAOMR_TTC_64Bytes ((unsigned int)0x00000000) /* threshold level of the MTL Transmit FIFO is 64 Bytes */ +#define ETH_DMAOMR_TTC_128Bytes ((unsigned int)0x00004000) /* threshold level of the MTL Transmit FIFO is 128 Bytes */ +#define ETH_DMAOMR_TTC_192Bytes ((unsigned int)0x00008000) /* threshold level of the MTL Transmit FIFO is 192 Bytes */ +#define ETH_DMAOMR_TTC_256Bytes ((unsigned int)0x0000C000) /* threshold level of the MTL Transmit FIFO is 256 Bytes */ +#define ETH_DMAOMR_TTC_40Bytes ((unsigned int)0x00010000) /* threshold level of the MTL Transmit FIFO is 40 Bytes */ +#define ETH_DMAOMR_TTC_32Bytes ((unsigned int)0x00014000) /* threshold level of the MTL Transmit FIFO is 32 Bytes */ +#define ETH_DMAOMR_TTC_24Bytes ((unsigned int)0x00018000) /* threshold level of the MTL Transmit FIFO is 24 Bytes */ +#define ETH_DMAOMR_TTC_16Bytes ((unsigned int)0x0001C000) /* threshold level of the MTL Transmit FIFO is 16 Bytes */ +#define ETH_DMAOMR_ST ((unsigned int)0x00002000) /* Start/stop transmission command */ +#define ETH_DMAOMR_FEF ((unsigned int)0x00000080) /* Forward error frames */ +#define ETH_DMAOMR_FUGF ((unsigned int)0x00000040) /* Forward undersized good frames */ +#define ETH_DMAOMR_RTC ((unsigned int)0x00000018) /* receive threshold control */ +#define ETH_DMAOMR_RTC_64Bytes ((unsigned int)0x00000000) /* threshold level of the MTL Receive FIFO is 64 Bytes */ +#define ETH_DMAOMR_RTC_32Bytes ((unsigned int)0x00000008) /* threshold level of the MTL Receive FIFO is 32 Bytes */ +#define ETH_DMAOMR_RTC_96Bytes ((unsigned int)0x00000010) /* threshold level of the MTL Receive FIFO is 96 Bytes */ +#define ETH_DMAOMR_RTC_128Bytes ((unsigned int)0x00000018) /* threshold level of the MTL Receive FIFO is 128 Bytes */ +#define ETH_DMAOMR_OSF ((unsigned int)0x00000004) /* operate on second frame */ +#define ETH_DMAOMR_SR ((unsigned int)0x00000002) /* Start/stop receive */ + +#define ETH_DMAIER_NISE ((unsigned int)0x00010000) /* Normal interrupt summary enable */ +#define ETH_DMAIER_AISE ((unsigned int)0x00008000) /* Abnormal interrupt summary enable */ +#define ETH_DMAIER_ERIE ((unsigned int)0x00004000) /* Early receive interrupt enable */ +#define ETH_DMAIER_FBEIE ((unsigned int)0x00002000) /* Fatal bus error interrupt enable */ +#define ETH_DMAIER_ETIE ((unsigned int)0x00000400) /* Early transmit interrupt enable */ +#define ETH_DMAIER_RWTIE ((unsigned int)0x00000200) /* Receive watchdog timeout interrupt enable */ +#define ETH_DMAIER_RPSIE ((unsigned int)0x00000100) /* Receive process stopped interrupt enable */ +#define ETH_DMAIER_RBUIE ((unsigned int)0x00000080) /* Receive buffer unavailable interrupt enable */ +#define ETH_DMAIER_RIE ((unsigned int)0x00000040) /* Receive interrupt enable */ +#define ETH_DMAIER_TUIE ((unsigned int)0x00000020) /* Transmit Underflow interrupt enable */ +#define ETH_DMAIER_ROIE ((unsigned int)0x00000010) /* Receive Overflow interrupt enable */ +#define ETH_DMAIER_TJTIE ((unsigned int)0x00000008) /* Transmit jabber timeout interrupt enable */ +#define ETH_DMAIER_TBUIE ((unsigned int)0x00000004) /* Transmit buffer unavailable interrupt enable */ +#define ETH_DMAIER_TPSIE ((unsigned int)0x00000002) /* Transmit process stopped interrupt enable */ +#define ETH_DMAIER_TIE ((unsigned int)0x00000001) /* Transmit interrupt enable */ + +#define ETH_DMAMFBOCR_OFOC ((unsigned int)0x10000000) /* Overflow bit for FIFO overflow counter */ +#define ETH_DMAMFBOCR_MFA ((unsigned int)0x0FFE0000) /* Number of frames missed by the application */ +#define ETH_DMAMFBOCR_OMFC ((unsigned int)0x00010000) /* Overflow bit for missed frame counter */ +#define ETH_DMAMFBOCR_MFC ((unsigned int)0x0000FFFF) /* Number of frames missed by the controller */ + +#define ETH_DMACHTDR_HTDAP ((unsigned int)0xFFFFFFFF) /* Host transmit descriptor address pointer */ +#define ETH_DMACHRDR_HRDAP ((unsigned int)0xFFFFFFFF) /* Host receive descriptor address pointer */ +#define ETH_DMACHTBAR_HTBAP ((unsigned int)0xFFFFFFFF) /* Host transmit buffer address pointer */ +#define ETH_DMACHRBAR_HRBAP ((unsigned int)0xFFFFFFFF) /* Host receive buffer address pointer */ + +#define ETH_MAC_BASE ((uint32_t)0x40406000) +#define ETH_MAC_ADDR_HBASE (ETH_MAC_BASE + 0x40) /* ETHERNET MAC address high offset */ +#define ETH_MAC_ADDR_LBASE (ETH_MAC_BASE + 0x44) /* ETHERNET MAC address low offset */ + +/*PHY configure register*/ +#define ETH_PHY_CR_PHY_RSTN ((unsigned int)0x80000000) //read-write Ethernet PHY global reset signal +#define ETH_PHY_CR_PHY_PD ((unsigned int)0x40000000) //read-write PHY pd mode selection +#define ETH_PHY_CR_PHY_EEE ((unsigned int)0x20000000) //read-write PHY work mode selection +#define ETH_PHY_CR_DUPlEX ((unsigned int)0x00000400) //read-only Even Ethernet mode selection +#define ETH_PHY_CR_SPEED ((unsigned int)0x00000200) //read-only Even Ethernet speed selection +#define ETH_PHY_CR_PHYADDR_EN ((unsigned int)0x00000080) //read-write Reconfigure the PHY address +#define ETH_PHY_CR_REPHYADDR ((unsigned int)0x0000001f) //read-write when the bit 7 set 1,bit4-0 serves as the address of thePHY + +/*CHKSUM configure register*/ +#define ETH_CHKSUM_CR_CHKSUM_EN ((unsigned int)0x00000100) //read-write the software sets 1 at the beginning of frame calculationand write 0at the end of frame calculation +#define ETH_CHKSUM_CR_BYTE_EN2 ((unsigned int)0x000000f0) //read-write Participate in the ip header checksum tocalculate byte control bits +#define ETH_CHKSUM_CR_BYTE_EN1 ((unsigned int)0x0000000f) //read-write Participate in the ip header checksum tocalculate byte control bits + +/*IP packet register*/ +#define ETH_IP_PDR ((unsigned int)0xffffffff) //read-write IP data written by software,need to be used withETH_CHKSUM_CR + +/*IP packet Header Checksum register*/ +#define ETH_CHKSUM_HR_RESULT ((unsigned int)0x0000ffff) //read-write IP header checksum + +/*IP data Checksum register*/ +#define ETH_CHKSUM_PR_RESULT ((unsigned int)0x0000ffff) //read-write IP header checksum + +/* ETHERNET MACMIIAR register Mask */ +#define MACMIIAR_CR_MASK ((unsigned int)0xFFFFFFE3) + +/* ETHERNET MACCR register Mask */ +#define MACCR_CLEAR_MASK ((unsigned int)0xFF20810F) + +/* ETHERNET MACFCR register Mask */ +#define MACFCR_CLEAR_MASK ((unsigned int)0x0000FF41) + +/* ETHERNET DMAOMR register Mask */ +#define DMAOMR_CLEAR_MASK ((unsigned int)0xF8DE3F23) + +/* ETHERNET Remote Wake-up frame register length */ +#define ETH_WAKEUP_REGISTER_LENGTH 8 + +/* ETHERNET Missed frames counter Shift */ +#define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17 + +/* ETHERNET DMA Tx descriptors Collision Count Shift */ +#define ETH_DMATXDESC_COLLISION_COUNTSHIFT 3 + +/* ETHERNET DMA Tx descriptors Buffer2 Size Shift */ +#define ETH_DMATXDESC_BUFFER2_SIZESHIFT 16 + +/* ETHERNET DMA Rx descriptors Frame Length Shift */ +#define ETH_DMARXDESC_FRAME_LENGTHSHIFT 16 + +/* ETHERNET DMA Rx descriptors Buffer2 Size Shift */ +#define ETH_DMARXDESC_BUFFER2_SIZESHIFT 16 + +/* ETHERNET errors */ +#define ETH_ERROR ((unsigned int)0) +#define ETH_SUCCESS ((unsigned int)1) + + +/* Bit or field definition for PHY basic control register */ +#define PHY_Reset ((uint16_t)0x8000) /* PHY Reset */ +#define PHY_Loopback ((uint16_t)0x4000) /* Select loop-back mode */ +#define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /* Set the full-duplex mode at 100 Mb/s */ +#define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /* Set the half-duplex mode at 100 Mb/s */ +#define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /* Set the full-duplex mode at 10 Mb/s */ +#define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /* Set the half-duplex mode at 10 Mb/s */ +#define PHY_AutoNegotiation ((uint16_t)0x1000) /* Enable auto-negotiation function */ +#define PHY_Restart_AutoNegotiation ((uint16_t)0x0200) /* Restart auto-negotiation function */ +#define PHY_Powerdown ((uint16_t)0x0800) /* Select the power down mode */ +#define PHY_Isolate ((uint16_t)0x0400) /* Isolate PHY from MII */ + +/* Bit or field definition for PHY basic status register */ +#define PHY_AutoNego_Complete ((uint16_t)0x0020) /* Auto-Negotioation process completed */ +#define PHY_Linked_Status ((uint16_t)0x0004) /* Valid link established */ +#define PHY_Jabber_detection ((uint16_t)0x0002) /* Jabber condition detected */ +#define PHY_RMII_Mode ((uint16_t)0x0020) /* RMII */ + + +/* PHY basic register */ +#define PHY_BCR 0x0 /*PHY transceiver Basic Control Register */ +#define PHY_BSR 0x01 /*PHY transceiver Basic Status Register*/ +#define PHY_BMCR PHY_BCR +#define PHY_BMSR PHY_BSR +#define PHY_PHYIDR1 0x02 /*PHY Identifier Register*/ +#define PHY_PHYIDR2 0x03 /*PHY Identifier Register*/ +#define PHY_ANAR 0x04 /* Auto-Negotiation Advertisement Register */ +#define PHY_ANLPAR 0x05 /* Auto-Negotiation Link Partner Base Page Ability Register*/ +#define PHY_ANER 0x06 /* Auto-Negotiation Expansion Register */ +#define PHY_ANNPTR 0x07 +#define PHY_ANLPNPR 0x08 +#define PHY_PAG_SEL 0x1F + +/****************Page 0********************/ +#define PHY_MMD_CONTROL 0x0D +#define PHY_MMD_ADDR 0x0E +#define PHY_FLASE_CAR_CNT 0x14 +#define PHY_RECV_ERR_CNT 0x15 +#define PHY_PWR_SAVE 0x18 +#define PHY_CONTROL1 0x19 +#define PHY_STATUS1 0x1A +#define PHY_ADDR 0x1B +#define PHY_MDI_MDIX 0x1C +#define PHY_INTERRUPT_IND 0x1E + +/****************Page 4********************/ +#define PHY_EEE_CAP0 0x10 +#define PHY_EEE_CAP1 0x15 +#define PHY_CRC_DET 0x17 +#define PHY_RX_CRCERR_CNT 0x18 +#define PHY_RX_PACKET_CNT 0x19 +#define PHY_BT100_ANA 0x1A + +/****************Page 7********************/ +#define PHY_EEEPC1R 0x00 +#define PHY_EEEPS1R 0x01 +#define PHY_EEECR 0x14 +#define PHY_EEEWER 0x16 +#define PHY_EEEAR 0x3C +#define PHY_EEELPAR 0x3D + +#define PHY_CUST_LED_SET 0x11 +#define PHY_EEE_LED_EN 0x12 +#define PHY_INTERRUPT_MASK 0x13 +#define PHY_LED_CONTROL 0x15 + +/****************Page 8********************/ +#define PHY_WKUPF_MASK0 0x10 +#define PHY_WKUPF_MASK1 0x11 +#define PHY_WKUPF_MASK2 0x12 +#define PHY_WKUPF_MASK3 0x13 +#define PHY_WKUPF_MASK4 0x14 +#define PHY_WKUPF_MASK5 0x15 +#define PHY_WKUPF_MASK6 0x16 +#define PHY_WKUPF_MASK7 0x17 + +/****************Page 16********************/ +#define PHY_WKCRC0 0x10 + +/****************Page 17********************/ +#define PHY_WOL_ABILITY 0x10 +#define PHY_WOL_RESET 0x11 +#define PHY_WOL_ISO_PMEB 0x13 +#define PHY_WOL_CTRL_SET 0x14 +#define PHY_WOL_STATUS 0x15 +#define PHY_WOL_PA_DBYTE0 0x16 +#define PHY_WOL_PA_DBYTE1 0x17 +#define PHY_WOL_PA_DBYTE2 0x18 + +/****************Page 18********************/ +#define PHY_UNI_PHY_ADDR0 0x10 +#define PHY_UNI_PHY_ADDR1 0x11 +#define PHY_UNI_PHY_ADDR2 0x12 +#define PHY_MULTICAST0 0x13 +#define PHY_MULTICAST1 0x14 +#define PHY_MULTICAST2 0x15 +#define PHY_MULTICAST3 0x16 + +#define PHY_REG_PAGE0 0x00 +#define PHY_REG_PAGE4 0x04 +#define PHY_REG_PAGE7 0x07 +#define PHY_REG_PAGE8 0x08 +#define PHY_REG_PAGE16 0x10 +#define PHY_REG_PAGE17 0x11 +#define PHY_REG_PAGE18 0x12 + +/***************INTERRUPT_IND******************/ +#define INTERRUPT_AUTO_NEGOTIATION_ERR ((uint16_t)0x8000) +#define INTERRUPT_SPEED_CHANGE ((uint16_t)0x4000) +#define INTERRUPT_DUPLEX_CHANGE ((uint16_t)0x2000) +#define INTERRUPT_LINK_CHANGE ((uint16_t)0x0800) +#define INTERRUPT_WOL_DONE ((uint16_t)0x0001) + +/***************PHY_WOL_STATUS******************/ +#define WOL_DONE_INT ((uint16_t)0x0001) + +void ETH_Start(void); + +void printf_dmasr (void); + +void ETH_DropRxPkt(void); + +void print_dmasr_rps(void); + +void print_dmasr_tps(void); + +void print_dmasr_tbus(void); + +void ETH_SoftwareReset(void); + +uint32_t ETH_GetRxPktSize(void); + +void ETH_MMCCountersReset(void); + +void ETH_FlushTransmitFIFO(void); + +void delay_clk (uint32_t nCount); + +void ETH_ResumeDMAReception(void); + +FlagStatus ETH_GetlinkStaus (void); + +void ETH_ResumeDMATransmission(void); + +uint32_t ETH_HandleRxPkt(uint8_t *ppkt); + +void ETH_InitiatePauseControlFrame(void); + +uint32_t ETH_GetReceiveProcessState(void); + +uint32_t ETH_GetTransmitProcessState(void); + +FlagStatus ETH_GetSoftwareResetStatus(void); + +uint32_t ETH_GetCurrentTxBufferAddress(void); + +uint32_t ETH_GetCurrentRxBufferAddress(void); + +void ETH_DMAClearFlag(uint32_t ETH_DMA_FLAG); + +FlagStatus ETH_GetFlowControlBusyStatus(void); + +uint32_t ETH_GetCurrentTxDescStartAddress(void); + +uint32_t ETH_GetCurrentRxDescStartAddress(void); + +FlagStatus ETH_GetFlushTransmitFIFOStatus(void); + +void ETH_PowerDownCmd(FunctionalState NewState); + +ITStatus ETH_GetMMCITStatus(uint32_t ETH_MMC_IT); + +uint32_t ETH_GetMMCRegister(uint32_t ETH_MMCReg); + +ITStatus ETH_GetMACITStatus(uint32_t ETH_MAC_IT); + +ITStatus ETH_GetDMAITStatus(uint32_t ETH_DMA_IT); + +void ETH_MACReceptionCmd(FunctionalState NewState); + +void ETH_DMAClearITPendingBit(uint32_t ETH_DMA_IT); + +void ETH_DMAReceptionCmd(FunctionalState NewState); + +uint32_t ETH_GetRxOverflowMissedFrameCounter(void); + +void ETH_MMCResetOnReadCmd(FunctionalState NewState); + +void ETH_ResetWakeUpFrameFilterRegisterPointer(void); + +void ETH_StructInit(ETH_InitTypeDef* ETH_InitStruct); + +void ETH_MACTransmissionCmd(FunctionalState NewState); + +void ETH_DMATransmissionCmd(FunctionalState NewState); + +void ETH_MMCCounterFreezeCmd(FunctionalState NewState); + +FlagStatus ETH_GetDMAFlagStatus(uint32_t ETH_DMA_FLAG); + +FlagStatus ETH_GetMACFlagStatus(uint32_t ETH_MAC_FLAG); + +FlagStatus ETH_GetPMTFlagStatus(uint32_t ETH_PMT_FLAG); + +void ETH_SetWakeUpFrameFilterRegister(uint32_t *Buffer); + +void ETH_GetMACAddress(uint32_t MacAddr, uint8_t *Addr); + +void ETH_MMCCounterRolloverCmd(FunctionalState NewState); + +void ETH_GlobalUnicastWakeUpCmd(FunctionalState NewState); + +uint32_t ETH_GetBufferUnavailableMissedFrameCounter(void); + +void ETH_WakeUpFrameDetectionCmd(FunctionalState NewState); + +void ETH_MagicPacketDetectionCmd(FunctionalState NewState); + +void ETH_SetDMATxDescOwnBit(ETH_DMADESCTypeDef *DMATxDesc); + +void ETH_MACAddressConfig(uint32_t MacAddr, uint8_t *Addr); + +void ETH_SetDMARxDescOwnBit(ETH_DMADESCTypeDef *DMARxDesc); + +void ETH_BackPressureActivationCmd(FunctionalState NewState); + +uint32_t ETH_HandleTxPkt(uint8_t *ppkt, uint16_t FrameLength); + +FlagStatus ETH_GetDMAOverflowStatus(uint32_t ETH_DMA_Overflow); + +uint32_t ETH_HandlePTPRxPkt(uint8_t *ppkt, uint32_t *PTPRxTab); + +void RGMII_TXC_Delay(uint8_t clock_polarity,uint8_t delay_time); + +void ETH_MACAddressFilterConfig(uint32_t MacAddr, uint32_t Filter); + +uint16_t ETH_ReadPHYRegister(uint16_t PHYAddress, uint16_t PHYReg); + +void ETH_DMAITConfig(uint32_t ETH_DMA_IT, FunctionalState NewState); + +void ETH_MACITConfig(uint32_t ETH_MAC_IT, FunctionalState NewState); + +uint32_t ETH_GetDMARxDescFrameLength(ETH_DMADESCTypeDef *DMARxDesc); + +void ETH_MMCITConfig(uint32_t ETH_MMC_IT, FunctionalState NewState); + +uint32_t ETH_GetDMATxDescCollisionCount(ETH_DMADESCTypeDef *DMATxDesc); + +uint32_t ETH_PHYLoopBackCmd(uint16_t PHYAddress, FunctionalState NewState); + +void ETH_MACAddressMaskBytesFilterConfig(uint32_t MacAddr, uint32_t MaskByte); + +void ETH_MACAddressPerfectFilterCmd(uint32_t MacAddr, FunctionalState NewState); + +void ETH_DMATxDescCRCCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +uint32_t ETH_HandlePTPTxPkt(uint8_t *ppkt, uint16_t FrameLength, uint32_t *PTPTxTab); + +uint32_t ETH_WritePHYRegister(uint16_t PHYAddress, uint16_t PHYReg, uint16_t PHYValue); + +void ETH_DMATxDescEndOfRingCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +void ETH_DMATxDescTimeStampCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +void ETH_DMARxDescEndOfRingCmd(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState); + +void ETH_DMARxDescReceiveITConfig(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState); + +void ETH_DMATxDescTransmitITConfig(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +uint32_t ETH_GetDMARxDescBufferSize(ETH_DMADESCTypeDef *DMARxDesc, uint32_t DMARxDesc_Buffer); + +void ETH_DMATxDescShortFramePaddingCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +FlagStatus ETH_GetDMATxDescFlagStatus(ETH_DMADESCTypeDef *DMATxDesc, uint32_t ETH_DMATxDescFlag); + +FlagStatus ETH_GetDMARxDescFlagStatus(ETH_DMADESCTypeDef *DMARxDesc, uint32_t ETH_DMARxDescFlag); + +void ETH_DMATxDescSecondAddressChainedCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState); + +void ETH_DMARxDescSecondAddressChainedCmd(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState); + +void ETH_DMATxDescChainInit(ETH_DMADESCTypeDef *DMATxDescTab, uint8_t *TxBuff, uint32_t TxBuffCount); + +void ETH_DMATxDescFrameSegmentConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t DMATxDesc_FrameSegment); + +void ETH_DMARxDescChainInit(ETH_DMADESCTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount); + +void ETH_DMATxDescChecksumInsertionConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t DMATxDesc_Checksum); + +void ETH_DMATxDescBufferSizeConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t BufferSize1, uint32_t BufferSize2); + +void ETH_DMATxDescRingInit(ETH_DMADESCTypeDef *DMATxDescTab, uint8_t *TxBuff1, uint8_t *TxBuff2, uint32_t TxBuffCount); + +void ETH_DMARxDescRingInit(ETH_DMADESCTypeDef *DMARxDescTab, uint8_t *RxBuff1, uint8_t *RxBuff2, uint32_t RxBuffCount); + +void ETH_InitializePTPTimeStamp(void); + +void ETH_EnablePTPTimeStampAddend(void); + +void ETH_EnablePTPTimeStampUpdate(void); + +void ETH_SetPTPTimeStampAddend(uint32_t Value); + +uint32_t ETH_GetPTPRegister(uint32_t ETH_PTPReg); + +void ETH_EnablePTPTimeStampInterruptTrigger(void); + +void ETH_PTPTimeStampCmd(FunctionalState NewState); + +void ETH_PTPUpdateMethodConfig(uint32_t UpdateMethod); + +FlagStatus ETH_GetPTPFlagStatus(uint32_t ETH_PTP_FLAG); + +void ETH_SetPTPSubSecondIncrement(uint32_t SubSecondValue); + +void ETH_SetPTPTargetTime(uint32_t HighValue, uint32_t LowValue); + +void ETH_SetPTPTimeStampUpdate(uint32_t Sign, uint32_t SecondValue, uint32_t SubSecondValue); + +void ETH_DMAPTPTxDescChainInit(ETH_DMADESCTypeDef *DMATxDescTab, ETH_DMADESCTypeDef *DMAPTPTxDescTab, uint8_t* TxBuff, uint32_t TxBuffCount); + +void ETH_DMAPTPRxDescChainInit(ETH_DMADESCTypeDef *DMARxDescTab, ETH_DMADESCTypeDef *DMAPTPRxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount); + + + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/Peripheral/inc/ch564_gpio.h b/Peripheral/inc/ch564_gpio.h new file mode 100644 index 0000000..08da89a --- /dev/null +++ b/Peripheral/inc/ch564_gpio.h @@ -0,0 +1,237 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_gpio.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * GPIO firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_GPIO_H +#define __CH564_GPIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +#define GPIO_Pin_0 (0x00000001)/*!< Pin 0 selected */ +#define GPIO_Pin_1 (0x00000002)/*!< Pin 1 selected */ +#define GPIO_Pin_2 (0x00000004)/*!< Pin 2 selected */ +#define GPIO_Pin_3 (0x00000008)/*!< Pin 3 selected */ +#define GPIO_Pin_4 (0x00000010)/*!< Pin 4 selected */ +#define GPIO_Pin_5 (0x00000020)/*!< Pin 5 selected */ +#define GPIO_Pin_6 (0x00000040)/*!< Pin 6 selected */ +#define GPIO_Pin_7 (0x00000080)/*!< Pin 7 selected */ +#define GPIO_Pin_8 (0x00000100)/*!< Pin 8 selected */ +#define GPIO_Pin_9 (0x00000200)/*!< Pin 9 selected */ +#define GPIO_Pin_10 (0x00000400)/*!< Pin 10 selected */ +#define GPIO_Pin_11 (0x00000800)/*!< Pin 11 selected */ +#define GPIO_Pin_12 (0x00001000)/*!< Pin 12 selected */ +#define GPIO_Pin_13 (0x00002000)/*!< Pin 13 selected */ +#define GPIO_Pin_14 (0x00004000)/*!< Pin 14 selected */ +#define GPIO_Pin_15 (0x00008000)/*!< Pin 15 selected */ +#define GPIO_Pin_16 (0x00010000)/*!< Pin 16 selected */ +#define GPIO_Pin_17 (0x00020000)/*!< Pin 17 selected */ +#define GPIO_Pin_18 (0x00040000)/*!< Pin 18 selected */ +#define GPIO_Pin_19 (0x00080000)/*!< Pin 19 selected */ +#define GPIO_Pin_20 (0x00100000)/*!< Pin 20 selected */ +#define GPIO_Pin_21 (0x00200000)/*!< Pin 21 selected */ +#define GPIO_Pin_22 (0x00400000)/*!< Pin 22 selected */ +#define GPIO_Pin_23 (0x00800000)/*!< Pin 23 selected */ +#define GPIO_Pin_24 (0x01000000)/*!< Pin 24 selected */ +#define GPIO_Pin_25 (0x02000000)/*!< Pin 25 selected */ +#define GPIO_Pin_26 (0x04000000)/*!< Pin 26 selected */ +#define GPIO_Pin_27 (0x08000000)/*!< Pin 27 selected */ +#define GPIO_Pin_28 (0x10000000)/*!< Pin 28 selected */ +#define GPIO_Pin_29 (0x20000000)/*!< Pin 29 selected */ +#define GPIO_Pin_30 (0x40000000)/*!< Pin 30 selected */ +#define GPIO_Pin_31 (0x80000000)/*!< Pin 31 selected */ +#define GPIO_Pin_All (0xFFFFFFFF)/*!< All pins selected */ + +#define GPIO_NoRemap_SPI0 (0x00020000) +#define GPIO_PartialRemap1_SPI0 (0x00020001) +#define GPIO_PartialRemap2_SPI0 (0x00020002) +#define GPIO_FullRemap_SPI0 (0x00020003) + +#define GPIO_NoRemap_UART0 (0x00220000) +#define GPIO_PartialRemap2_UART0 (0x00220002) +#define GPIO_FullRemap_UART0 (0x00220003) + +#define GPIO_NoRemap_UART1 (0x00420000) +#define GPIO_PartialRemap1_UART1 (0x00420001) +#define GPIO_FullRemap_UART1 (0x00420003) + +#define GPIO_NoRemap_UART2 (0x00620000) +#define GPIO_PartialRemap1_UART2 (0x00620001) +#define GPIO_PartialRemap2_UART2 (0x00620002) +#define GPIO_FullRemap_UART2 (0x00620003) + +#define GPIO_NoRemap_UART3 (0x00820000) +#define GPIO_PartialRemap1_UART3 (0x00820001) +#define GPIO_FullRemap_UART3 (0x00820003) + +#define GPIO_NoRemap_UART0_MODEM (0x00a20000) +#define GPIO_PartialRemap1_UART0_MODEM (0x00a20001) +#define GPIO_PartialRemap2_UART0_MODEM (0x00a20002) +#define GPIO_FullRemap_UART0_MODEM (0x00a20003) + +#define GPIO_NoRemap_UART1_MODEM (0x00c20000) +#define GPIO_PartialRemap1_UART1_MODEM (0x00c20001) +#define GPIO_PartialRemap2_UART1_MODEM (0x00c20002) +#define GPIO_FullRemap_UART1_MODEM (0x00c20003) + +#define GPIO_NoRemap_UART2_MODEM (0x00e20000) +#define GPIO_PartialRemap2_UART2_MODEM (0x00e20002) +#define GPIO_FullRemap_UART2_MODEM (0x00e20003) + +#define GPIO_NoRemap_I2C (0x01020000) +#define GPIO_PartialRemap1_I2C (0x01020001) + +#define GPIO_NoRemap_SLV_INTERUPT (0x01220000) +#define GPIO_PartialRemap1_SLV_INTERUPT (0x01220001) +#define GPIO_PartialRemap2_SLV_INTERUPT (0x01220002) +#define GPIO_FullRemap_SLV_INTERUPT (0x01220003) + +#define GPIO_NoRemap_SLV_CS (0x01420000) +#define GPIO_PartialRemap1_SLV_CS (0x01420001) + +#define GPIO_NoRemap_SLV_ADDR (0x01620000) +#define GPIO_PartialRemap1_SLV_ADDR (0x01620001) +#define GPIO_PartialRemap2_SLV_ADDR (0x01620002) + +#define GPIO_NoRemap_SLV_ADDR1 (0x01820000) +#define GPIO_PartialRemap2_SLV_ADDR1 (0x01820002) +#define GPIO_FullRemap_SLV_ADDR1 (0x01820003) + +#define GPIO_NoRemap_SLV_DATA (0x01a20000) +#define GPIO_PartialRemap1_SLV_DATA (0x01a20001) + +#define GPIO_NoRemap_SLV_RW (0x01c20000) +#define GPIO_NolRemap_SLV_RW GPIO_NoRemap_SLV_RW +#define GPIO_PartialRemap1_SLV_RW (0x01c20001) + +#define GPIO_NoRemap_LINK_LED (0x01e20000) +#define GPIO_PartialRemap1_LINK_LED (0x01e20001) +#define GPIO_PartialRemap2_LINK_LED (0x01e20002) +#define GPIO_FullRemap_LINK_LED (0x01e20003) + +#define GPIO_NoRemap_ACT_LED (0x80020000) +#define GPIO_PartialRemap1_ACT_LED (0x80020001) +#define GPIO_PartialRemap2_ACT_LED (0x80020002) +#define GPIO_FullRemap_ACT_LED (0x80020003) + +#define GPIO_NoRemap_RST (0x80220000) +#define GPIO_PartialRemap1_RST (0x80220001) +#define GPIO_PartialRemap2_RST (0x80220002) +#define GPIO_FullRemap_RST (0x80220003) + +#define GPIO_NoRemap_TIMER0 (0x80410000) +#define GPIO_FullRemap_TIMER0 (0x80410001) + +#define GPIO_NoRemap_TIMER1 (0x80510000) +#define GPIO_FullRemap_TIMER1 (0x80510001) + +#define GPIO_NoRemap_BUSY (0x80610000) +#define GPIO_FullRemap_BUSY (0x80610001) + +#define GPIO_NoRemap_SPI1 (0x80820000) +#define GPIO_FullRemap_SPI1 (0x80820003) + +#define GPIO_NoRemap_TNOW0 (0x80a20000) +#define GPIO_FullRemap_TNOW0 (0x80a20003) + +#define GPIO_NoRemap_TNOW1 (0x80c20000) +#define GPIO_FullRemap_TNOW1 (0x80c20003) + +#define GPIO_NoRemap_TNOW2 (0x80e20000) +#define GPIO_FullRemap_TNOW2 (0x80e20003) + +#define GPIO_NoRemap_TNOW3 (0x81020000) +#define GPIO_FullRemap_TNOW3 (0x81020003) + +#define GPIO_NoRemap_UART3_MODEM (0x81220000) +#define GPIO_FullRemap_UART3_MODEM (0x81220003) + +/** + * @brief GPIO mode structure configuration + */ +typedef enum +{ + GPIO_ModeIN_Floating = 0, + GPIO_ModeIN_PU, + GPIO_ModeIN_PD, + GPIO_ModeOut_PP, + GPIO_ModeOut_OP +} GPIOModeTypeDef; + +/** + * @brief GPIO interrupt structure configuration + */ +typedef enum +{ + GPIO_ITMode_LowLevel = 0, // Low level trigger + GPIO_ITMode_HighLevel, // High level trigger + GPIO_ITMode_FallEdge, // Falling edge trigger + GPIO_ITMode_RiseEdge, // Rising edge trigger + GPIO_ITMode_None +} GPIOITModeTpDef; + +/** + * @brief GPIO MCO structure configuration + */ +typedef enum +{ + MCO_125 = 0, + MCO_25 = 4, + MCO_2d5 = 0xC, +} MCOMode; + +void GPIOA_ModeCfg(uint32_t pin, GPIOModeTypeDef mode); /* GPIOA port pin mode configuration */ +void GPIOB_ModeCfg(uint32_t pin, GPIOModeTypeDef mode); /* GPIOB port pin mode configuration */ +void GPIOD_ModeCfg(uint32_t pin, GPIOModeTypeDef mode); /* GPIOB port pin mode configuration */ +#define GPIOA_ResetBits(pin) (R32_PA_CLR |= pin) /* GPIOA port pin output set low */ +#define GPIOA_SetBits(pin) (R32_PA_OUT |= pin) /* GPIOA port pin output set high */ +#define GPIOB_ResetBits(pin) (R32_PB_CLR |= pin) /* GPIOB port pin output set low */ +#define GPIOB_SetBits(pin) (R32_PB_OUT |= pin) /* GPIOB port pin output set high */ +#define GPIOD_ResetBits(pin) (R32_PD_OUT &= ~pin) /* GPIOA port pin output set low */ +#define GPIOD_SetBits(pin) (R32_PD_OUT |= pin) /* GPIOA port pin output set high */ +#define GPIOA_InverseBits(pin) (R32_PA_OUT ^= pin) /* GPIOA port pin output level flip */ +#define GPIOB_InverseBits(pin) (R32_PB_OUT ^= pin) /* GPIOB port pin output level flip */ +#define GPIOD_InverseBits(pin) (R32_PD_OUT ^= pin) /* GPIOB port pin output level flip */ +#define GPIOA_ReadPort() (R32_PA_PIN) /* The 32-bit data returned by the GPIOA port, the lower 16 bits are valid */ +#define GPIOB_ReadPort() (R32_PB_PIN) /* The 32-bit data returned by the GPIOB port, the lower 24 bits are valid */ +#define GPIOD_ReadPort() (R32_PD_PIN) /* The 32-bit data returned by the GPIOB port, the lower 24 bits are valid */ +#define GPIOA_ReadPortPin(pin) (R32_PA_PIN & pin) /* GPIOA port pin status, 0-pin low level, (!0)-pin high level */ +#define GPIOB_ReadPortPin(pin) (R32_PB_PIN & pin) /* GPIOB port pin status, 0-pin low level, (!0)-pin high level */ +#define GPIOD_ReadPortPin(pin) (R32_PD_PIN & pin) /* GPIOB port pin status, 0-pin low level, (!0)-pin high level */ +void GPIOA_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode); /* GPIOA pin interrupt mode configuration */ +void GPIOB_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode); /* GPIOB pin interrupt mode configuration */ +void GPIOD_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode); /* GPIOB pin interrupt mode configuration */ +#define GPIOA_ReadITFlagPort() (R32_INT_STATUS_PA) /* Read GPIOA port interrupt flag status */ +#define GPIOB_ReadITFlagPort() (R32_INT_STATUS_PB) /* Read GPIOB port interrupt flag status */ +#define GPIOD_ReadITFlagPort() (R32_INT_STATUS_PD) /* Read GPIOD port interrupt flag status */ + +/*************************************Read Interrupt Bit Flag************************************/ +#define GPIOA_ReadITFLAGBit(pin) (R32_INT_STATUS_PA & pin) +#define GPIOB_ReadITFLAGBit(pin) (R32_INT_STATUS_PB & pin) +#define GPIOD_ReadITFLAGBit(pin) (R32_INT_STATUS_PD & pin) + +/*************************************Clear Interrupt Bit Flag************************************/ +#define GPIOA_ClearITFlagbit(pin) (R32_INT_STATUS_PA |= pin) +#define GPIOB_ClearITFlagbit(pin) (R32_INT_STATUS_PB |= pin) +#define GPIOD_ClearITFlagbit(pin) (R32_INT_STATUS_PD |= pin) + +void GPIO_PinRemapConfig(uint32_t GPIO_Remap, FunctionalState NewSTA); +void GPIO_IPD_Unused(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_i2c.h b/Peripheral/inc/ch564_i2c.h new file mode 100644 index 0000000..270d3cb --- /dev/null +++ b/Peripheral/inc/ch564_i2c.h @@ -0,0 +1,188 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_i2c.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * I2C firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_I2C_H +#define __CH564_I2C_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +/* I2C Init structure definition */ +typedef struct +{ + uint32_t I2C_ClockSpeed; /* Specifies the clock frequency. + This parameter must be set to a value lower than 400kHz */ + + uint16_t I2C_Mode; /* Specifies the I2C mode. + This parameter can be a value of @ref I2C_mode */ + + uint16_t I2C_DutyCycle; /* Specifies the I2C fast mode duty cycle. + This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ + + uint16_t I2C_OwnAddress1; /* Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint16_t I2C_Ack; /* Enables or disables the acknowledgement. + This parameter can be a value of @ref I2C_acknowledgement */ + + uint16_t I2C_AcknowledgedAddress; /* Specifies if 7-bit or 10-bit address is acknowledged. + This parameter can be a value of @ref I2C_acknowledged_address */ +} I2C_InitTypeDef; + +/* I2C_mode */ +#define I2C_Mode_I2C ((uint16_t)0x0000) + +/* I2C_duty_cycle_in_fast_mode */ +#define I2C_DutyCycle_16_9 ((uint16_t)0x4000) /* I2C fast mode Tlow/Thigh = 16/9 */ +#define I2C_DutyCycle_2 ((uint16_t)0xBFFF) /* I2C fast mode Tlow/Thigh = 2 */ + +/* I2C_acknowledgement */ +#define I2C_Ack_Enable ((uint16_t)0x0400) +#define I2C_Ack_Disable ((uint16_t)0x0000) + +/* I2C_transfer_direction */ +#define I2C_Direction_Transmitter ((uint8_t)0x00) +#define I2C_Direction_Receiver ((uint8_t)0x01) + +/* I2C_acknowledged_address */ +#define I2C_AcknowledgedAddress_7bit ((uint16_t)0x4000) +#define I2C_AcknowledgedAddress_10bit ((uint16_t)0xC000) + +/* I2C_registers */ +#define I2C_Register_CTLR1 ((uint8_t)0x00) +#define I2C_Register_CTLR2 ((uint8_t)0x04) +#define I2C_Register_OADDR1 ((uint8_t)0x08) +#define I2C_Register_OADDR2 ((uint8_t)0x0C) +#define I2C_Register_DATAR ((uint8_t)0x10) +#define I2C_Register_STAR1 ((uint8_t)0x14) +#define I2C_Register_STAR2 ((uint8_t)0x18) +#define I2C_Register_CKCFGR ((uint8_t)0x1C) + +/* I2C_PEC_position */ +#define I2C_PECPosition_Next ((uint16_t)0x0800) +#define I2C_PECPosition_Current ((uint16_t)0xF7FF) + +/* I2C_NACK_position */ +#define I2C_NACKPosition_Next ((uint16_t)0x0800) +#define I2C_NACKPosition_Current ((uint16_t)0xF7FF) + +/* I2C_interrupts_definition */ +#define I2C_IT_BUF ((uint16_t)0x0400) +#define I2C_IT_EVT ((uint16_t)0x0200) +#define I2C_IT_ERR ((uint16_t)0x0100) + +/* I2C_interrupts_definition */ +#define I2C_IT_PECERR ((uint32_t)0x01001000) +#define I2C_IT_OVR ((uint32_t)0x01000800) +#define I2C_IT_AF ((uint32_t)0x01000400) +#define I2C_IT_ARLO ((uint32_t)0x01000200) +#define I2C_IT_BERR ((uint32_t)0x01000100) +#define I2C_IT_TXE ((uint32_t)0x06000080) +#define I2C_IT_RXNE ((uint32_t)0x06000040) +#define I2C_IT_STOPF ((uint32_t)0x02000010) +#define I2C_IT_ADD10 ((uint32_t)0x02000008) +#define I2C_IT_BTF ((uint32_t)0x02000004) +#define I2C_IT_ADDR ((uint32_t)0x02000002) +#define I2C_IT_SB ((uint32_t)0x02000001) + +/* STAR2 register flags */ +#define I2C_FLAG_DUALF ((uint32_t)0x00800000) +#define I2C_FLAG_GENCALL ((uint32_t)0x00100000) +#define I2C_FLAG_TRA ((uint32_t)0x00040000) +#define I2C_FLAG_BUSY ((uint32_t)0x00020000) +#define I2C_FLAG_MSL ((uint32_t)0x00010000) + +/* STAR1 register flags */ +#define I2C_FLAG_PECERR ((uint32_t)0x10001000) +#define I2C_FLAG_OVR ((uint32_t)0x10000800) +#define I2C_FLAG_AF ((uint32_t)0x10000400) +#define I2C_FLAG_ARLO ((uint32_t)0x10000200) +#define I2C_FLAG_BERR ((uint32_t)0x10000100) +#define I2C_FLAG_TXE ((uint32_t)0x10000080) +#define I2C_FLAG_RXNE ((uint32_t)0x10000040) +#define I2C_FLAG_STOPF ((uint32_t)0x10000010) +#define I2C_FLAG_ADD10 ((uint32_t)0x10000008) +#define I2C_FLAG_BTF ((uint32_t)0x10000004) +#define I2C_FLAG_ADDR ((uint32_t)0x10000002) +#define I2C_FLAG_SB ((uint32_t)0x10000001) + + /****************I2C Master Events (Events grouped in order of communication)********************/ + +#define I2C_EVENT_MASTER_MODE_SELECT ((uint32_t)0x00030001) /* BUSY, MSL and SB flag */ +#define I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED ((uint32_t)0x00070082) /* BUSY, MSL, ADDR, TXE and TRA flags */ +#define I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED ((uint32_t)0x00030002) /* BUSY, MSL and ADDR flags */ +#define I2C_EVENT_MASTER_MODE_ADDRESS10 ((uint32_t)0x00030008) /* BUSY, MSL and ADD10 flags */ +#define I2C_EVENT_MASTER_BYTE_RECEIVED ((uint32_t)0x00030040) /* BUSY, MSL and RXNE flags */ +#define I2C_EVENT_MASTER_BYTE_TRANSMITTING ((uint32_t)0x00070080) /* TRA, BUSY, MSL, TXE flags */ +#define I2C_EVENT_MASTER_BYTE_TRANSMITTED ((uint32_t)0x00070084) /* TRA, BUSY, MSL, TXE and BTF flags */ + + /******************I2C Slave Events (Events grouped in order of communication)******************/ + +#define I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED ((uint32_t)0x00020002) /* BUSY and ADDR flags */ +#define I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED ((uint32_t)0x00060082) /* TRA, BUSY, TXE and ADDR flags */ +#define I2C_EVENT_SLAVE_RECEIVER_SECONDADDRESS_MATCHED ((uint32_t)0x00820000) /* DUALF and BUSY flags */ +#define I2C_EVENT_SLAVE_TRANSMITTER_SECONDADDRESS_MATCHED ((uint32_t)0x00860080) /* DUALF, TRA, BUSY and TXE flags */ +#define I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED ((uint32_t)0x00120000) /* GENCALL and BUSY flags */ +#define I2C_EVENT_SLAVE_BYTE_RECEIVED ((uint32_t)0x00020040) /* BUSY and RXNE flags */ +#define I2C_EVENT_SLAVE_STOP_DETECTED ((uint32_t)0x00000010) /* STOPF flag */ +#define I2C_EVENT_SLAVE_BYTE_TRANSMITTED ((uint32_t)0x00060084) /* TRA, BUSY, TXE and BTF flags */ +#define I2C_EVENT_SLAVE_BYTE_TRANSMITTING ((uint32_t)0x00060080) /* TRA, BUSY and TXE flags */ +#define I2C_EVENT_SLAVE_ACK_FAILURE ((uint32_t)0x00000400) /* AF flag */ + +void I2C_DeInit(I2C_Typedef *I2Cx); +void I2C_Init(I2C_Typedef *I2Cx, I2C_InitTypeDef *I2C_InitStruct); +void I2C_StructInit(I2C_InitTypeDef *I2C_InitStruct); +void I2C_Cmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_DMACmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_DMALastTransferCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_GenerateSTART(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_GenerateSTOP(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_AcknowledgeConfig(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_OwnAddress2Config(I2C_Typedef *I2Cx, uint8_t Address); +void I2C_DualAddressCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_GeneralCallCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_ITConfig(I2C_Typedef *I2Cx, uint16_t I2C_IT, FunctionalState NewState); +void I2C_SendData(I2C_Typedef *I2Cx, uint8_t Data); +uint8_t I2C_ReceiveData(I2C_Typedef *I2Cx); +void I2C_Send7bitAddress(I2C_Typedef *I2Cx, uint8_t Address, uint8_t I2C_Direction); +uint16_t I2C_ReadRegister(I2C_Typedef *I2Cx, uint8_t I2C_Register); +void I2C_SoftwareResetCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_NACKPositionConfig(I2C_Typedef *I2Cx, uint16_t I2C_NACKPosition); +void I2C_TransmitPEC(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_PECPositionConfig(I2C_Typedef *I2Cx, uint16_t I2C_PECPosition); +void I2C_CalculatePEC(I2C_Typedef *I2Cx, FunctionalState NewState); +uint8_t I2C_GetPEC(I2C_Typedef *I2Cx); +void I2C_ARPCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_StretchClockCmd(I2C_Typedef *I2Cx, FunctionalState NewState); +void I2C_FastModeDutyCycleConfig(I2C_Typedef *I2Cx, uint16_t I2C_DutyCycle); + +/**************************************************************************************** + * I2C State Monitoring Functions + ****************************************************************************************/ + +ErrorStatus I2C_CheckEvent(I2C_Typedef *I2Cx, uint32_t I2C_EVENT); +uint32_t I2C_GetLastEvent(I2C_Typedef *I2Cx); +FlagStatus I2C_GetFlagStatus(I2C_Typedef *I2Cx, uint32_t I2C_FLAG); + +void I2C_ClearFlag(I2C_Typedef *I2Cx, uint32_t I2C_FLAG); +ITStatus I2C_GetITStatus(I2C_Typedef *I2Cx, uint32_t I2C_IT); +void I2C_ClearITPendingBit(I2C_Typedef *I2Cx, uint32_t I2C_IT); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_pwr.h b/Peripheral/inc/ch564_pwr.h new file mode 100644 index 0000000..9158d0a --- /dev/null +++ b/Peripheral/inc/ch564_pwr.h @@ -0,0 +1,67 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_pwr.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * PWR firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_PWR_H +#define __CH564_PWR_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" +/* STOP_mode_entry */ +#define PWR_STOPEntry_WFI ((uint8_t)0x01) +#define PWR_STOPEntry_WFE ((uint8_t)0x02) + +#define WDOG_ENABLE() \ +{ \ + R8_SAFE_ACCESS_SIG = 0x57; \ + R8_SAFE_ACCESS_SIG = 0xA8; \ + R8_GLOB_RST_CFG |= (0x40 | RB_GLOB_WDOG_EN); \ + R8_SAFE_ACCESS_SIG = 0x00; \ +} +#define WDOG_DISABLE() \ +{ \ + R8_SAFE_ACCESS_SIG = 0x57; \ + R8_SAFE_ACCESS_SIG = 0xA8; \ + R8_GLOB_RST_CFG = 0x40; \ + R8_SAFE_ACCESS_SIG = 0x00; \ +} +#define FEED_DOG() (R8_WDOG_CLEAR = 0) +#define VIO_PWN_INT_CMD(cmd) \ +{ \ + cmd == ENABLE ? (R32_EXTEN_CTLR1 |= RB_VIO_PWN_INT_EN) : (R32_EXTEN_CTLR1 &= ~RB_VIO_PWN_INT_EN); \ +} +#define VIO_PWN_RST_CMD(cmd) \ +{ \ + cmd == ENABLE ? (R32_EXTEN_CTLR1 |= RB_VIO_PWN_RST_EN) : (R32_EXTEN_CTLR1 &= ~RB_VIO_PWN_RST_EN); \ +} +#define VIO_PWN_IO_CMD(cmd) \ +{ \ + cmd == ENABLE ? (R32_EXTEN_CTLR1 |= RB_VIO_PWN_IO_EN) : (R32_EXTEN_CTLR1 &= ~RB_VIO_PWN_IO_EN); \ +} +#define LDO_DORMENCY_EN(cmd) \ +{ \ + cmd == ENABLE ? (R32_EXTEN_CTLR1 |= RB_LDO_SLP_EN) : (R32_EXTEN_CTLR1 &= ~RB_LDO_SLP_EN); \ +} + + + +void PWR_Sleep(uint8_t PWR_STOPEntry); +void PWR_DeepSleep(uint8_t PWR_STOPEntry); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_rcc.h b/Peripheral/inc/ch564_rcc.h new file mode 100644 index 0000000..c55add0 --- /dev/null +++ b/Peripheral/inc/ch564_rcc.h @@ -0,0 +1,133 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_rcc.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * RCC firmware library. + ********************************************************************************* +* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. +* Attention: This software (modified or not) and binary are used for +* microcontroller manufactured by Nanjing Qinheng Microelectronics. +*******************************************************************************/ +#ifndef __CH564_RCC_H +#define __CH564_RCC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +#define RCC_UNLOCK_SAFE_ACCESS() \ +({ \ + R8_SAFE_ACCESS_SIG = 0x57; \ + R8_SAFE_ACCESS_SIG = 0xA8; \ + __NOP(); \ +}) + +#define RCC_LOCK_SAFE_ACCESS() ({ R8_SAFE_ACCESS_SIG = 0x0; }) +#define RCC_GET_ID_SAFELY() (R8_SAFE_ACCESS_ID) +#define RCC_CLEAR_WDOG() ({ R8_WDOG_CLEAR = 0; }) + +#define HSI_ON() (R32_EXTEN_CTLR1 |= RB_HSION) +#define HSE_ON() (R32_EXTEN_CTLR1 |= RB_HSEON) +#define HSE_GET_STTATEUS() ((R32_EXTEN_CTLR1 & 0x8000) != 0 ? 1 : 0) +#define HSI_OFF() (R32_EXTEN_CTLR1 &= ~RB_HSION) +#define HSE_OFF() (R32_EXTEN_CTLR1 &= ~RB_HSEON) +#define USB_PLL_ON() \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 |= (RB_USBPLLON); \ + RCC_LOCK_SAFE_ACCESS(); \ +} +#define USB_PLL_OFF() \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 &= ~(RB_USBPLLON); \ + RCC_LOCK_SAFE_ACCESS(); \ +} +#define USB_PLL_MUL_15 0x0000c000 +#define USB_PLL_MUL_16 0x00008000 +#define USB_PLL_MUL_20 0x00004000 +#define USB_PLL_MUL_24 0x00000000 +#define USB_PLL_MUL_SELECT(USB_PLL_MUL) \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 &= ~USB_PLL_MUL_15; \ + R32_EXTEN_CTLR0 |= (USB_PLL_MUL); \ + RCC_LOCK_SAFE_ACCESS(); \ +} +#define USB_PLL_SOURCE_HSI 0x00000060 +#define USB_PLL_SOURCE_HSE 0x00000020 +#define USB_PLL_SOURCE_ETH_PLL_OUT 0x00000040 +#define USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE) \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 &= ~USB_PLL_SOURCE_HSI; \ + R32_EXTEN_CTLR0 |= (USB_PLL_SOURCE); \ + RCC_LOCK_SAFE_ACCESS(); \ +} + +#define CLKSEL_HSI() \ +{ \ + R32_EXTEN_CTLR1 &= ~(RB_CLKSEL); \ +} +#define CLKSEL_HSE() \ +{ \ + R32_EXTEN_CTLR1 |= (RB_CLKSEL); \ +} +#define USB_PLL_ON() \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 |= (RB_USBPLLON); \ + RCC_LOCK_SAFE_ACCESS(); \ +} +#define USB_PLL_OFF() \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R32_EXTEN_CTLR0 &= ~(RB_USBPLLON); \ + RCC_LOCK_SAFE_ACCESS(); \ +} +#define SYSCLK_SOURCE_USBPLL 0 +#define SYSCLK_SOURCE_HSI_HSE 1 +#define SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE) \ +{ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + ((SYSCLK_SOURCE) == SYSCLK_SOURCE_HSI_HSE) ? (R32_EXTEN_CTLR0 |= (RB_SW)) : (R32_EXTEN_CTLR0 &= ~(RB_SW)); \ + RCC_LOCK_SAFE_ACCESS(); \ +} + +#define RCC_GET_GLOB_RST_KEEP() (R8_GLOB_RESET_KEEP) +#define RCC_SET_GLOB_RST_KEEP(val) {R8_GLOB_RESET_KEEP = (val);} +#define RCC_SET_PLL_SYS_OUT_DIV(val) \ +({ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + R8_PLL_OUT_DIV = 0x04 | ((val) << 4); \ + RCC_LOCK_SAFE_ACCESS(); \ +}) +#define RCC_FLASH_CLK_PRE_DIV(sta) \ +({ \ + RCC_UNLOCK_SAFE_ACCESS(); \ + ((sta) == ENABLE) ? (R32_EXTEN_CTLR0 |= 0x00200000) : (R32_EXTEN_CTLR0 &= ~0x00200000) RCC_LOCK_SAFE_ACCESS(); \ +}) + +typedef enum +{ + Code16k_Data128k = 0x0, + Code48k_Data96k = 0x1, + Code80k_Data64k = 0x2 +} GlobMem_Cfg; + +void RCC_SetGlobalMemCFG(GlobMem_Cfg Cfg); +void RCC_LockPort(uint8_t globport, FunctionalState NewSTA); +void RCC_GlobleRstCFG(uint8_t cfg, FunctionalState NewSTA); +void RCC_SlpClkOff(volatile uint8_t *reg, uint8_t slpclk, FunctionalState NewSTA); +void RCC_SlpWakeCtrl(uint8_t slpwake, FunctionalState NewSTA); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_slv.h b/Peripheral/inc/ch564_slv.h new file mode 100644 index 0000000..7467176 --- /dev/null +++ b/Peripheral/inc/ch564_slv.h @@ -0,0 +1,69 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_slv.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * SLV firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_SLV_H +#define __CH564_SLV_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +typedef enum +{ + slv_data, + slv_cmd, + slv_timeout +} SLV_STA; + +#define SLV_CFG(cfglist, en) (BITS_CFG(R8_SLV_CONFIG, cfglist, en)) +#define SLV_SEND_DATA(data) (R8_SLV_DOUT = (data)) +#define SLV_SEND_STA(status) (R8_SLV_STATUS = (status)) +#define SLV_GET_IF(RB_IF_SLV) (R8_INT_FLAG_SLV & (RB_IF_SLV)) +#define SLV_CLEAR_IF(RB_IF_SLV) (R8_INT_FLAG_SLV |= (RB_IF_SLV)) +#define SLV_GET_DATA() (R8_INT_SLV_DIN) +#define SLV_DMA_CFG(cfglist, en) (BITS_CFG(R8_DMA_EN_SLV, cfglist, en)) +#define SLV_SET_MODE_CTRL(cfglist, en) (BITS_CFG(R8_DMA_MODE_CTRL_SLV, cfglist, en)) +#define SLV_SET_MODE_EN(cfglist, en) (BITS_CFG(R8_DMA_MODE_EN_SLV, cfglist, en)) + +#define SLV_DMA_GET_IF(slv_dma_if) (R8_DMA_INT_FLAG_SLV & (slv_dma_if)) +#define SLV_DMA_CLEAR_IF(slv_dma_if) (R8_DMA_INT_FLAG_SLV |= (slv_dma_if)) +#define SLV_DMA_START_ADDR_RD(address) (R32_RD_DMA_START_ADDR_SLV = (uint32_t)(address)) + +#define SLV_DMA_END_ADDR_RD(address) (R32_RD_DMA_END_ADDR_SLV = (uint32_t)(address)) + +#define SLV_DMA_START_ADDR_WR(address) (R32_WR_DMA_START_ADDR_SLV = (uint32_t)(address)) + +#define SLV_DMA_END_ADDR_WR(address) (R32_WR_DMA_END_ADDR_SLV = (uint32_t)(address)) + +#define SLV_DMA_GET_NOW_ADDR() (R32_DMA_END_NOW_SLV) + +#define SLV_SET_DMA_CMD0(cmd) (R8_DMA_CMD0_SLV = (cmd)) + +#define SLV_SET_DMA_CMD1(cmd) (R8_DMA_CMD1_SLV = (cmd)) +#define SLV_SET_RST_CMD(cmd) (R8_SLV_RESET_CMD = (cmd)) + +#define SLV_GET_OTHER_DATA() (R8_OTHER_DATA) +#define SLV_GET_DMA_DEC_LEN() (R16_DMA_DEC_LEN) +#define SLV_GET_DMA_DEC_OFFSET() (R16_DMA_DEC_OFFSET) + +SLV_STA SLV_Read(uint8_t *dataAddress, uint16_t dataSize, uint16_t timeout); +ErrorStatus SLV_SendDATA(uint8_t *data, uint16_t datasize); +ErrorStatus SLV_SendSTA(uint8_t *sta, uint16_t datasize); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_spi.h b/Peripheral/inc/ch564_spi.h new file mode 100644 index 0000000..8ae6357 --- /dev/null +++ b/Peripheral/inc/ch564_spi.h @@ -0,0 +1,141 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_spi.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * SPI firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_SPI_H +#define __CH564_SPI_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +/** + * @brief SPI0 interrupt bit define + */ +#define SPI0_IT_FST_BYTE RB_SPI_IE_FST_BYTE +#define SPI0_IT_FIFO_OV RB_SPI_IE_FIFO_OV +#define SPI0_IT_DMA_END RB_SPI_IE_DMA_END +#define SPI0_IT_FIFO_HF RB_SPI_IE_FIFO_HF +#define SPI0_IT_BYTE_END RB_SPI_IE_BYTE_END +#define SPI0_IT_CNT_END RB_SPI_IE_CNT_END + +#define SPI_MAX_DELAY 0xffff + +/** + * @brief Configuration data mode + */ +typedef enum +{ + Mode0_HighBitINFront, + Mode3_HighBitINFront, +} ModeBitOrderTypeDef; + +/** + * @brief Configuration SPI slave mode + */ +typedef enum +{ + Mode_DataStream = 0, + Mose_FirstCmd, +} Slave_ModeTypeDef; + +/**************** SPI0 */ +void SPI0_MasterInit(uint32_t clockRate); +void SPI0_DataMode(ModeBitOrderTypeDef mode); + +void SPI0_MasterSendByte(uint8_t data); +uint8_t SPI0_MasterRecvByte(void); + +void SPI0_MasterTrans(uint8_t *pbuf, uint16_t len); +void SPI0_MasterRecv(uint8_t *pbuf, uint16_t len); + +void SPI0_DMATrans(uint8_t *pbuf, uint32_t len); +void SPI0_DMARecv(uint8_t *pbuf, uint32_t len); +void SPI0_MasterTransRecv(uint8_t *ptbuf, uint8_t *prbuf, uint16_t len); + +void SPI0_SlaveInit(); +#define SetFirst0Data(data) (R8_SPI0_SLAVE_PRE = (data)) +void SPI0_SlaveSendByte(uint8_t data); +uint8_t SPI0_SlaveRecvByte(void); + +uint8_t SPI0_SlaveTrans(uint8_t *pbuf, uint16_t len,uint16_t timeouts); +uint8_t SPI0_SlaveRecv(uint8_t *pbuf, uint16_t len,uint16_t timeouts); + +// refer to SPI0 interrupt bit define +#define SPI0_MODE_CFG(cfglist, en) BITS_CFG(R8_SPI0_CTRL_MOD, cfglist, en) +#define SPI0_ITCfg(cfglist, en) BITS_CFG(R8_SPI0_INTER_EN, cfglist, en) +#define SPI0_SET_CLOCK_DIV(div) (R8_SPI0_CLOCK_DIV = (div)) +#define SPI0_GetITFlag(f) (R8_SPI0_INT_FLAG & (f)) +#define SPI0_ClearITFlag(f) (R8_SPI0_INT_FLAG = (f)) +#define SPI0_SET_RST(dat) (R8_SPI0_RESET_CMD = (dat)) +#define SPI0_GET_RST() (R8_SPI0_RESET_CMD) +#define SPI0_GET_BUSY() (R8_SPI0_BUSY) +#define SPI0_GET_BUFFER() (R8_SPI0_BUFFER) +#define SPI0_SET_BUFFER(dat) (R8_SPI0_BUFFER = (dat)) +#define SPI0_CLEAR_FIFO() (R8_SPI0_CTRL_MOD |= RB_SPI_ALL_CLEAR); +#define SPI0_GET_FIFO() (R8_SPI0_FIFO) +#define SPI0_SET_FIFO(dat) (R8_SPI0_FIFO = (dat)) +#define SPI0_SET_FIFO_CNT(cnt) (R8_SPI0_FIFO_COUNT = (cnt)) +#define SPI0_GET_FIFO_CNT() (R8_SPI0_FIFO_COUNT) +#define SPI0_SET_TOTAL_CNT(cnt) (R16_SPI0_TOTAL_CNT = (cnt) ) +#define SPI0_GET_TOTAL_CNT() (R16_SPI0_TOTAL_CNT) + +#define SPI0_SET_DMA_MODE(cfglist, en) BITS_CFG(R8_SPI0_CTRL_DMA, cfglist, en) +#define SPI0_SET_DMA_RANGE(start, end) \ +({ \ + R32_SPI0_DMA_BEG = (uint32_t)(start) & MASK_SPI0_DMA_ADDR; \ + R32_SPI0_DMA_END = (uint32_t)(end) & MASK_SPI0_DMA_ADDR; \ +}) + +/**************** SPI1 */ +void SPI1_MasterInit(uint32_t clockRate); +void SPI1_DataMode(ModeBitOrderTypeDef mode); + +void SPI1_MasterSendByte(uint8_t data); +uint8_t SPI1_MasterRecvByte(void); + +void SPI1_MasterTrans(uint8_t *pbuf, uint16_t len); +void SPI1_MasterRecv(uint8_t *pbuf, uint16_t len); + +void SPI1_SlaveInit(); +#define SetFirst1Data(data) (R8_SPI1_SLAVE_PRE = (data)) +void SPI1_SlaveSendByte(uint8_t data); +uint8_t SPI1_SlaveRecvByte(void); + +uint8_t SPI1_SlaveTrans(uint8_t *pbuf, uint16_t len,uint16_t timeouts); +uint8_t SPI1_SlaveRecv(uint8_t *pbuf, uint16_t len,uint16_t timeouts); + +// refer to SPI1 interrupt bit define +#define SPI1_MODE_CFG(cfglist, en) BITS_CFG(R8_SPI1_CTRL_MOD, cfglist, en) +#define SPI1_ITCfg(cfglist, en) BITS_CFG(R8_SPI1_INTER_EN, cfglist, en) +#define SPI1_SET_CLOCK_DIV(div) (R8_SPI1_CLOCK_DIV = (div)) +#define SPI1_GetITFlag(f) (R8_SPI1_INT_FLAG & (f)) +#define SPI1_ClearITFlag(f) (R8_SPI1_INT_FLAG = (f)) +#define SPI1_GET_BUFFER() (R8_SPI1_BUFFER) +#define SPI1_SET_BUFFER(dat) (R8_SPI1_BUFFER = (dat)) +#define SPI1_CLEAR_FIFO() (R8_SPI1_CTRL_MOD |= RB_SPI_ALL_CLEAR); +#define SPI1_GET_FIFO() (R8_SPI1_FIFO) +#define SPI1_SET_FIFO(dat) (R8_SPI1_FIFO = (dat)) +#define SPI1_SET_FIFO_CNT(cnt) (R8_SPI1_FIFO_COUNT = (cnt)) +#define SPI1_GET_FIFO_CNT() (R8_SPI1_FIFO_COUNT) +#define SPI1_SET_TOTAL_CNT(cnt) (R16_SPI1_TOTAL_CNT = (cnt)) +#define SPI1_GET_TOTAL_CNT() (R16_SPI1_TOTAL_CNT) + +#define SPI1_SET_DMA_MODE(cfglist, en) BITS_CFG(R8_SPI1_CTRL_DMA, (cfglist), (en)) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_tim.h b/Peripheral/inc/ch564_tim.h new file mode 100644 index 0000000..028889e --- /dev/null +++ b/Peripheral/inc/ch564_tim.h @@ -0,0 +1,231 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_tim.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * TIM firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_TIM_H +#define __CH564_TIM_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +/** + * @brief Pulse Width Modulation Effective Output Words + */ +typedef enum +{ + PWM_Times_1 = 0, // PWM effective output repeats 1 times + PWM_Times_4 = 1, // PWM effective output repeats 4 times + PWM_Times_8 = 2, // PWM effective output repeats 8 times + PWM_Times_16 = 3, // PWM effective output repeats 16 times +} PWM_RepeatTsTypeDef; + +/** + * @brief Input Capture Edge Mode + */ +typedef enum +{ + CAP_NULL = 0, // not capture + Edge_To_Edge = 1, // between any edge + FallEdge_To_FallEdge = 2, // falling edge to falling edge + RiseEdge_To_RiseEdge = 3, // rising edge to rising edge +} CapModeTypeDef; + +/** + * @brief Input Capture Edge Mode + */ +typedef enum +{ + clock16 = 0, + clock8 +} CapWidthTypedef; + +/** + * @brief Direct access memory loop mode + */ +typedef enum +{ + Mode_Single = 0, // single mode + Mode_LOOP = 1, // cycle mode + Mode_Burst = 2, + Mode_Burst_Loop = 3 +} DMAModeTypeDef; + +/** + * @brief PWM output polarity + */ +typedef enum +{ + high_on_low = 0, // Default low level, high level is active + low_on_high = 1, // Default high level, low level active +} PWM_PolarTypeDef; + +/****************** TMR0 */ +// Timing and counting +void TMR0_TimerInit(uint32_t arr); /* Timing function initialization */ +#define TMR0_DeInit() (R8_TMR0_CTRL_MOD = 0) +#define TMR0_GetCurrentCount() R32_TMR0_COUNT /* Get the current count value, 67108864 */ +#define TMR0_ClrCurrentCount() {R8_TMR0_CTRL_MOD |= RB_TMR_ALL_CLEAR;R8_TMR0_CTRL_MOD &= ~RB_TMR_ALL_CLEAR;} +#define TMR0_SET_CNT_END(cnt_end) ({R32_TMR0_CNT_END = (cnt_end);}) + +// Pulse Width Modulation Function +#define TMR0_PWMCycleCfg(cyc) \ + (R32_TMR0_CNT_END = (cyc)) /* PWM0 channel output waveform period configuration, maximum 67108864 */ +void TMR0_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime); /* PWM0 output initialization */ +#define TMR0_PWMActDataWidth(d) (R32_TMR0_FIFO = (d)) /* PWM0 effective data pulse width, maximum 67108864 */ + +// Catch pulse width +#define TMR0_CAPTimeoutCfg(cyc) \ + (R32_TMR0_CNT_END = (cyc)) /* CAP0 capture level timeout configuration, maximum 33554432 */ +void TMR0_CapInit(CapModeTypeDef capedge,CapWidthTypedef widt); /* External signal capture function initialization */ +#define TMR0_CAPGetData() R32_TMR0_FIFO /* Get pulse data */ +#define TMR0_CAPDataCounter() R8_TMR0_FIFO_COUNT /* Get the number of currently captured data */ +void TMR0_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode); /* DMA configuration */ + +#define TMR0_Disable() (R8_TMR0_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* Close TMR0 */ +#define TMR0_Enable() (R8_TMR0_CTRL_MOD |= RB_TMR_COUNT_EN) /* Open TMR0 */ +// refer to TMR0 interrupt bit define +#define TMR0_ITCfg(cfglist, en) \ + BITS_CFG(R8_TMR0_INTER_EN, (cfglist), (en)) /* TMR0 corresponding interrupt bit on and off */ +// refer to TMR0 interrupt bit define +#define TMR0_ClearITFlag(f) (R8_TMR0_INT_FLAG = (f)) /* Clear interrupt flag */ +#define TMR0_GetITFlag(f) (R8_TMR0_INT_FLAG & (f)) /* Query interrupt flag status */ + +#define TMR0_DMA_SET_RANGE(start, end) \ +({ \ + R32_TMR0_DMA_BEG = (start)&MASK_TMR_DMA_ADDR; \ + R32_TMR0_DMA_END = (end)&MASK_TMR_DMA_ADDR; \ +}) +#define TMR0_DMA_GET_BEG() (R32_TMR0_DMA_BEG) +#define TMR0_DMA_GET_END() (R32_TMR0_DMA_END) +#define TMR0_DMA_GET_NOW() (R32_TMR0_DMA_NOW) + +/****************** TMR1 */ +// Timing and counting +void TMR1_TimerInit(uint32_t arr); /* Timing function initialization */ +#define TMR1_DeInit() (R8_TMR1_CTRL_MOD = 0) +#define TMR1_GetCurrentCount() R32_TMR1_COUNT /* Get the current count value, 67108864 */ +#define TMR1_ClrCurrentCount() {R8_TMR1_CTRL_MOD |= RB_TMR_ALL_CLEAR;R8_TMR1_CTRL_MOD &= ~RB_TMR_ALL_CLEAR;} +#define TMR1_SET_CNT_END(cnt_end) ({R32_TMR1_CNT_END = (cnt_end);}) + +// Pulse Width Modulation Function +#define TMR1_PWMCycleCfg(cyc) \ + (R32_TMR1_CNT_END = (cyc)) /* PWM1 channel output waveform period configuration, maximum 67108864 */ +void TMR1_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime); /* PWM1 output initialization */ +#define TMR1_PWMActDataWidth(d) (R32_TMR1_FIFO = (d)) /* PWM1 effective data pulse width, maximum 67108864 */ + +// Catch pulse width +#define TMR1_CAPTimeoutCfg(cyc) \ + (R32_TMR1_CNT_END = (cyc)) /* CAP1 capture level timeout configuration, maximum 33554432 */ +void TMR1_CapInit(CapModeTypeDef capedge,CapWidthTypedef widt); /* External signal capture function initialization */ +#define TMR1_CAPGetData() R32_TMR1_FIFO /* Get pulse data */ +#define TMR1_CAPDataCounter() R8_TMR1_FIFO_COUNT /* Get the number of currently captured data */ + +void TMR1_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode); /* DMA configuration */ + +#define TMR1_Disable() (R8_TMR1_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* Close TMR1 */ +#define TMR1_Enable() (R8_TMR1_CTRL_MOD |= RB_TMR_COUNT_EN) /* Open TMR1 */ +// refer to TMR1 interrupt bit define +#define TMR1_ITCfg(cfglist, en) \ + BITS_CFG(R8_TMR1_INTER_EN, (cfglist), (en)) /* TMR1 corresponding interrupt bit on and off */ +// refer to TMR1 interrupt bit define +#define TMR1_ClearITFlag(f) (R8_TMR1_INT_FLAG = (f)) /* Clear interrupt flag */ +#define TMR1_GetITFlag(f) (R8_TMR1_INT_FLAG & (f)) /* Query interrupt flag status */ + +#define TMR1_DMA_SET_RANGE(start, end) \ +({ \ + R32_TMR1_DMA_BEG = (start)&MASK_TMR_DMA_ADDR; \ + R32_TMR1_DMA_END = (end)&MASK_TMR_DMA_ADDR; \ +}) +#define TMR1_DMA_GET_BEG() (R32_TMR1_DMA_BEG) +#define TMR1_DMA_GET_END() (R32_TMR1_DMA_END) +#define TMR1_DMA_GET_NOW() (R32_TMR1_DMA_NOW) +/****************** TMR2 */ +// Timing and counting +void TMR2_TimerInit(uint32_t arr); /* Timing function initialization */ +#define TMR2_DeInit() (R8_TMR2_CTRL_MOD = 0) +#define TMR2_GetCurrentCount() R32_TMR2_COUNT /* Get the current count value, 67108864 */ +#define TMR2_ClrCurrentCount() {R8_TMR2_CTRL_MOD |= RB_TMR_ALL_CLEAR;R8_TMR2_CTRL_MOD &= ~RB_TMR_ALL_CLEAR;} +#define TMR2_SET_CNT_END(cnt_end) ({R32_TMR2_CNT_END = (cnt_end);}) + +// Pulse Width Modulation Function +#define TMR2_PWMCycleCfg(cyc) \ + (R32_TMR2_CNT_END = (cyc)) /* PWM2 channel output waveform period configuration, maximum 67108864 */ +void TMR2_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime); /* PWM2 output initialization */ +#define TMR2_PWMActDataWidth(d) (R32_TMR2_FIFO = (d)) /* PWM2 effective data pulse width, maximum 67108864 */ + +// Catch pulse width +#define TMR2_CAPTimeoutCfg(cyc) \ + (R32_TMR2_CNT_END = (cyc)) /* CAP2 capture level timeout configuration, maximum 33554432 */ +void TMR2_CapInit(CapModeTypeDef capedge,CapWidthTypedef widt); /* External signal capture function initialization */ +#define TMR2_CAPGetData() R32_TMR2_FIFO /* Get pulse data */ +#define TMR2_CAPDataCounter() R8_TMR2_FIFO_COUNT /* Get the number of currently captured data */ + +void TMR2_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode); /* DMA configuration */ + +#define TMR2_Disable() (R8_TMR2_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* Close TMR2 */ +#define TMR2_Enable() (R8_TMR2_CTRL_MOD |= RB_TMR_COUNT_EN) /* Open TMR2 */ +// refer to TMR2 interrupt bit define +#define TMR2_ITCfg(cfglist, en) \ + BITS_CFG(R8_TMR2_INTER_EN, (cfglist), (en)) /* TMR2 corresponding interrupt bit on and off */ +// refer to TMR2 interrupt bit define +#define TMR2_ClearITFlag(f) (R8_TMR2_INT_FLAG = (f)) /* Clear interrupt flag */ +#define TMR2_GetITFlag(f) (R8_TMR2_INT_FLAG & (f)) /* Query interrupt flag status */ + +#define TMR2_DMA_SET_RANGE(start, end) \ +({ \ + R32_TMR2_DMA_BEG = (start)&MASK_TMR_DMA_ADDR; \ + R32_TMR2_DMA_END = (end)&MASK_TMR_DMA_ADDR; \ +}) +#define TMR2_DMA_GET_BEG() (R32_TMR2_DMA_BEG) +#define TMR2_DMA_GET_END() (R32_TMR2_DMA_END) +#define TMR2_DMA_GET_NOW() (R32_TMR2_DMA_NOW) +/****************** TMR3 */ +// Timing and counting +void TMR3_TimerInit(uint32_t arr); /* Timing function initialization */ +#define TMR3_DeInit() (R8_TMR3_CTRL_MOD = 0) +void TMR3_EXTSignalCounterInit(uint32_t arr, CapModeTypeDef capedge, + CapWidthTypedef capwidth); /* External signal counting function initialization */ +#define TMR3_GetCurrentCount() R32_TMR3_COUNT /* Get the current count value, 67108864 */ +#define TMR3_ClrCurrentCount() {R8_TMR3_CTRL_MOD |= RB_TMR_ALL_CLEAR;R8_TMR3_CTRL_MOD &= ~RB_TMR_ALL_CLEAR;} + +#define TMR3_SET_CNT_END(cnt_end) ({R32_TMR3_CNT_END = (cnt_end);}) + +// Pulse Width Modulation Function +#define TMR3_PWMCycleCfg(cyc) \ + (R32_TMR3_CNT_END = (cyc)) /* PWM2 channel output waveform period configuration, maximum 67108864 */ +void TMR3_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime); /* PWM2 output initialization */ +#define TMR3_PWMActDataWidth(d) (R32_TMR3_FIFO = (d)) /* PWM2 effective data pulse width, maximum 67108864 */ + +// Catch pulse width +#define TMR3_CAPTimeoutCfg(cyc) \ + (R32_TMR3_CNT_END = (cyc)) /* CAP2 capture level timeout configuration, maximum 33554432 */ +void TMR3_CapInit(CapModeTypeDef capedge,CapWidthTypedef widt); /* External signal capture function initialization */ +#define TMR3_CAPGetData() R32_TMR3_FIFO /* Get pulse data */ +#define TMR3_CAPDataCounter() R8_TMR3_FIFO_COUNT /* Get the number of currently captured data */ + +#define TMR3_Disable() (R8_TMR3_CTRL_MOD &= ~RB_TMR_COUNT_EN) /* Close TMR3 */ +#define TMR3_Enable() (R8_TMR3_CTRL_MOD |= RB_TMR_COUNT_EN) /* Close TMR3 */ +// refer to TMR3 interrupt bit define +#define TMR3_ITCfg(cfglist, en) \ + BITS_CFG(R8_TMR3_INTER_EN, (cfglist), (en)) /* TMR3 corresponding interrupt bit on and off */ +// refer to TMR3 interrupt bit define +#define TMR3_ClearITFlag(f) (R8_TMR3_INT_FLAG = (f)) /* Clear interrupt flag */ +#define TMR3_GetITFlag(f) (R8_TMR3_INT_FLAG & (f)) /* Query interrupt flag status */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_uart.h b/Peripheral/inc/ch564_uart.h new file mode 100644 index 0000000..ec32dff --- /dev/null +++ b/Peripheral/inc/ch564_uart.h @@ -0,0 +1,259 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_uart.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * UART firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_UART_H +#define __CH564_UART_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "ch564.h" + +/** + * @brief Line Error Status Definition + */ +#define STA_ERR_BREAK RB_LSR_BREAK_ERR // Data Interval Error +#define STA_ERR_FRAME RB_LSR_FRAME_ERR // DataFrame error +#define STA_ERR_PAR RB_LSR_PAR_ERR // Parity bit error +#define STA_ERR_FIFOOV RB_LSR_OVER_ERR // Receive Data Overflow + +#define STA_TXFIFO_EMP RB_LSR_TX_FIFO_EMP // The current send FIFO is empty, you can continue to fill the send data +#define STA_TXALL_EMP RB_LSR_TX_ALL_EMP // All currently sent data has been sent +#define STA_RECV_DATA RB_LSR_DATA_RDY // Data is currently received + +/** + * @brief Serial port byte trigger configuration + */ +typedef enum { + UART_1BYTE_TRIG = 0, // 1 byte trigger + UART_2BYTE_TRIG = 1, // 2 byte trigger + UART_4BYTE_TRIG = 2, // 4 byte trigger + UART_7BYTE_TRIG = 3, // 7 byte trigger + +} UARTByteTRIGTypeDef; + +/****************** UART0 */ +void UART0_DefInit (void); /* Serial port default initialization configuration */ +void UART0_BaudRateCfg (uint32_t baudrate); /* Serial port baud rate configuration */ +void UART0_ByteTrigCfg (UARTByteTRIGTypeDef UARTByteTRIG); /* Serial byte trigger interrupt configuration */ +void UART0_INTCfg (FunctionalState NewSTA, uint8_t RB_IER); /* Serial port interrupt configuration */ +void UART0_Reset (void); /* Serial port software reset */ + +#define UART0_SET_DLV(dlv) ({ R8_UART0_DIV = (dlv); }) + +#define UART0_CLR_RXFIFO() (R8_UART0_FCR |= RB_FCR_RX_FIFO_CLR) /* Clear the current receive FIFO */ +#define UART0_CLR_TXFIFO() (R8_UART0_FCR |= RB_FCR_TX_FIFO_CLR) /* Clear the current transmit FIFO */ + +#define UART0_GetITFlag() (R8_UART0_IIR & (RB_IIR_NO_INT | RB_IIR_INT_MASK)) /* Get the current interrupt flag */ + +#define UART0_SET_FCR(cfglist, en) BITS_CFG (R8_UART0_FCR, (cfglist), (en)) +#define UART0_SET_LCR(cfglist, en) BITS_CFG (R8_UART0_LCR, (cfglist), (en)) +#define UART0_SET_MCR(cfglist, en) BITS_CFG (R8_UART0_MCR, (cfglist), (en)) + +#define UART0_SET_RTS() UART0_SET_MCR(RB_MCR_RTS,ENABLE) +#define UART0_SET_DTR() UART0_SET_MCR(RB_MCR_DTR,ENABLE) +#define UART0_RESET_RTS() UART0_SET_MCR(RB_MCR_RTS,DISABLE) +#define UART0_RESET_DTR() UART0_SET_MCR(RB_MCR_DTR,DISABLE) + +// please refer to LINE error and status define +#define UART0_GetLinSTA() (R8_UART0_LSR) /* Get the current communication status */ +#define UART0_GetMSRSTA() (R8_UART0_MSR) /* Get the current flow control status, only applicable to UART0 */ + +#define UART0_DMACFG(cfglist, en) BITS_CFG (R8_UART0_DMA_CTRL, (cfglist), (en)) +#define UART0_DMA_SET_RD_RANGE(start, end) \ + ({ \ + R32_UART0_DMA_RD_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART0_DMA_RD_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART0_DMA_GET_RD_CURRENT_ADDR() (R32_UART0_DMA_RD_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_GET_RD_BEG_ADDR() (R32_UART0_DMA_RD_START_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_GET_RD_END_ADDR() (R32_UART0_DMA_RD_END_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_SET_WR_RANGE(start, end) \ + ({ \ + R32_UART0_DMA_WR_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART0_DMA_WR_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART0_DMA_GET_WR_CURRENT_ADDR() (R32_UART0_DMA_WR_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_GET_WR_BEG_ADDR() (R32_UART0_DMA_WR_START_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_GET_WR_END_ADDR() (R32_UART0_DMA_WR_END_ADDR & MASK_UART_DMA_ADDR) +#define UART0_DMA_GET_IT_FLAG(dmaif) (R8_UART0_DMA_IF & (dmaif)) + +#define UART0_SendByte(b) (R8_UART0_THR = (b)) /* Serial port single byte transmission */ +void UART0_SendString (uint8_t *buf, uint16_t length); /* Serial multi-byte transmission */ +void UART0_Send_DMA (uint8_t *buf, uint32_t lenth); +void UART0_Recv_DMA (uint8_t *buf, uint32_t lenth); +#define UART0_RecvByte() (R8_UART0_RBR) /* Serial port read single byte */ +uint16_t UART0_RecvString (uint8_t *buf); /* Serial port read multibyte */ +void UART0_DTRDSR_Cfg(FunctionalState en); +void UART0_CTSRTS_Cfg(GPIO_Typedef* GPIOx, FunctionalState en,FunctionalState auto_ctrl_en); + +/****************** UART1 */ +void UART1_DefInit (void); /* Serial port default initialization configuration */ +void UART1_BaudRateCfg (uint32_t baudrate); /* Serial port baud rate configuration */ +void UART1_ByteTrigCfg (UARTByteTRIGTypeDef UARTByteTRIG); /* Serial byte trigger interrupt configuration */ +void UART1_INTCfg (FunctionalState NewSTA, uint8_t RB_IER); /* Serial port interrupt configuration */ +void UART1_Reset (void); /* Serial port software reset */ + +#define UART1_SET_DLV(dlv) ({ R8_UART1_DIV = dlv; }) + +#define UART1_CLR_RXFIFO() (R8_UART1_FCR |= RB_FCR_RX_FIFO_CLR) /* Clear the current receive FIFO */ +#define UART1_CLR_TXFIFO() (R8_UART1_FCR |= RB_FCR_TX_FIFO_CLR) /* Clear the current transmit FIFO */ + +#define UART1_GetITFlag() (R8_UART1_IIR & (RB_IIR_NO_INT | RB_IIR_INT_MASK)) /* Get the current interrupt flag */ + +#define UART1_SET_FCR(cfglist, en) BITS_CFG (R8_UART1_FCR, (cfglist), (en)) +#define UART1_SET_LCR(cfglist, en) BITS_CFG (R8_UART1_LCR, (cfglist), (en)) +#define UART1_SET_MCR(cfglist, en) BITS_CFG (R8_UART1_MCR, (cfglist), (en)) + +#define UART1_SET_RTS() UART1_SET_MCR(RB_MCR_RTS,ENABLE) +#define UART1_RESET_RTS() UART1_SET_MCR(RB_MCR_RTS,DISABLE) + +// please refer to LINE error and status define +#define UART1_GetLinSTA() (R8_UART1_LSR) /* Get the current communication status */ +#define UART1_GetMSRSTA() (R8_UART1_MSR) /* Get the current flow control status, only applicable to UART1 */ + +#define UART1_DMACFG(cfglist, en) BITS_CFG (R8_UART1_DMA_CTRL, (cfglist), (en)) +#define UART1_DMA_SET_RD_RANGE(start, end) \ + ({ \ + R32_UART1_DMA_RD_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART1_DMA_RD_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART1_DMA_GET_RD_CURRENT_ADDR() (R32_UART1_DMA_RD_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_GET_RD_BEG_ADDR() (R32_UART1_DMA_RD_START_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_GET_RD_END_ADDR() (R32_UART1_DMA_RD_END_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_SET_WR_RANGE(start, end) \ + ({ \ + R32_UART1_DMA_WR_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART1_DMA_WR_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART1_DMA_GET_WR_CURRENT_ADDR() (R32_UART1_DMA_WR_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_GET_WR_BEG_ADDR() (R32_UART1_DMA_WR_START_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_GET_WR_END_ADDR() (R32_UART1_DMA_WR_END_ADDR & MASK_UART_DMA_ADDR) +#define UART1_DMA_GET_IT_FLAG(dmaif) (R8_UART1_DMA_IF & (dmaif)) + +#define UART1_SendByte(b) (R8_UART1_THR = (b)) /* Serial port single byte transmission */ +void UART1_SendString (uint8_t *buf, uint16_t length); /* Serial multi-byte transmission */ +void UART1_Send_DMA (uint8_t *buf, uint32_t lenth); +void UART1_Recv_DMA (uint8_t *buf, uint32_t lenth); +#define UART1_RecvByte() (R8_UART1_RBR) /* Serial port read single byte */ +uint16_t UART1_RecvString (uint8_t *buf); /* Serial port read multibyte */ +void UART1_CTSRTS_Cfg(GPIO_Typedef* GPIOx, FunctionalState en,FunctionalState auto_ctrl_en); + +/****************** UART2 */ +void UART2_DefInit (void); /* Serial port default initialization configuration */ +void UART2_BaudRateCfg (uint32_t baudrate); /* Serial port baud rate configuration */ +void UART2_ByteTrigCfg (UARTByteTRIGTypeDef UARTByteTRIG); /* Serial byte trigger interrupt configuration */ +void UART2_INTCfg (FunctionalState NewSTA, uint8_t RB_IER); /* Serial port interrupt configuration */ +void UART2_Reset (void); /* Serial port software reset */ + +#define UART2_SET_DLV(dlv) ({ R8_UART2_DIV = (dlv); }) + +#define UART2_CLR_RXFIFO() (R8_UART2_FCR |= RB_FCR_RX_FIFO_CLR) /* Clear the current receive FIFO */ +#define UART2_CLR_TXFIFO() (R8_UART2_FCR |= RB_FCR_TX_FIFO_CLR) /* Clear the current transmit FIFO */ + +#define UART2_GetITFlag() (R8_UART2_IIR & (RB_IIR_NO_INT | RB_IIR_INT_MASK)) /* Get the current interrupt flag */ + +#define UART2_SET_FCR(cfglist, en) BITS_CFG (R8_UART2_FCR, (cfglist), (en)) +#define UART2_SET_LCR(cfglist, en) BITS_CFG (R8_UART2_LCR, (cfglist), (en)) +#define UART2_SET_MCR(cfglist, en) BITS_CFG (R8_UART2_MCR, (cfglist), (en)) + +#define UART2_SET_RTS() UART2_SET_MCR(RB_MCR_RTS,ENABLE) +#define UART2_RESET_RTS() UART2_SET_MCR(RB_MCR_RTS,DISABLE) + +// please refer to LINE error and status define +#define UART2_GetLinSTA() (R8_UART2_LSR) /* Get the current communication status */ +#define UART2_GetMSRSTA() (R8_UART2_MSR) /* Get the current flow control status, only applicable to UART2 */ + +#define UART2_DMACFG(cfglist, en) BITS_CFG (R8_UART2_DMA_CTRL, (cfglist), (en)) +#define UART2_DMA_SET_RD_RANGE(start, end) \ + ({ \ + R32_UART2_DMA_RD_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART2_DMA_RD_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART2_DMA_GET_RD_CURRENT_ADDR() (R32_UART2_DMA_RD_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_GET_RD_BEG_ADDR() (R32_UART2_DMA_RD_START_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_GET_RD_END_ADDR() (R32_UART2_DMA_RD_END_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_SET_WR_RANGE(start, end) \ + ({ \ + R32_UART2_DMA_WR_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART2_DMA_WR_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART2_DMA_GET_WR_CURRENT_ADDR() (R32_UART2_DMA_WR_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_GET_WR_BEG_ADDR() (R32_UART2_DMA_WR_START_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_GET_WR_END_ADDR() (R32_UART2_DMA_WR_END_ADDR & MASK_UART_DMA_ADDR) +#define UART2_DMA_GET_IT_FLAG(dmaif) (R8_UART2_DMA_IF & (dmaif)) + +#define UART2_SendByte(b) (R8_UART2_THR = (b)) /* Serial port single byte transmission */ +void UART2_SendString (uint8_t *buf, uint16_t length); /* Serial multi-byte transmission */ +void UART2_Send_DMA (uint8_t *buf, uint32_t lenth); +void UART2_Recv_DMA (uint8_t *buf, uint32_t lenth); +#define UART2_RecvByte() (R8_UART2_RBR) /* Serial port read single byte */ +uint16_t UART2_RecvString (uint8_t *buf); /* Serial port read multibyte */ +void UART2_CTSRTS_Cfg(GPIO_Typedef* GPIOx, FunctionalState en,FunctionalState auto_ctrl_en); + +/****************** UART3 */ +void UART3_DefInit (void); /* Serial port default initialization configuration */ +void UART3_BaudRateCfg (uint32_t baudrate); /* Serial port baud rate configuration */ +void UART3_ByteTrigCfg (UARTByteTRIGTypeDef UARTByteTRIG); /* Serial byte trigger interrupt configuration */ +void UART3_INTCfg (FunctionalState NewSTA, uint8_t RB_IER); /* Serial port interrupt configuration */ +void UART3_Reset (void); /* Serial port software reset */ + +#define UART3_SET_DLV(dlv) ({ R8_UART3_DIV = dlv; }) + +#define UART3_CLR_RXFIFO() (R8_UART3_FCR |= RB_FCR_RX_FIFO_CLR) /* Clear the current receive FIFO */ +#define UART3_CLR_TXFIFO() (R8_UART3_FCR |= RB_FCR_TX_FIFO_CLR) /* Clear the current transmit FIFO */ + +#define UART3_GetITFlag() (R8_UART3_IIR & (RB_IIR_NO_INT | RB_IIR_INT_MASK)) /* Get the current interrupt flag */ + +#define UART3_SET_FCR(cfglist, en) BITS_CFG (R8_UART3_FCR, (cfglist), (en)) +#define UART3_SET_LCR(cfglist, en) BITS_CFG (R8_UART3_LCR, (cfglist), (en)) +#define UART3_SET_MCR(cfglist, en) BITS_CFG (R8_UART3_MCR, (cfglist), (en)) + +#define UART3_SET_RTS() UART3_SET_MCR(RB_MCR_RTS,ENABLE) +#define UART3_RESET_RTS() UART3_SET_MCR(RB_MCR_RTS,DISABLE) + +// please refer to LINE error and status define +#define UART3_GetLinSTA() (R8_UART3_LSR) /* Get the current communication status */ +#define UART3_GetMSRSTA() (R8_UART3_MSR) /* Get the current flow control status, only applicable to UART3 */ + +#define UART3_DMACFG(cfglist, en) BITS_CFG (R8_UART3_DMA_CTRL, (cfglist), (en)) +#define UART3_DMA_SET_RD_RANGE(start, end) \ + ({ \ + R32_UART3_DMA_RD_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART3_DMA_RD_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART3_DMA_GET_RD_CURRENT_ADDR() (R32_UART3_DMA_RD_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_GET_RD_BEG_ADDR() (R32_UART3_DMA_RD_START_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_GET_RD_END_ADDR() (R32_UART3_DMA_RD_END_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_SET_WR_RANGE(start, end) \ + ({ \ + R32_UART3_DMA_WR_START_ADDR = (uint32_t)(start)&MASK_UART_DMA_ADDR; \ + R32_UART3_DMA_WR_END_ADDR = (uint32_t)(end)&MASK_UART_DMA_ADDR; \ + }) +#define UART3_DMA_GET_WR_CURRENT_ADDR() (R32_UART3_DMA_WR_NOW_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_GET_WR_BEG_ADDR() (R32_UART3_DMA_WR_START_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_GET_WR_END_ADDR() (R32_UART3_DMA_WR_END_ADDR & MASK_UART_DMA_ADDR) +#define UART3_DMA_GET_IT_FLAG(dmaif) (R8_UART3_DMA_IF & (dmaif)) + +#define UART3_SendByte(b) (R8_UART3_THR = (b)) /* Serial port single byte transmission */ +void UART3_SendString (uint8_t *buf, uint16_t length); /* Serial multi-byte transmission */ +void UART3_Send_DMA (uint8_t *buf, uint32_t lenth); +void UART3_Recv_DMA (uint8_t *buf, uint32_t lenth); +#define UART3_RecvByte() (R8_UART3_RBR) /* Serial port read single byte */ +uint16_t UART3_RecvString (uint8_t *buf); /* Serial port read multibyte */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_usb.h b/Peripheral/inc/ch564_usb.h new file mode 100644 index 0000000..137d91a --- /dev/null +++ b/Peripheral/inc/ch564_usb.h @@ -0,0 +1,659 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_usb.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * USB firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_USB_H +#define __CH564_USB_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + + +/* USB standard device request code */ +#ifndef USB_GET_DESCRIPTOR +#define USB_GET_STATUS 0x00 +#define USB_CLEAR_FEATURE 0x01 +#define USB_SET_FEATURE 0x03 +#define USB_SET_ADDRESS 0x05 +#define USB_GET_DESCRIPTOR 0x06 +#define USB_SET_DESCRIPTOR 0x07 +#define USB_GET_CONFIGURATION 0x08 +#define USB_SET_CONFIGURATION 0x09 +#define USB_GET_INTERFACE 0x0A +#define USB_SET_INTERFACE 0x0B +#define USB_SYNCH_FRAME 0x0C +#endif + +#define DEF_STRING_DESC_LANG 0x00 +#define DEF_STRING_DESC_MANU 0x01 +#define DEF_STRING_DESC_PROD 0x02 +#define DEF_STRING_DESC_SERN 0x03 + +/* USB hub class request code */ +#ifndef HUB_GET_DESCRIPTOR +#define HUB_GET_STATUS 0x00 +#define HUB_CLEAR_FEATURE 0x01 +#define HUB_GET_STATE 0x02 +#define HUB_SET_FEATURE 0x03 +#define HUB_GET_DESCRIPTOR 0x06 +#define HUB_SET_DESCRIPTOR 0x07 +#endif + +/* USB HID class request code */ +#ifndef HID_GET_REPORT +#define HID_GET_REPORT 0x01 +#define HID_GET_IDLE 0x02 +#define HID_GET_PROTOCOL 0x03 +#define HID_SET_REPORT 0x09 +#define HID_SET_IDLE 0x0A +#define HID_SET_PROTOCOL 0x0B +#endif + +/* USB CDC Class request code */ +#ifndef CDC_GET_LINE_CODING +#define CDC_GET_LINE_CODING 0x21 /* This request allows the host to find out the currently configured line coding */ +#define CDC_SET_LINE_CODING 0x20 /* Configures DTE rate, stop-bits, parity, and number-of-character */ +#define CDC_SET_LINE_CTLSTE 0x22 /* This request generates RS-232/V.24 style control signals */ +#define CDC_SEND_BREAK 0x23 /* Sends special carrier modulation used to specify RS-232 style break */ +#endif + +/* Bit Define for USB Request Type */ +#ifndef USB_REQ_TYP_MASK +#define USB_REQ_TYP_IN 0x80 +#define USB_REQ_TYP_OUT 0x00 +#define USB_REQ_TYP_READ 0x80 +#define USB_REQ_TYP_WRITE 0x00 +#define USB_REQ_TYP_MASK 0x60 +#define USB_REQ_TYP_STANDARD 0x00 +#define USB_REQ_TYP_CLASS 0x20 +#define USB_REQ_TYP_VENDOR 0x40 +#define USB_REQ_TYP_RESERVED 0x60 +#define USB_REQ_RECIP_MASK 0x1F +#define USB_REQ_RECIP_DEVICE 0x00 +#define USB_REQ_RECIP_INTERF 0x01 +#define USB_REQ_RECIP_ENDP 0x02 +#define USB_REQ_RECIP_OTHER 0x03 +#define USB_REQ_FEAT_REMOTE_WAKEUP 0x01 +#define USB_REQ_FEAT_ENDP_HALT 0x00 +#endif + +/* USB Descriptor Type */ +#ifndef USB_DESCR_TYP_DEVICE +#define USB_DESCR_TYP_DEVICE 0x01 +#define USB_DESCR_TYP_CONFIG 0x02 +#define USB_DESCR_TYP_STRING 0x03 +#define USB_DESCR_TYP_INTERF 0x04 +#define USB_DESCR_TYP_ENDP 0x05 +#define USB_DESCR_TYP_QUALIF 0x06 +#define USB_DESCR_TYP_SPEED 0x07 +#define USB_DESCR_TYP_OTG 0x09 +#define USB_DESCR_TYP_BOS 0X0F +#define USB_DESCR_TYP_HID 0x21 +#define USB_DESCR_TYP_REPORT 0x22 +#define USB_DESCR_TYP_PHYSIC 0x23 +#define USB_DESCR_TYP_CS_INTF 0x24 +#define USB_DESCR_TYP_CS_ENDP 0x25 +#define USB_DESCR_TYP_HUB 0x29 +#endif + +/* USB Device Class */ +#ifndef USB_DEV_CLASS_HUB +#define USB_DEV_CLASS_RESERVED 0x00 +#define USB_DEV_CLASS_AUDIO 0x01 +#define USB_DEV_CLASS_COMMUNIC 0x02 +#define USB_DEV_CLASS_HID 0x03 +#define USB_DEV_CLASS_MONITOR 0x04 +#define USB_DEV_CLASS_PHYSIC_IF 0x05 +#define USB_DEV_CLASS_POWER 0x06 +#define USB_DEV_CLASS_IMAGE 0x06 +#define USB_DEV_CLASS_PRINTER 0x07 +#define USB_DEV_CLASS_STORAGE 0x08 +#define USB_DEV_CLASS_HUB 0x09 +#define USB_DEV_CLASS_VEN_SPEC 0xFF +#endif + +/* USB Hub Class Request */ +#ifndef HUB_GET_HUB_DESCRIPTOR +#define HUB_CLEAR_HUB_FEATURE 0x20 +#define HUB_CLEAR_PORT_FEATURE 0x23 +#define HUB_GET_BUS_STATE 0xA3 +#define HUB_GET_HUB_DESCRIPTOR 0xA0 +#define HUB_GET_HUB_STATUS 0xA0 +#define HUB_GET_PORT_STATUS 0xA3 +#define HUB_SET_HUB_DESCRIPTOR 0x20 +#define HUB_SET_HUB_FEATURE 0x20 +#define HUB_SET_PORT_FEATURE 0x23 +#endif + +/* Hub Class Feature Selectors */ +#ifndef HUB_PORT_RESET +#define HUB_C_HUB_LOCAL_POWER 0 +#define HUB_C_HUB_OVER_CURRENT 1 +#define HUB_PORT_CONNECTION 0 +#define HUB_PORT_ENABLE 1 +#define HUB_PORT_SUSPEND 2 +#define HUB_PORT_OVER_CURRENT 3 +#define HUB_PORT_RESET 4 +#define HUB_PORT_POWER 8 +#define HUB_PORT_LOW_SPEED 9 +#define HUB_C_PORT_CONNECTION 16 +#define HUB_C_PORT_ENABLE 17 +#define HUB_C_PORT_SUSPEND 18 +#define HUB_C_PORT_OVER_CURRENT 19 +#define HUB_C_PORT_RESET 20 +#endif + +/* USB UDisk */ +#ifndef USB_BO_CBW_SIZE +#define USB_BO_CBW_SIZE 0x1F +#define USB_BO_CSW_SIZE 0x0D +#endif +#ifndef USB_BO_CBW_SIG0 +#define USB_BO_CBW_SIG0 0x55 +#define USB_BO_CBW_SIG1 0x53 +#define USB_BO_CBW_SIG2 0x42 +#define USB_BO_CBW_SIG3 0x43 +#define USB_BO_CSW_SIG0 0x55 +#define USB_BO_CSW_SIG1 0x53 +#define USB_BO_CSW_SIG2 0x42 +#define USB_BO_CSW_SIG3 0x53 +#endif + +/*******************************************************************************/ +/* USBHS Related Register Macro Definition */ + +/* USBHS Device Register Definition */ +/* Bit definition for USB_CTRL register */ +#define DEV_LPM_EN 0x80 /* LPM enable */ +#define DEV_EN 0x20 /* USB device enabled */ +#define DEV_DMA_EN 0x10 /* DMA transfer enabled */ +#define PHY_SUSPENDM 0x08 /* USB PHY suspend */ +#define USB_ALL_CLR 0x04 /* clear all interrupt flags */ +#define SIE_RESET 0x02 /* USB protocol processor reset */ +#define LINK_RESET 0x01 + +/* Bit definition for usb_BASE_MODE register */ +#define EXP_SPD_MASK 0x03 /* bit[0:1] controls the desired device speed */ +#define EXP_FS_SPD 0x00 /* Full-speed mode */ +#define EXP_HS_SPD 0x01 /* High-speed mode */ +#define EXP_LOW_SPD 0x02 /* Low-speed mode */ + +/* Bit definition for USB_INT_EN register */ +#define FIFO_OVER_IE 0x80 /* USB Overflow interrupt enable */ +#define LINK_RDY_IE 0x40 /* USB connection interrupt enable */ +#define RX_SOF_IE 0x20 /* Receive SOF packet interrupt enable */ +#define RTX_ACT_IE 0x10 /* USB transfer end interrupt enabled */ +#define LPM_ACT_IE 0x08 /* LMP transfer end interrupt enabled */ +#define BUS_SLEEP_IE 0x04 /* USB bus sleep interrupt enabled */ +#define BUS_SUSP_IE 0x02 /* USB bus pause interrupt enabled */ +#define BUS_REST_IE 0x01 /* USB bus reset interrupt enabled */ + +/* Bit definition for USB_DEV_AD register */ +#define MASK_USB_ADDR 0x7f + +/* Bit definition for USB_WAKE_CR register */ +#define RB_RMT_WAKE 0x01 /* remote wake up */ + +/* Bit definition for USB_TEST_MODE register */ +#define RB_TEST_EN 0x80 /* test mode enable */ +#define RB_TEST_SE0NAK 0x08 /* test mode,output SEO */ +#define RB_TEST_PKT 0x04 /* test mode,output a packet */ +#define RB_TEST_K 0x02 /* test mode,output K */ +#define RB_TEST_J 0x01 /* test mode,output J */ + +/* Bit definition for USB_LPM_DATA register */ +#define LPM_BUSY 0x8000 +#define LPM_DATA 0x07ff /* read-only power management data */ + +/* Bit definition for USB_INT_FG register */ +#define FIFO_OVER_IF 0x80 /* read-write USB Overflow interrupt flag */ +#define LINK_RDY_IF 0x40 /* read-write USB connection interrupt flag */ +#define RX_SOF_IF 0x20 /* read-write Receive SOF packet interrupt flag */ +#define RTX_ACT_IF 0x10 /* read-only USB transmission end interrupt flag */ +#define LPM_ACT_IF 0x08 /* read-write LPM transmission end interrupt flag */ +#define BUS_SLEEP_IF 0x04 /* read-write USB bus sleep interrupt flag */ +#define BUS_SUSP_IF 0x02 /* read-write USB bus suspend interrupt flag */ +#define BUS_REST_IF 0x01 /* read-write USB bus reset interrupt flag */ + +/* Bit definition for USB_INT_ST register */ +#define RB_UIS_EP_DIR 0x10 /* Endpoint data transmission direction */ +#define RB_UIS_EP_ID_MASK 0x07 /* The endpoint number at which the data transfer occurs */ + +/* Bit definition for USB_MIS_ST register */ +#define RB_UMS_HS_MOD 0x80 /* whether the host is high-speed */ +#define RB_UMS_SUSP_REQ 0x10 /* USB suspends the request */ +#define RB_UMS_FREE 0x08 /* USB free status */ +#define RB_UMS_SLEEP 0x04 /* USB sleep status */ +#define RB_UMS_SUSPEND 0x02 /* USB suspend status */ +#define RB_UMS_READY 0x01 /* USB connection status */ + +/* Bit definition for USB_FRAMME_NO register */ +#define MICRO_FRAME 0xe000 /* Received micro frame number */ +#define FRAME_NO 0x07ff /* Received frame number */ + +/* Bit definition for USB_BUS register */ +#define USB_DM_ST 0x0008 /* read-only UDM status */ +#define USB_DP_ST 0x0004 /* read-only UDP status */ +#define USB_WAKEUP 0x0001 /* read-only USB wakeup */ + +/* Bit definition for DEV_UEP_TX_EN & DEV_UEP_RX_EN register */ +#define RB_EP0_EN 0x0001 +#define RB_EP1_EN 0x0002 +#define RB_EP2_EN 0x0004 +#define RB_EP3_EN 0x0008 +#define RB_EP4_EN 0x0010 +#define RB_EP5_EN 0x0020 +#define RB_EP6_EN 0x0040 +#define RB_EP7_EN 0x0080 +#define RB_EP8_EN 0x0100 +#define RB_EP9_EN 0x0200 +#define RB_EP10_EN 0x0400 +#define RB_EP11_EN 0x0800 +#define RB_EP12_EN 0x1000 +#define RB_EP13_EN 0x2000 +#define RB_EP14_EN 0x4000 +#define RB_EP15_EN 0x8000 + +/* Bit definition for DEV_UEP_T_TOG_AUTO register */ +#define EP0_T_TOG_AUTO 0x01 +#define EP1_T_TOG_AUTO 0x02 +#define EP2_T_TOG_AUTO 0x04 +#define EP3_T_TOG_AUTO 0x08 +#define EP4_T_TOG_AUTO 0x10 +#define EP5_T_TOG_AUTO 0x20 +#define EP6_T_TOG_AUTO 0x40 +#define EP7_T_TOG_AUTO 0x80 + +/* Bit definition for DEV_UEP_R_TOG_AUTO register */ +#define EP0_R_TOG_AUTO 0x01 +#define EP1_R_TOG_AUTO 0x02 +#define EP2_R_TOG_AUTO 0x04 +#define EP3_R_TOG_AUTO 0x08 +#define EP4_R_TOG_AUTO 0x10 +#define EP5_R_TOG_AUTO 0x20 +#define EP6_R_TOG_AUTO 0x40 +#define EP7_R_TOG_AUTO 0x80 + +/* Bit definition for DEV_UEP_T_BURST register */ +#define EP0_T_BURST_EN 0x01 +#define EP1_T_BURST_EN 0x02 +#define EP2_T_BURST_EN 0x04 +#define EP3_T_BURST_EN 0x08 +#define EP4_T_BURST_EN 0x10 +#define EP5_T_BURST_EN 0x20 +#define EP6_T_BURST_EN 0x40 +#define EP7_T_BURST_EN 0x80 + +/* Bit definition for DEV_UEP_T_BURST_MODE register */ +#define EP0_T_BURST_MODE 0x01 +#define EP1_T_BURST_MODE 0x02 +#define EP2_T_BURST_MODE 0x04 +#define EP3_T_BURST_MODE 0x08 +#define EP4_T_BURST_MODE 0x10 +#define EP5_T_BURST_MODE 0x20 +#define EP6_T_BURST_MODE 0x40 +#define EP7_T_BURST_MODE 0x80 + +/* Bit definition for DEV_UEP_R_BURST register */ +#define EP0_R_BURST_EN 0x01 +#define EP1_R_BURST_EN 0x02 +#define EP2_R_BURST_EN 0x04 +#define EP3_R_BURST_EN 0x08 +#define EP4_R_BURST_EN 0x10 +#define EP5_R_BURST_EN 0x20 +#define EP6_R_BURST_EN 0x40 +#define EP7_R_BURST_EN 0x80 + +/* Bit definition for DEV_UEP_R_RES_MODE register */ +#define EP0_R_RES_MODE 0x01 +#define EP1_R_RES_MODE 0x02 +#define EP2_R_RES_MODE 0x04 +#define EP3_R_RES_MODE 0x08 +#define EP4_R_RES_MODE 0x10 +#define EP5_R_RES_MODE 0x20 +#define EP6_R_RES_MODE 0x40 +#define EP7_R_RES_MODE 0x80 + +/* Bit definition for DEV_UEP_AF_MODE register */ +#define EP1_T_AF 0x02 +#define EP2_T_AF 0x04 +#define EP3_T_AF 0x08 +#define EP4_T_AF 0x10 +#define EP5_T_AF 0x20 +#define EP6_T_AF 0x40 +#define EP7_T_AF 0x80 + +/* Bit definition for UEPx_TX_CTRL register */ +#define USBHS_UEP_T_RES_MASK 0x03 /* Response control mask for endpoint 0 transmission */ +#define USBHS_UEP_T_RES_NAK 0x00 /* UEP0_TX_CTRL[0:1] = 00, reply NAK to host */ +#define USBHS_UEP_T_RES_STALL 0x01 /* UEP0_TX_CTRL[0:1] = 01, reply STALL to host */ +#define USBHS_UEP_T_RES_ACK 0x02 /* UEP0_TX_CTRL[0:1] = 10, reply ACK to host */ +#define USBHS_UEP_T_RES_NYET 0x03 /* UEP0_TX_CTRL[0:1] = 11, reply NYET to host */ +#define USBHS_UEP_T_TOG_MASK 0x0C /* Synchronization trigger bit mask */ +#define USBHS_UEP_T_TOG_DATA0 0x00 /* UEP0_TX_CTRL[2:3] = 00, represents DATA0 */ +#define USBHS_UEP_T_TOG_DATA1 0x04 /* UEP0_TX_CTRL[2:3] = 01, represents DATA1 */ +#define USBHS_UEP_T_TOG_DATA2 0x08 /* UEP0_TX_CTRL[2:3] = 10, represents DATA2 */ +#define USBHS_UEP_T_TOG_MDATA 0x0C /* UEP0_TX_CTRL[2:3] = 11, represents MDATA */ +#define USBHS_UEP_ENDP_T_DONE 0x80 /* Writing 0 clears the interrupt */ + +/* Bit definition for UEPx_RX_CTRL register */ +#define USBHS_UEP_R_RES_MASK 0x03 /* Response control mask for endpoint 0 transmission */ +#define USBHS_UEP_R_RES_NAK 0x00 /* UEP0_TX_CTRL[0:1] = 00, reply NAK to host */ +#define USBHS_UEP_R_RES_STALL 0x01 /* UEP0_TX_CTRL[0:1] = 01, reply STALL to host */ +#define USBHS_UEP_R_RES_ACK 0x02 /* UEP0_TX_CTRL[0:1] = 10, reply ACK to host */ +#define USBHS_UEP_R_RES_NYET 0x03 /* UEP0_TX_CTRL[0:1] = 11, reply NYET to host */ +#define USBHS_UEP_R_TOG_MASK 0x0C /* Synchronization trigger bit mask */ +#define USBHS_UEP_R_TOG_DATA0 0x00 /* UEP0_TX_CTRL[2:3] = 00, represents DATA0 */ +#define USBHS_UEP_R_TOG_DATA1 0x04 /* UEP0_TX_CTRL[2:3] = 01, represents DATA1 */ +#define USBHS_UEP_R_TOG_DATA2 0x08 /* UEP0_TX_CTRL[2:3] = 10, represents DATA2 */ +#define USBHS_UEP_R_TOG_MDATA 0x0C /* UEP0_TX_CTRL[2:3] = 11, represents MDATA */ +#define USBHS_UEP_ENDP_T_DONE 0x80 /* Writing 0 clears the interrupt */ +#define USBHS_UEP_ENDP_R_DONE 0x80 /* Writing 0 clears the interrupt */ +#define USBHS_RB_SETUP_IS 0x08 /* Indicates whether the reception of endpoint 0 is a Setup transaction */ +#define USBHS_ENDP_R_TOG_MATCH 0x10 + +/* Bit definition for DEV_UEP_T_ISO register */ +#define EP1_T_ISO 0x02 +#define EP2_T_ISO 0x04 +#define EP3_T_ISO 0x08 +#define EP4_T_ISO 0x10 +#define EP5_T_ISO 0x20 +#define EP6_T_ISO 0x40 +#define EP7_T_ISO 0x80 + +/* Bit definition for DEV_UEP_R_ISO register */ +#define EP1_R_ISO 0x02 +#define EP2_R_ISO 0x04 +#define EP3_R_ISO 0x08 +#define EP4_R_ISO 0x10 +#define EP5_R_ISO 0x20 +#define EP6_R_ISO 0x40 +#define EP7_R_ISO 0x80 + +/* USBHS Host Register Definition */ +/* Bit definition for UHOST_CTRL register */ +#define root_LPM_EN (1<<7) +#define ROOT_FORCE_FS (1<<6) +#define ROOT_SOF_EN (1<<5) +#define ROOT_DMA_EN (1<<4) +#define ROOT_PHY_SUSPENDM (1<<3) +#define ROOT_ALL_CLR (1<<2) +#define ROOT_SIE_RESET (1<<1) +#define ROOT_LINK_RESET (1<<0) + +/* Bit definition for UH_INT_EN register */ +#define FIFO_OV_IE (1<<7) +#define TX_HALT_IE (1<<6) +#define SOF_ACT_IE (1<<5) +#define USB_ACT_IE (1<<4) +#define RESUME_ACT_IE (1<<3) +#define WKUP_ACT_IE (1<<2) + +/* Bit definition for UH_CONTROL register */ +#define RX_NO_RES (1<<23) +#define TX_NO_RES (1<<22) +#define RX_NO_DATA (1<<21) +#define TX_NO_DATA (1<<20) +#define TX_LOW_SPD (1<<19) +#define SPLIT_VALID (1<<18) +#define LPM_VALID (1<<17) +#define HOST_ACTION (1<<16) +#define BUF_MODE (1<<10) +#define TOG_MASK (3<<8) +#define TOG_MDATA (3<<8) +#define TOG_DATA2 (2<<8) +#define TOG_DATA1 (1<<8) +#define TOG_DATA0 (0<<8) + +/* Bit definition for UH_INT_FLAG register */ +#define RB_FIFO_OV_IF (1<<7) +#define RB_TX_HALT_IF (1<<6) +#define RB_SOF_ACT_IF (1<<5) +#define RB_USB_ACT_IF (1<<4) +#define RB_RESUME_ACT_IF (1<<3) +#define RB_WKUP_IF (1<<2) + +/* Bit definition for UH_INT_ST register */ +#define PORT_RX_RESUME (1<<4) +#define USB_PID_MASK 0x0f +#define USB_PID_TOUT 0x0 +#define USB_PID_ACK 0x2 +#define USB_PID_NAK 0xa +#define USB_PID_STALL 0xe +#define USB_PID_NYET 0x6 +#define USB_PID_DATA0 0x3 +#define USB_PID_DATA1 0xb +#define USB_PID_DATA2 0x7 +#define USB_PID_MDATA 0xf + +#define USB_PID_PRE 0xc +#define USB_PID_ERR 0xc +#define USB_PID_SPLIT 0x8 +#define USB_PID_PING 0x4 +#define USB_PID_SOF 0x5 +#define USB_PID_SETUP 0xd +#define USB_PID_IN 0x9 +#define USB_PID_OUT 0x1 + +/* Bit definition for UH_MIS_ST register */ +#define RB_BUS_SE0 (1<<7) +#define RB_BUS_J (1<<6) +#define RB_LINESTATE_MASK (0x3<<4) +#define RB_USB_WAKEUP (1<<3) +#define RB_SOF_ST (1<<2) +#define RB_SOF_PRE (1<<1) +#define RB_SOF_FREE (1<<0) + +/* Bit definition for UH_FRAME register */ +#define SOF_CNT_CLR (1<<25) +#define SOF_CNT_EN (1<<24) + +/* Bit definition for PORT_CTRL register */ +#define BUS_RST_LONG (1<<16) +#define PORT_SLEEP_BESL (0xf<<12) +#define CLR_PORT_SLEEP (1<<8) +#define CLR_PORT_CONNECT (1<<5) +#define CLR_PORT_EN (1<<4) +#define SET_PORT_SLEEP (1<<3) +#define CLR_PORT_SUSP (1<<2) +#define SET_PORT_SUSP (1<<1) +#define SET_PORT_RESET (1<<0) + +/* Bit definition for PORT_CFG register */ +#define PORT_15K_RPD (1<<7) +#define PORT_HOST_MODE (1<<0)//1: HOST function +#define PORT_DEVICE_MODE (0<<0)//0: DEVICE function + +/* Bit definition for PORT_INT_EN register */ +#define PORT_SLP_IE (1<<5) +#define PORT_RESET_IE (1<<4) +#define PORT_SUSP_IE (1<<2) +#define PORT_EN_IE (1<<1) +#define PORT_CONNECT_IE (1<<0) + +/* Bit definition for PORT_TEST_CT register */ +#define TEST_FORCE_EN (1<<2) +#define TEST_K (1<<1) +#define TEST_J (1<<0) + +/* Bit definition for PORT_STATUS register */ +#define PORT_TEST (1<<11) +#define PORT_SPD_MASK (3<<9) +#define PORT_HIGH_SPD (1<<10) +#define PORT_LOW_SPD (1<<9) +#define PORT_FULL_SPD (0<<9) +#define PORT_SLP (1<<5) +#define PORT_RESETTING (1<<4) +#define PORT_OVC (1<<3) +#define PORT_SUSP (1<<2) +#define PORT_EN (1<<1) +#define PORT_CONNECT (1<<0) + +/* Bit definition for PORT_STATUS_CHG register */ +#define PORT_SLP_IF (1<<5) +#define PORT_RESET_IF (1<<4) +#define PORT_SUSP_IF (1<<2) +#define PORT_EN_IF (1<<1) +#define PORT_CONNECT_IF (1<<0) + +/* Bit definition for ROOT_BC_CR register */ +#define UDM_VSRC_ACT (1<<10) +#define UDM_BC_CMPE (1<<9) +#define UDP_BC_CMPE (1<<8) +#define BC_AUTO_MODE (1<<6) +#define UDM_BC_VSRC (1<<5) +#define UDP_BC_VSRC (1<<4) +#define UDM_BC_CMPO (1<<1) +#define UDP_BC_CMPO (1<<0) + +/* Bit definition for HSI_CAL_CR register */ +#define CLK_SEL (1<<21) +#define SOF_FREE (1<<3) +#define SFT_RST (1<<2) +#define CAL_EN (1<<1) +#define CAL_RST (1<<0) + +/*******************************************************************************/ +/* Struct Definition */ + +/* USB Setup Request */ +typedef struct __attribute__((packed)) _USB_SETUP_REQ +{ + uint8_t bRequestType; + uint8_t bRequest; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; +} USB_SETUP_REQ, *PUSB_SETUP_REQ; + +/* USB Device Descriptor */ +typedef struct __attribute__((packed)) _USB_DEVICE_DESCR +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} USB_DEV_DESCR, *PUSB_DEV_DESCR; + +/* USB Configuration Descriptor */ +typedef struct __attribute__((packed)) _USB_CONFIG_DESCR +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t MaxPower; +} USB_CFG_DESCR, *PUSB_CFG_DESCR; + +/* USB Interface Descriptor */ +typedef struct __attribute__((packed)) _USB_INTERF_DESCR +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} USB_ITF_DESCR, *PUSB_ITF_DESCR; + +/* USB Endpoint Descriptor */ +typedef struct __attribute__((packed)) _USB_ENDPOINT_DESCR +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint8_t wMaxPacketSizeL; + uint8_t wMaxPacketSizeH; + uint8_t bInterval; +} USB_ENDP_DESCR, *PUSB_ENDP_DESCR; + +/* USB Configuration Descriptor Set */ +typedef struct __attribute__((packed)) _USB_CONFIG_DESCR_LONG +{ + USB_CFG_DESCR cfg_descr; + USB_ITF_DESCR itf_descr; + USB_ENDP_DESCR endp_descr[ 1 ]; +} USB_CFG_DESCR_LONG, *PUSB_CFG_DESCR_LONG; + +/* USB HUB Descriptor */ +typedef struct __attribute__((packed)) _USB_HUB_DESCR +{ + uint8_t bDescLength; + uint8_t bDescriptorType; + uint8_t bNbrPorts; + uint8_t wHubCharacteristicsL; + uint8_t wHubCharacteristicsH; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; + uint8_t PortPwrCtrlMask; +} USB_HUB_DESCR, *PUSB_HUB_DESCR; + +/* USB HID Descriptor */ +typedef struct __attribute__((packed)) _USB_HID_DESCR +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdHID; + uint8_t bCountryCode; + uint8_t bNumDescriptors; + uint8_t bDescriptorTypeX; + uint8_t wDescriptorLengthL; + uint8_t wDescriptorLengthH; +} USB_HID_DESCR, *PUSB_HID_DESCR; + +/* USB UDisk */ +typedef struct __attribute__((packed)) _UDISK_BOC_CBW +{ + uint32_t mCBW_Sig; + uint32_t mCBW_Tag; + uint32_t mCBW_DataLen; + uint8_t mCBW_Flag; + uint8_t mCBW_LUN; + uint8_t mCBW_CB_Len; + uint8_t mCBW_CB_Buf[ 16 ]; +} UDISK_BOC_CBW, *PXUDISK_BOC_CBW; + +/* USB UDisk */ +typedef struct __attribute__((packed)) _UDISK_BOC_CSW +{ + uint32_t mCBW_Sig; + uint32_t mCBW_Tag; + uint32_t mCSW_Residue; + uint8_t mCSW_Status; +} UDISK_BOC_CSW, *PXUDISK_BOC_CSW; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_usbpd.h b/Peripheral/inc/ch564_usbpd.h new file mode 100644 index 0000000..1b3c10a --- /dev/null +++ b/Peripheral/inc/ch564_usbpd.h @@ -0,0 +1,321 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_usbpd.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * USBPD firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_USBPD_H +#define __CH564_USBPD_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +/* Register Bit Definition */ +/* USBPD->CONFIG */ +#define PD_FILT_ED (1<<0) /* PD pin input filter enable */ +#define PD_ALL_CLR (1<<1) /* Clear all interrupt flags */ +#define CC_SEL (1<<2) /* Select PD communication port */ +#define PD_DMA_EN (1<<3) /* Enable DMA for USBPD */ +#define PD_RST_EN (1<<4) /* PD mode reset command enable */ +#define WAKE_POLAR (1<<5) /* PD port wake-up level */ +#define IE_PD_IO (1<<10) /* PD IO interrupt enable */ +#define IE_RX_BIT (1<<11) /* Receive bit interrupt enable */ +#define IE_RX_BYTE (1<<12) /* Receive byte interrupt enable */ +#define IE_RX_ACT (1<<13) /* Receive completion interrupt enable */ +#define IE_RX_RESET (1<<14) /* Reset interrupt enable */ +#define IE_TX_END (1<<15) /* Transfer completion interrupt enable */ + +/* USBPD->CONTROL */ +#define PD_TX_EN (1<<0) /* USBPD transceiver mode and transmit enable */ +#define BMC_START (1<<1) /* BMC send start signal */ +#define RX_STATE_0 (1<<2) /* PD received state bit 0 */ +#define RX_STATE_1 (1<<3) /* PD received state bit 1 */ +#define RX_STATE_2 (1<<4) /* PD received state bit 2 */ +#define DATA_FLAG (1<<5) /* Cache data valid flag bit */ +#define TX_BIT_BACK (1<<6) /* Indicates the current bit status of the BMC when sending the code */ +#define BMC_BYTE_HI (1<<7) /* Indicates the current half-byte status of the PD data being sent and received */ + +/* USBPD->TX_SEL */ +#define TX_SEL1 (0<<0) +#define TX_SEL1_SYNC1 (0<<0) /* 0-SYNC1 */ +#define TX_SEL1_RST1 (1<<0) /* 1-RST1 */ +#define TX_SEL2_Mask (3<<2) +#define TX_SEL2_SYNC1 (0<<2) /* 00-SYNC1 */ +#define TX_SEL2_SYNC3 (1<<2) /* 01-SYNC3 */ +#define TX_SEL2_RST1 (2<<2) /* 1x-RST1 */ +#define TX_SEL3_Mask (3<<4) +#define TX_SEL3_SYNC1 (0<<4) /* 00-SYNC1 */ +#define TX_SEL3_SYNC3 (1<<4) /* 01-SYNC3 */ +#define TX_SEL3_RST1 (2<<4) /* 1x-RST1 */ +#define TX_SEL4_Mask (3<<6) +#define TX_SEL4_SYNC2 (0<<6) /* 00-SYNC2 */ +#define TX_SEL4_SYNC3 (1<<6) /* 01-SYNC3 */ +#define TX_SEL4_RST2 (2<<6) /* 1x-RST2 */ + +/* USBPD->STATUS */ +#define BMC_AUX_Mask (3<<0) /* Clear BMC auxiliary information */ +#define BMC_AUX_INVALID (0<<0) /* 00-Invalid */ +#define BMC_AUX_SOP0 (1<<0) /* 01-SOP0 */ +#define BMC_AUX_SOP1_HRST (2<<0) /* 10-SOP1 hard reset */ +#define BMC_AUX_SOP2_CRST (3<<0) /* 11-SOP2 cable reset */ +#define BUF_ERR (1<<2) /* BUFFER or DMA error interrupt flag */ +#define IF_RX_BIT (1<<3) /* Receive bit or 5bit interrupt flag */ +#define IF_RX_BYTE (1<<4) /* Receive byte or SOP interrupt flag */ +#define IF_RX_ACT (1<<5) /* Receive completion interrupt flag */ +#define IF_RX_RESET (1<<6) /* Receive reset interrupt flag */ +#define IF_TX_END (1<<7) /* Transfer completion interrupt flag */ + +/* USBPD->PORT_CC1 */ +/* USBPD->PORT_CC2 */ +#define PA_CC_AI (1<<0) /* CC port comparator analogue input */ +#define CC_PD (1<<1) /* CC port pull-down resistor enable */ +#define CC_PU_Mask (3<<2) /* Clear CC port pull-up current */ +#define CC_NO_PU (0<<2) /* 00-Prohibit pull-up current */ +#define CC_PU_330 (1<<2) /* 01-330uA */ +#define CC_PU_180 (2<<2) /* 10-180uA */ +#define CC_PU_80 (3<<2) /* 11-80uA */ +#define CC_LVE (1<<4) /* CC port output low voltage enable */ +#define CC_CMP_Mask (7<<5) /* Clear CC_CMP*/ +#define CC_NO_CMP (0<<5) /* 000-closed */ +#define CC_CMP_22 (2<<5) /* 010-0.22V */ +#define CC_CMP_45 (3<<5) /* 011-0.45V */ +#define CC_CMP_55 (4<<5) /* 100-0.55V */ +#define CC_CMP_66 (5<<5) /* 101-0.66V */ +#define CC_CMP_95 (6<<5) /* 110-0.95V */ +#define CC_CMP_123 (7<<5) /* 111-1.23V */ + +/********************************************************* + * PD pin PC14/PC15 high threshold input mode: + * 1-High threshold input (2.2V typical), to reduce the I/O power consumption during PD communication + * 0-Normal GPIO threshold input + * *******************************************************/ +#define USBPD_PHY_V33 (1<<8) +/********************************************************** +* PD transceiver PHY pull-up limit configuration bits: +* 1-Direct use of VDD for GPIO applications or PD applications with VDD voltage of 3.3V +* 0-LDO buck enabled, limited to approx 3.3V, for PD applications with VDD more than 4V +* ********************************************************/ + +/* Control Message Types */ +#define DEF_TYPE_RESERVED 0x00 +#define DEF_TYPE_GOODCRC 0x01 /* Send By: Source,Sink,Cable Plug */ +#define DEF_TYPE_GOTOMIN 0x02 /* Send By: Source */ +#define DEF_TYPE_ACCEPT 0x03 /* Send By: Source,Sink,Cable Plug */ +#define DEF_TYPE_REJECT 0x04 /* Send By: Source,Sink,Cable Plug */ +#define DEF_TYPE_PING 0x05 /* Send By: Source */ +#define DEF_TYPE_PS_RDY 0x06 /* Send By: Source,Sink */ +#define DEF_TYPE_GET_SRC_CAP 0x07 /* Send By: Sink,DRP */ +#define DEF_TYPE_GET_SNK_CAP 0x08 /* Send By: Source,DRP */ +#define DEF_TYPE_DR_SWAP 0x09 /* Send By: Source,Sink */ +#define DEF_TYPE_PR_SWAP 0x0A /* Send By: Source,Sink */ +#define DEF_TYPE_VCONN_SWAP 0x0B /* Send By: Source,Sink */ +#define DEF_TYPE_WAIT 0x0C /* Send By: Source,Sink */ +#define DEF_TYPE_SOFT_RESET 0x0D /* Send By: Source,Sink */ +#define DEF_TYPE_DATA_RESET 0x0E /* Send By: Source,Sink */ +#define DEF_TYPE_DATA_RESET_CMP 0x0F /* Send By: Source,Sink */ +#define DEF_TYPE_NOT_SUPPORT 0x10 /* Send By: Source,Sink,Cable Plug */ +#define DEF_TYPE_GET_SRC_CAP_EX 0x11 /* Send By: Sink,DRP */ +#define DEF_TYPE_GET_STATUS 0x12 /* Send By: Source,Sink */ +#define DEF_TYPE_GET_STATUS_R 0X02 /* ext=1 */ +#define DEF_TYPE_FR_SWAP 0x13 /* Send By: Sink */ +#define DEF_TYPE_GET_PPS_STATUS 0x14 /* Send By: Sink */ +#define DEF_TYPE_GET_CTY_CODES 0x15 /* Send By: Source,Sink */ +#define DEF_TYPE_GET_SNK_CAP_EX 0x16 /* Send By: Source,DRP */ +#define DEF_TYPE_GET_SRC_INFO 0x17 /* Send By: Sink,DRP */ +#define DEF_TYPE_GET_REVISION 0x18 /* Send By: Source,Sink */ + +/* Data Message Types */ +#define DEF_TYPE_SRC_CAP 0x01 /* Send By: Source,Dual-Role Power */ +#define DEF_TYPE_REQUEST 0x02 /* Send By: Sink */ +#define DEF_TYPE_BIST 0x03 /* Send By: Tester,Source,Sink */ +#define DEF_TYPE_SNK_CAP 0x04 /* Send By: Sink,Dual-Role Power */ +#define DEF_TYPE_BAT_STATUS 0x05 /* Send By: Source,Sink */ +#define DEF_TYPE_ALERT 0x06 /* Send By: Source,Sink */ +#define DEF_TYPE_GET_CTY_INFO 0x07 /* Send By: Source,Sink */ +#define DEF_TYPE_ENTER_USB 0x08 /* Send By: DFP */ +#define DEF_TYPE_EPR_REQUEST 0x09 /* Send By: Sink */ +#define DEF_TYPE_EPR_MODE 0x0A /* Send By: Source,Sink */ +#define DEF_TYPE_SRC_INFO 0x0B /* Send By: Source */ +#define DEF_TYPE_REVISION 0x0C /* Send By: Source,Sink,Cable Plug */ +#define DEF_TYPE_VENDOR_DEFINED 0x0F /* Send By: Source,Sink,Cable Plug */ + +/* Vendor Define Message Command */ +#define DEF_VDM_DISC_IDENT 0x01 +#define DEF_VDM_DISC_SVID 0x02 +#define DEF_VDM_DISC_MODE 0x03 +#define DEF_VDM_ENTER_MODE 0x04 +#define DEF_VDM_EXIT_MODE 0x05 +#define DEF_VDM_ATTENTION 0x06 +#define DEF_VDM_DP_S_UPDATE 0x10 +#define DEF_VDM_DP_CONFIG 0x11 + +/* PD Revision */ +#define DEF_PD_REVISION_10 0x00 +#define DEF_PD_REVISION_20 0x01 +#define DEF_PD_REVISION_30 0x02 + + +/* PD PHY Channel */ +#define DEF_PD_CC1 0x00 +#define DEF_PD_CC2 0x01 + +#define PIN_CC1 GPIO_Pin_18 +#define PIN_CC2 GPIO_Pin_19 + +/* PD Tx Status */ +#define DEF_PD_TX_OK 0x00 +#define DEF_PD_TX_FAIL 0x01 + +/* PDO INDEX */ +#define PDO_INDEX_1 1 +#define PDO_INDEX_2 2 +#define PDO_INDEX_3 3 +#define PDO_INDEX_4 4 +#define PDO_INDEX_5 5 + +/******************************************************************************/ + +#define UPD_TMR_TX_48M (80-1) /* timer value for USB PD BMC transmittal @Fsys=48MHz */ +#define UPD_TMR_RX_48M (120-1) /* timer value for USB PD BMC receiving @Fsys=48MHz */ +#define UPD_TMR_TX_24M (40-1) /* timer value for USB PD BMC transmittal @Fsys=24MHz */ +#define UPD_TMR_RX_24M (60-1) /* timer value for USB PD BMC receiving @Fsys=24MHz */ +#define UPD_TMR_TX_12M (20-1) /* timer value for USB PD BMC transmittal @Fsys=12MHz */ +#define UPD_TMR_RX_12M (30-1) /* timer value for USB PD BMC receiving @Fsys=12MHz */ + +#define MASK_PD_STAT 0x03 /* Bit mask for current PD status */ +#define PD_RX_SOP0 0x01 /* SOP0 received */ +#define PD_RX_SOP1_HRST 0x02 /* SOP1 or Hard Reset received */ +#define PD_RX_SOP2_CRST 0x03 /* SOP2 or Cable Reset received */ + +#define UPD_SOP0 ( TX_SEL1_SYNC1 | TX_SEL2_SYNC1 | TX_SEL3_SYNC1 | TX_SEL4_SYNC2 ) /* SOP1 */ +#define UPD_SOP1 ( TX_SEL1_SYNC1 | TX_SEL2_SYNC1 | TX_SEL3_SYNC3 | TX_SEL4_SYNC3 ) /* SOP2 */ +#define UPD_SOP2 ( TX_SEL1_SYNC1 | TX_SEL2_SYNC3 | TX_SEL3_SYNC1 | TX_SEL4_SYNC3 ) /* SOP3 */ +#define UPD_HARD_RESET ( TX_SEL1_RST1 | TX_SEL2_RST1 | TX_SEL3_RST1 | TX_SEL4_RST2 ) /* Hard Reset*/ +#define UPD_CABLE_RESET ( TX_SEL1_RST1 | TX_SEL2_SYNC1 | TX_SEL3_RST1 | TX_SEL4_SYNC3 ) /* Cable Reset*/ + + +#define bCC_CMP_22 0X01 +#define bCC_CMP_45 0X02 +#define bCC_CMP_55 0X04 +#define bCC_CMP_66 0X08 +#define bCC_CMP_95 0X10 +#define bCC_CMP_123 0X20 +#define bCC_CMP_220 0X40 + +/******************************************************************************/ +/* PD State Machine */ +typedef enum +{ + STA_IDLE = 0, /* 0: No task status */ + STA_DISCONNECT, /* 1: Disconnection */ + STA_SRC_CONNECT, /* 2: SRC connect */ + STA_RX_SRC_CAP_WAIT, /* 3: Waiting to receive SRC_CAP */ + STA_RX_SRC_CAP, /* 4: SRC_CAP received */ + STA_TX_REQ, /* 5: Send REQUEST */ + STA_RX_ACCEPT_WAIT, /* 6: Waiting to receive ACCEPT */ + STA_RX_ACCEPT, /* 7: ACCEPT received */ + STA_RX_REJECT, /* 8: REJECT received */ + STA_RX_PS_RDY_WAIT, /* 9: Waiting to receive PS_RDY */ + STA_RX_PS_RDY, /* 10: PS_RDY received */ + STA_SINK_CONNECT, /* 11: SNK access */ + STA_TX_SRC_CAP, /* 12: Send SRC_CAP */ + STA_RX_REQ_WAIT, /* 13: Waiting to receive REQUEST */ + STA_RX_REQ, /* 14: REQUEST received */ + STA_TX_ACCEPT, /* 15: Send ACCEPT */ + STA_TX_REJECT, /* 16: Send REJECT */ + STA_ADJ_VOL, /* 17: Adjustment of output voltage and current */ + STA_TX_PS_RDY, /* 18: Send PS_RDY */ + STA_TX_DR_SWAP, /* 19: Send DR_SWAP */ + STA_RX_DR_SWAP_ACCEPT, /* 20: Waiting to receive the answer ACCEPT from DR_SWAP */ + STA_TX_PR_SWAP, /* 21: Send PR_SWAP */ + STA_RX_PR_SWAP_ACCEPT, /* 22: Waiting to receive the answer ACCEPT from PR_SWAP */ + STA_RX_PR_SWAP_PS_RDY, /* 23: Waiting to receive the answer PS_RDY from PR_SWAP */ + STA_TX_PR_SWAP_PS_RDY, /* 24: Send answer PS_RDY for PR_SWAP */ + STA_PR_SWAP_RECON_WAIT, /* 25: Wait for PR_SWAP before reconnecting */ + STA_SRC_RECON_WAIT, /* 26: Waiting for SRC to reconnect */ + STA_SINK_RECON_WAIT, /* 27: Waiting for SNK to reconnect */ + STA_RX_APD_PS_RDY_WAIT, /* 28: Waiting for PS_RDY from the receiving adapter */ + STA_RX_APD_PS_RDY, /* 29: PS_RDY received from the adapter */ + STA_MODE_SWITCH, /* 30: Mode switching */ + STA_TX_SOFTRST, /* 31: Sending a software reset */ + STA_TX_HRST, /* 32: Send hardware reset */ + STA_PHY_RST, /* 33: PHY reset */ + STA_APD_IDLE_WAIT, /* 34: Waiting for the adapter to become idle */ +} CC_STATUS; + +/******************************************************************************/ +/* PD Message Header Struct */ +typedef union +{ + struct _Message_Header + { + UINT8 MsgType: 5; /* Message Type */ + UINT8 PDRole: 1; /* 0-UFP; 1-DFP */ + UINT8 SpecRev: 2; /* 00-Rev1.0; 01-Rev2.0; 10-Rev3.0; */ + UINT8 PRRole: 1; /* 0-Sink; 1-Source */ + UINT8 MsgID: 3; + UINT8 NumDO: 3; + UINT8 Ext: 1; + }Message_Header; + UINT16 Data; +}_Message_Header; + +/******************************************************************************/ +/* Bit definition */ +typedef union +{ + struct _BITS_ + { + UINT8 Msg_Recvd: 1; /* Notify the main program of the receipt of a PD packet */ + UINT8 Connected: 1; /* PD Physical Layer Connected Flag */ + UINT8 Stop_Det_Chk: 1; /* 0-Enable detection; 1-Disable disconnection detection */ + UINT8 PD_Role: 1; /* 0-UFP; 1-DFP */ + UINT8 PR_Role: 1; /* 0-Sink; 1-Source */ + UINT8 Auto_Ack_PRRole: 1; /* Role used by auto-responder 0:SINK; 1:SOURCE */ + UINT8 PD_Version: 1; /* PD version 0-PD2.0; 1-PD3.0 */ + UINT8 VDM_Version: 1; /* VDM Version 0-1.0 1-2.0 */ + UINT8 HPD_Connected: 1; /* HPD Physical Layer Connected Flag */ + UINT8 HPD_Det_Chk: 1; /* 0-turn off HPD connection detection; 1-turn on HPD connection detection */ + UINT8 CC_Sel_En: 1; /* 0-CC channel selection toggle enable; 1-CC channel selection toggle disable */ + UINT8 CC_Sel_State: 1; /* 0-CC channel selection switches to 0; 1-CC channel selection switches to 1 */ + UINT8 PD_Comm_Succ: 1; /* 0-PD communication unsuccessful; 1-PD communication successful; */ + UINT8 Recv: 3; + }Bit; + UINT16 Bit_Flag; +}_BIT_FLAG; + +/* PD control-related structures */ +typedef struct _PD_CONTROL +{ + CC_STATUS PD_State; /* PD communication status machine */ + CC_STATUS PD_State_Last; /* PD communication status machine (last value) */ + UINT8 Msg_ID; /* ID of the message sent */ + UINT8 Det_Timer; /* PD connection status detection timing */ + UINT8 Det_Cnt; /* Number of PD connection status detections */ + UINT8 Det_Sel_Cnt; /* Number of SEL toggles for PD connection status detection */ + UINT8 HPD_Det_Timer; /* HPD connection detection timing */ + UINT8 HPD_Det_Cnt; /* HPD pin connection status detection count */ + UINT16 PD_Comm_Timer; /* PD shared timing variables */ + UINT8 ReqPDO_Idx; /* Index of the requested PDO, valid values 1-7 */ + UINT16 PD_BusIdle_Timer; /* Bus Idle Time Timer */ + UINT8 Mode_Try_Cnt; /* Number of retries for current mode, highest bit marks mode */ + UINT8 Err_Op_Cnt; /* Exception operation count */ + UINT8 Adapter_Idle_Cnt; /* Adapter communication idle timing */ + _BIT_FLAG Flag; /* Flag byte bit definition */ +}PD_CONTROL, *pPD_CONTROL; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/inc/ch564_xbus.h b/Peripheral/inc/ch564_xbus.h new file mode 100644 index 0000000..7b6ccc7 --- /dev/null +++ b/Peripheral/inc/ch564_xbus.h @@ -0,0 +1,46 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_xbus.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file contains all the functions prototypes for the + * XBUS firmware library. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __CH564_XBUS_H +#define __CH564_XBUS_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ch564.h" + +typedef enum +{ + NoOutput = 0x0, + AddrNum_6bit, + AddrNum_12bit, + AddrNum_ALL +} XbusOutputADDrBit; + +typedef enum +{ + Setuptime_1clk, + Setuptime_2clk, +} XbusSetupTime; + +#define SET_XBUS_CYCLE(val) (R8_XBUS_CYCLE = XBUS_CYCLE_VALUE_MASK & (val)) + +void XbusInit(XbusOutputADDrBit AddrBit, FunctionalState Bit32En, FunctionalState Stat); +void XbusHoldInit(XbusSetupTime setuptm, uint8_t holdtm); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Peripheral/src/ch564_adc.c b/Peripheral/src/ch564_adc.c new file mode 100644 index 0000000..52165dc --- /dev/null +++ b/Peripheral/src/ch564_adc.c @@ -0,0 +1,37 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_adc.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the ADC firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_adc.h" + +/********************************************************************* + * @fn ADC_SelectChannel + * + * @brief The function sets the ADC channel for conversion. + * + * @param adcChannel The adcChannel parameter is of type ADCChannelTypedef, which is likely an + * enumeration or a typedef for an integer value representing the desired ADC channel. + * + * @return none + */ +void ADC_SelectChannel(ADCChannelTypedef adcChannel) +{ + if (adcChannel <= ADC_Channel0_1) + { + R32_ADC_CTRL &= ~MASK_ADC_CTL_MOD1; + R8_ADC_CTRL_MOD &= ~RB_ADC_CHAN_MOD; + R8_ADC_CTRL_MOD |= adcChannel << 4; + } + else + { + R32_ADC_CTRL &= ~MASK_ADC_CTL_MOD1; + R32_ADC_CTRL |= adcChannel - 1; + } +} diff --git a/Peripheral/src/ch564_eth.c b/Peripheral/src/ch564_eth.c new file mode 100644 index 0000000..6e49ed2 --- /dev/null +++ b/Peripheral/src/ch564_eth.c @@ -0,0 +1,2487 @@ +/********************************** (C) COPYRIGHT ******************************* +* File Name : ch564_eth.c +* Author : WCH +* Version : V1.0.0 +* Date : 2024/05/05 +* Description : This file provides all the ETH firmware functions. +********************************************************************************* +* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. +* Attention: This software (modified or not) and binary are used for +* microcontroller manufactured by Nanjing Qinheng Microelectronics. +*******************************************************************************/ +#include "ch564_eth.h" + +ETH_DMADESCTypeDef *DMATxDescToSet; +ETH_DMADESCTypeDef *DMARxDescToGet; +ETH_DMADESCTypeDef *DMAPTPTxDescToSet; +ETH_DMADESCTypeDef *DMAPTPRxDescToGet; + +/********************************************************************* + * @fn ETH_StructInit + * + * @brief Fills each ETH_InitStruct member with its default value. + * + * @param ETH_InitStruct - pointer to a ETH_InitTypeDef structure + * which will be initialized. + * + * @return none + */ +void ETH_StructInit(ETH_InitTypeDef *ETH_InitStruct) +{ + /*------------------------ MAC -----------------------------------*/ + ETH_InitStruct->ETH_Watchdog = ETH_Watchdog_Enable; + ETH_InitStruct->ETH_Jabber = ETH_Jabber_Enable; + ETH_InitStruct->ETH_InterFrameGap = ETH_InterFrameGap_96Bit; + ETH_InitStruct->ETH_ChecksumOffload = ETH_ChecksumOffload_Disable; + ETH_InitStruct->ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable; + ETH_InitStruct->ETH_DeferralCheck = ETH_DeferralCheck_Disable; + ETH_InitStruct->ETH_ReceiveAll = ETH_ReceiveAll_Disable; + ETH_InitStruct->ETH_SourceAddrFilter = ETH_SourceAddrFilter_Disable; + ETH_InitStruct->ETH_PassControlFrames = ETH_PassControlFrames_BlockAll; + ETH_InitStruct->ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Disable; + ETH_InitStruct->ETH_DestinationAddrFilter = ETH_DestinationAddrFilter_Normal; + ETH_InitStruct->ETH_PromiscuousMode = ETH_PromiscuousMode_Disable; + ETH_InitStruct->ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect; + ETH_InitStruct->ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect; + ETH_InitStruct->ETH_HashTableHigh = 0x0; + ETH_InitStruct->ETH_HashTableLow = 0x0; + ETH_InitStruct->ETH_PauseTime = 0x0; + ETH_InitStruct->ETH_UnicastPauseFrameDetect = ETH_UnicastPauseFrameDetect_Disable; + ETH_InitStruct->ETH_ReceiveFlowControl = ETH_ReceiveFlowControl_Disable; + ETH_InitStruct->ETH_TransmitFlowControl = ETH_TransmitFlowControl_Disable; + ETH_InitStruct->ETH_VLANTagComparison = ETH_VLANTagComparison_16Bit; + ETH_InitStruct->ETH_VLANTagIdentifier = 0x0; + /*------------------------ DMA -----------------------------------*/ + ETH_InitStruct->ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Disable; + ETH_InitStruct->ETH_FlushReceivedFrame = ETH_FlushReceivedFrame_Enable; + ETH_InitStruct->ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable; + ETH_InitStruct->ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Disable; + ETH_InitStruct->ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Disable; +} + +/********************************************************************* + * @fn ETH_Start + * + * @brief Enables ENET MAC and DMA reception/transmission. + * + * @return none + */ +void ETH_Start(void) +{ + ETH_MACTransmissionCmd(ENABLE); + ETH_FlushTransmitFIFO(); + ETH_MACReceptionCmd(ENABLE); + ETH_DMATransmissionCmd(ENABLE); + ETH_DMAReceptionCmd(ENABLE); +} + +/********************************************************************* + * @fn ETH_HandleTxPkt + * + * @brief Transmits a packet, from application buffer, pointed by ppkt. + * + * @param ppkt - pointer to the application's packet buffer to transmit. + * FrameLength - Tx Packet size. + * + * @return ETH_ERROR - in case of Tx desc owned by DMA. + * ETH_SUCCESS - for correct transmission. + */ +uint32_t ETH_HandleTxPkt(uint8_t *ppkt, uint16_t FrameLength) +{ + uint32_t offset = 0; + + if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (uint32_t)RESET) + { + return ETH_ERROR; + } + + for(offset = 0; offset < FrameLength; offset++) + { + (*(__IO uint8_t *)((DMATxDescToSet->Buffer1Addr) + offset)) = (*(ppkt + offset)); + } + + DMATxDescToSet->ControlBufferSize = (FrameLength & ETH_DMATxDesc_TBS1); + DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS; + DMATxDescToSet->Status |= ETH_DMATxDesc_OWN; + + if((ETH->DMASR & ETH_DMASR_TBUS) != (uint32_t)RESET) + { + ETH->DMASR = ETH_DMASR_TBUS; + ETH->DMATPDR = 0; + } + + if((DMATxDescToSet->Status & ETH_DMATxDesc_TCH) != (uint32_t)RESET) + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)(DMATxDescToSet->Buffer2NextDescAddr); + } + else + { + if((DMATxDescToSet->Status & ETH_DMATxDesc_TER) != (uint32_t)RESET) + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)(ETH->DMATDLAR); + } + else + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)((uint32_t)DMATxDescToSet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + } + } + + return ETH_SUCCESS; +} + +/********************************************************************* + * @fn ETH_HandleRxPkt + * + * @brief Receives a packet and copies it to memory pointed by ppkt. + * + * @param ppkt - pointer to the application packet receive buffer. + * + * @return ETH_ERROR - if there is error in reception + * framelength - received packet size if packet reception is correct + */ +uint32_t ETH_HandleRxPkt(uint8_t *ppkt) +{ + uint32_t offset = 0, framelength = 0; + + if((DMARxDescToGet->Status & ETH_DMARxDesc_OWN) != (uint32_t)RESET) + { + return ETH_ERROR; + } + + if(((DMARxDescToGet->Status & ETH_DMARxDesc_ES) == (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_LS) != (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_FS) != (uint32_t)RESET)) + { + framelength = ((DMARxDescToGet->Status & ETH_DMARxDesc_FL) >> ETH_DMARXDESC_FRAME_LENGTHSHIFT) - 4; + + for(offset = 0; offset < framelength; offset++) + { + (*(ppkt + offset)) = (*(__IO uint8_t *)((DMARxDescToGet->Buffer1Addr) + offset)); + } + } + else + { + framelength = ETH_ERROR; + } + + DMARxDescToGet->Status = ETH_DMARxDesc_OWN; + + if((ETH->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET) + { + ETH->DMASR = ETH_DMASR_RBUS; + ETH->DMARPDR = 0; + } + + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RCH) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(DMARxDescToGet->Buffer2NextDescAddr); + } + else + { + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RER) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(ETH->DMARDLAR); + } + else + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)((uint32_t)DMARxDescToGet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + } + } + + return (framelength); +} + +/********************************************************************* + * @fn ETH_GetRxPktSize + * + * @brief Get the size of received the received packet. + * + * @return framelength - received packet size + */ +uint32_t ETH_GetRxPktSize(void) +{ + uint32_t frameLength = 0; + if(((DMARxDescToGet->Status & ETH_DMARxDesc_OWN) == (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_ES) == (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_LS) != (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_FS) != (uint32_t)RESET)) + { + frameLength = ETH_GetDMARxDescFrameLength(DMARxDescToGet); + } + + return frameLength; +} + +/********************************************************************* + * @fn ETH_DropRxPkt + * + * @brief Drop a Received packet. + * + * @return none + */ +void ETH_DropRxPkt(void) +{ + DMARxDescToGet->Status = ETH_DMARxDesc_OWN; + + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RCH) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(DMARxDescToGet->Buffer2NextDescAddr); + } + else + { + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RER) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(ETH->DMARDLAR); + } + else + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)((uint32_t)DMARxDescToGet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + } + } +} + +/********************************************************************* + * @fn ETH_ReadPHYRegister + * + * @brief Read a PHY register. + * + * @param PHYAddress - PHY device address, is the index of one of supported 32 PHY devices. + * PHYReg - PHY register address, is the index of one of the 32 PHY register. + * + * @return ETH_ERROR - in case of timeout. + * MAC MIIDR register value - Data read from the selected PHY register. + */ +uint16_t ETH_ReadPHYRegister(uint16_t PHYAddress, uint16_t PHYReg) +{ + uint32_t tmpreg = 0; + __IO uint32_t timeout = 0; + + tmpreg = ETH->MACMIIAR; + tmpreg &= ~MACMIIAR_CR_MASK; + tmpreg |= (((uint32_t)PHYAddress << 11) & ETH_MACMIIAR_PA); + tmpreg |= (((uint32_t)PHYReg << 6) & ETH_MACMIIAR_MR); + tmpreg &= ~ETH_MACMIIAR_MW; + tmpreg |= ETH_MACMIIAR_MB; + ETH->MACMIIAR = tmpreg; + + do + { + timeout++; + tmpreg = ETH->MACMIIAR; + } while((tmpreg & ETH_MACMIIAR_MB) && (timeout < (uint32_t)PHY_READ_TO)); + + if(timeout == PHY_READ_TO) + { + return (uint16_t)ETH_ERROR; + } + + return (uint16_t)(ETH->MACMIIDR); +} + +/********************************************************************* + * @fn ETH_WritePHYRegister + * + * @brief Write to a PHY register. + * + * @param PHYAddress - PHY device address, is the index of one of supported 32 PHY devices. + * PHYReg - PHY register address, is the index of one of the 32 PHY register. + * PHYValue - the value to write. + * + * @return ETH_ERROR - in case of timeout. + * ETH_SUCCESS - for correct write + */ +uint32_t ETH_WritePHYRegister(uint16_t PHYAddress, uint16_t PHYReg, uint16_t PHYValue) +{ + uint32_t tmpreg = 0; + __IO uint32_t timeout = 0; + + tmpreg = ETH->MACMIIAR; + tmpreg &= ~MACMIIAR_CR_MASK; + tmpreg |= (((uint32_t)PHYAddress << 11) & ETH_MACMIIAR_PA); + tmpreg |= (((uint32_t)PHYReg << 6) & ETH_MACMIIAR_MR); + tmpreg |= ETH_MACMIIAR_MW; + tmpreg |= ETH_MACMIIAR_MB; + ETH->MACMIIDR = PHYValue; + ETH->MACMIIAR = tmpreg; + + do + { + timeout++; + tmpreg = ETH->MACMIIAR; + } while((tmpreg & ETH_MACMIIAR_MB) && (timeout < (uint32_t)PHY_WRITE_TO)); + + if(timeout >= PHY_WRITE_TO) + { + return ETH_ERROR; + } + + return ETH_SUCCESS; +} + +/********************************************************************* + * @fn ETH_PHYLoopBackCmd + * + * @brief Enables or disables the PHY loopBack mode. + * + * @param PHYAddress - PHY device address, is the index of one of supported 32 PHY devices. + * NewState - new state of the PHY loopBack mode. + * + * @return ETH_ERROR - in case of bad PHY configuration. + * ETH_SUCCESS - for correct PHY configuration. + */ +uint32_t ETH_PHYLoopBackCmd(uint16_t PHYAddress, FunctionalState NewState) +{ + uint16_t tmpreg = 0; + + tmpreg = ETH_ReadPHYRegister(PHYAddress, PHY_BCR); + + if(NewState != DISABLE) + { + tmpreg |= PHY_Loopback; + } + else + { + tmpreg &= (uint16_t)(~(uint16_t)PHY_Loopback); + } + + if(ETH_WritePHYRegister(PHYAddress, PHY_BCR, tmpreg) != (uint32_t)RESET) + { + return ETH_SUCCESS; + } + else + { + return ETH_ERROR; + } +} + +/********************************************************************* + * @fn ETH_MACTransmissionCmd + * + * @brief Enables or disables the MAC transmission. + * + * @param NewState - new state of the MAC transmission. + * + * @return none + */ +void ETH_MACTransmissionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACCR |= ETH_MACCR_TE; + } + else + { + ETH->MACCR &= ~ETH_MACCR_TE; + } +} + +/********************************************************************* + * @fn ETH_MACReceptionCmd + * + * @brief Enables or disables the MAC reception. + * + * @param NewState - new state of the MAC reception. + * + * @return none + */ +void ETH_MACReceptionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACCR |= ETH_MACCR_RE; + } + else + { + ETH->MACCR &= ~ETH_MACCR_RE; + } +} + +/********************************************************************* + * @fn ETH_GetFlowControlBusyStatus + * + * @brief Enables or disables the MAC reception. + * + * @return The new state of flow control busy status bit (SET or RESET). + */ +FlagStatus ETH_GetFlowControlBusyStatus(void) +{ + FlagStatus bitstatus = RESET; + + if((ETH->MACFCR & ETH_MACFCR_FCBBPA) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_InitiatePauseControlFrame + * + * @brief Initiate a Pause Control Frame (Full-duplex only). + * + * @return none + */ +void ETH_InitiatePauseControlFrame(void) +{ + ETH->MACFCR |= ETH_MACFCR_FCBBPA; +} + +/********************************************************************* + * @fn ETH_BackPressureActivationCmd + * + * @brief Enables or disables the MAC BackPressure operation activation (Half-duplex only). + * + * @param NewState - new state of the MAC BackPressure operation activation. + * + * @return none + */ +void ETH_BackPressureActivationCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACFCR |= ETH_MACFCR_FCBBPA; + } + else + { + ETH->MACFCR &= ~ETH_MACFCR_FCBBPA; + } +} + +/********************************************************************* + * @fn ETH_GetMACFlagStatus + * + * @brief Checks whether the specified ETHERNET MAC flag is set or not. + * + * @param ETH_MAC_FLAG - specifies the flag to check. + * + * @return The new state of ETHERNET MAC flag (SET or RESET). + */ +FlagStatus ETH_GetMACFlagStatus(uint32_t ETH_MAC_FLAG) +{ + FlagStatus bitstatus = RESET; + + if((ETH->MACSR & ETH_MAC_FLAG) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetMACITStatus + * + * @brief Checks whether the specified ETHERNET MAC interrupt has occurred or not. + * + * @param ETH_MAC_IT - specifies the interrupt source to check. + * + * @return The new state of ETHERNET MAC interrupt (SET or RESET). + */ +ITStatus ETH_GetMACITStatus(uint32_t ETH_MAC_IT) +{ + FlagStatus bitstatus = RESET; + + if((ETH->MACSR & ETH_MAC_IT) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_MACITConfig + * + * @brief Enables or disables the specified ETHERNET MAC interrupts. + * + * @param ETH_MAC_IT - specifies the interrupt source to check. + * NewState - new state of the specified ETHERNET MAC interrupts. + * + * @return none + */ +void ETH_MACITConfig(uint32_t ETH_MAC_IT, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACIMR &= (~(uint32_t)ETH_MAC_IT); + } + else + { + ETH->MACIMR |= ETH_MAC_IT; + } +} + +/********************************************************************* + * @fn ETH_MACAddressConfig + * + * @brief Configures the selected MAC address. + * + * @param MacAddr - The MAC addres to configure. + * ETH_MAC_Address0 - MAC Address0 + * ETH_MAC_Address1 - MAC Address1 + * ETH_MAC_Address2 - MAC Address2 + * ETH_MAC_Address3 - MAC Address3 + * Addr - Pointer on MAC address buffer data (6 bytes). + * + * @return none + */ +void ETH_MACAddressConfig(uint32_t MacAddr, uint8_t *Addr) +{ + uint32_t tmpreg; + + tmpreg = ((uint32_t)Addr[5] << 8) | (uint32_t)Addr[4]; + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) = tmpreg; + tmpreg = ((uint32_t)Addr[3] << 24) | ((uint32_t)Addr[2] << 16) | ((uint32_t)Addr[1] << 8) | Addr[0]; + + (*(__IO uint32_t *)(ETH_MAC_ADDR_LBASE + MacAddr)) = tmpreg; +} + +/********************************************************************* + * @fn ETH_GetMACAddress + * + * @brief Get the selected MAC address. + * + * @param MacAddr - The MAC address to return. + * ETH_MAC_Address0 - MAC Address0 + * ETH_MAC_Address1 - MAC Address1 + * ETH_MAC_Address2 - MAC Address2 + * ETH_MAC_Address3 - MAC Address3 + * Addr - Pointer on MAC address buffer data (6 bytes). + * + * @return none + */ +void ETH_GetMACAddress(uint32_t MacAddr, uint8_t *Addr) +{ + uint32_t tmpreg; + + tmpreg = (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)); + + Addr[5] = ((tmpreg >> 8) & (uint8_t)0xFF); + Addr[4] = (tmpreg & (uint8_t)0xFF); + tmpreg = (*(__IO uint32_t *)(ETH_MAC_ADDR_LBASE + MacAddr)); + Addr[3] = ((tmpreg >> 24) & (uint8_t)0xFF); + Addr[2] = ((tmpreg >> 16) & (uint8_t)0xFF); + Addr[1] = ((tmpreg >> 8) & (uint8_t)0xFF); + Addr[0] = (tmpreg & (uint8_t)0xFF); +} + +/********************************************************************* + * @fn ETH_MACAddressPerfectFilterCmd + * + * @brief Enables or disables the Address filter module uses the specified. + * + * @param MacAddr - The MAC address to return. + * ETH_MAC_Address0 - MAC Address0 + * ETH_MAC_Address1 - MAC Address1 + * ETH_MAC_Address2 - MAC Address2 + * ETH_MAC_Address3 - MAC Address3 + * NewState - new state of the specified ETHERNET MAC address use. + * + * @return none + */ +void ETH_MACAddressPerfectFilterCmd(uint32_t MacAddr, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) |= ETH_MACA1HR_AE; + } + else + { + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) &= (~(uint32_t)ETH_MACA1HR_AE); + } +} + +/********************************************************************* + * @fn ETH_MACAddressFilterConfig + * + * @brief Set the filter type for the specified ETHERNET MAC address. + * + * @param MacAddr - specifies the ETHERNET MAC address. + * ETH_MAC_Address0 - MAC Address0 + * ETH_MAC_Address1 - MAC Address1 + * ETH_MAC_Address2 - MAC Address2 + * ETH_MAC_Address3 - MAC Address3 + * Filter - specifies the used frame received field for comparaison. + * ETH_MAC_AddressFilter_SA - MAC Address is used to compare with the + * SA fields of the received frame. + * ETH_MAC_AddressFilter_DA - MAC Address is used to compare with the + * DA fields of the received frame. + * + * @return none + */ +void ETH_MACAddressFilterConfig(uint32_t MacAddr, uint32_t Filter) +{ + if(Filter != ETH_MAC_AddressFilter_DA) + { + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) |= ETH_MACA1HR_SA; + } + else + { + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) &= (~(uint32_t)ETH_MACA1HR_SA); + } +} + +/********************************************************************* + * @fn ETH_MACAddressMaskBytesFilterConfig + * + * @brief Set the filter type for the specified ETHERNET MAC address. + * + * @param MacAddr - specifies the ETHERNET MAC address. + * ETH_MAC_Address1 - MAC Address1 + * ETH_MAC_Address2 - MAC Address2 + * ETH_MAC_Address3 - MAC Address3 + * MaskByte - specifies the used address bytes for comparaison + * ETH_MAC_AddressMask_Byte5 - Mask MAC Address high reg bits [7:0]. + * ETH_MAC_AddressMask_Byte4 - Mask MAC Address low reg bits [31:24]. + * ETH_MAC_AddressMask_Byte3 - Mask MAC Address low reg bits [23:16]. + * ETH_MAC_AddressMask_Byte2 - Mask MAC Address low reg bits [15:8]. + * ETH_MAC_AddressMask_Byte1 - Mask MAC Address low reg bits [7:0]. + * + * @return none + */ +void ETH_MACAddressMaskBytesFilterConfig(uint32_t MacAddr, uint32_t MaskByte) +{ + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) &= (~(uint32_t)ETH_MACA1HR_MBC); + (*(__IO uint32_t *)(ETH_MAC_ADDR_HBASE + MacAddr)) |= MaskByte; +} + +/********************************************************************* + * @fn ETH_DMATxDescChainInit + * + * @brief Initializes the DMA Tx descriptors in chain mode. + * + * @param DMATxDescTab - Pointer on the first Tx desc list + * TxBuff - Pointer on the first TxBuffer list + * TxBuffCount - Number of the used Tx desc in the list + * + * @return none + */ +void ETH_DMATxDescChainInit(ETH_DMADESCTypeDef *DMATxDescTab, uint8_t *TxBuff, uint32_t TxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMATxDesc; + + DMATxDescToSet = DMATxDescTab; + + for(i = 0; i < TxBuffCount; i++) + { + DMATxDesc = DMATxDescTab + i; + DMATxDesc->Status = ETH_DMATxDesc_TCH | ETH_DMATxDesc_IC; + DMATxDesc->Buffer1Addr = (uint32_t)(&TxBuff[i * ETH_MAX_PACKET_SIZE]); + + if(i < (TxBuffCount - 1)) + { + DMATxDesc->Buffer2NextDescAddr = (uint32_t)(DMATxDescTab + i + 1); + } + else + { + DMATxDesc->Buffer2NextDescAddr = (uint32_t)DMATxDescTab; + } + } + + ETH->DMATDLAR = (uint32_t)DMATxDescTab; +} + +/********************************************************************* + * @fn ETH_DMATxDescRingInit + * + * @brief Initializes the DMA Tx descriptors in ring mode. + * + * @param DMATxDescTab - Pointer on the first Tx desc list. + * TxBuff1 - Pointer on the first TxBuffer1 list. + * TxBuff2 - Pointer on the first TxBuffer2 list. + * TxBuffCount - Number of the used Tx desc in the list. + * + * @return none + */ +void ETH_DMATxDescRingInit(ETH_DMADESCTypeDef *DMATxDescTab, uint8_t *TxBuff1, uint8_t *TxBuff2, uint32_t TxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMATxDesc; + + DMATxDescToSet = DMATxDescTab; + + for(i = 0; i < TxBuffCount; i++) + { + DMATxDesc = DMATxDescTab + i; + DMATxDesc->Buffer1Addr = (uint32_t)(&TxBuff1[i * ETH_MAX_PACKET_SIZE]); + DMATxDesc->Buffer2NextDescAddr = (uint32_t)(&TxBuff2[i * ETH_MAX_PACKET_SIZE]); + + if(i == (TxBuffCount - 1)) + { + DMATxDesc->Status = ETH_DMATxDesc_TER; + } + } + + ETH->DMATDLAR = (uint32_t)DMATxDescTab; +} + +/********************************************************************* + * @fn ETH_GetDMATxDescFlagStatus + * + * @brief Checks whether the specified ETHERNET DMA Tx Desc flag is set or not. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor + * ETH_DMATxDescFlag - specifies the flag to check. + * ETH_DMATxDesc_OWN - OWN bit - descriptor is owned by DMA engine + * ETH_DMATxDesc_IC - Interrupt on completetion + * ETH_DMATxDesc_LS - Last Segment + * ETH_DMATxDesc_FS - First Segment + * ETH_DMATxDesc_DC - Disable CRC + * ETH_DMATxDesc_DP - Disable Pad + * ETH_DMATxDesc_TTSE - Transmit Time Stamp Enable + * ETH_DMATxDesc_TER - Transmit End of Ring + * ETH_DMATxDesc_TCH - Second Address Chained + * ETH_DMATxDesc_TTSS - Tx Time Stamp Status + * ETH_DMATxDesc_IHE - IP Header Error + * ETH_DMATxDesc_ES - Error summary + * ETH_DMATxDesc_JT - Jabber Timeout + * ETH_DMATxDesc_FF - Frame Flushed - DMA/MTL flushed the frame due to SW flush + * ETH_DMATxDesc_PCE - Payload Checksum Error + * ETH_DMATxDesc_LCA - Loss of Carrier - carrier lost during tramsmission + * ETH_DMATxDesc_NC - No Carrier - no carrier signal from the tranceiver + * ETH_DMATxDesc_LCO - Late Collision - transmission aborted due to collision + * ETH_DMATxDesc_EC - Excessive Collision - transmission aborted after 16 collisions + * ETH_DMATxDesc_VF - VLAN Frame + * ETH_DMATxDesc_CC - Collision Count + * ETH_DMATxDesc_ED - Excessive Deferral + * ETH_DMATxDesc_UF - Underflow Error - late data arrival from the memory + * ETH_DMATxDesc_DB - Deferred Bit + * + * @return The new state of ETH_DMATxDescFlag (SET or RESET). + */ +FlagStatus ETH_GetDMATxDescFlagStatus(ETH_DMADESCTypeDef *DMATxDesc, uint32_t ETH_DMATxDescFlag) +{ + FlagStatus bitstatus = RESET; + + if((DMATxDesc->Status & ETH_DMATxDescFlag) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetDMATxDescCollisionCount + * + * @brief Returns the specified ETHERNET DMA Tx Desc collision count. + * + * @param pointer on a DMA Tx descriptor. + * + * @return The Transmit descriptor collision counter value. + */ +uint32_t ETH_GetDMATxDescCollisionCount(ETH_DMADESCTypeDef *DMATxDesc) +{ + return ((DMATxDesc->Status & ETH_DMATxDesc_CC) >> ETH_DMATXDESC_COLLISION_COUNTSHIFT); +} + +/********************************************************************* + * @fn ETH_SetDMATxDescOwnBit + * + * @brief Set the specified DMA Tx Desc Own bit. + * + * @param DMATxDesc - Pointer on a Tx desc + * + * @return none + */ +void ETH_SetDMATxDescOwnBit(ETH_DMADESCTypeDef *DMATxDesc) +{ + DMATxDesc->Status |= ETH_DMATxDesc_OWN; +} + +/********************************************************************* + * @fn ETH_DMATxDescTransmitITConfig + * + * @brief Enables or disables the specified DMA Tx Desc Transmit interrupt. + * + * @param Pointer on a Tx desc. + * NewState - new state of the DMA Tx Desc transmit interrupt. + * + * @return none + */ +void ETH_DMATxDescTransmitITConfig(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status |= ETH_DMATxDesc_IC; + } + else + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_IC); + } +} + +/********************************************************************* + * @fn ETH_DMATxDescFrameSegmentConfig + * + * @brief Enables or disables the specified DMA Tx Desc Transmit interrupt. + * + * @param PDMATxDesc - Pointer on a Tx desc. + * ETH_DMATxDesc_FirstSegment - actual Tx desc contain first segment. + * + * @return none + */ +void ETH_DMATxDescFrameSegmentConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t DMATxDesc_FrameSegment) +{ + DMATxDesc->Status |= DMATxDesc_FrameSegment; +} + +/********************************************************************* + * @fn ETH_DMATxDescChecksumInsertionConfig + * + * @brief Selects the specified ETHERNET DMA Tx Desc Checksum Insertion. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor. + * DMATxDesc_Checksum - specifies is the DMA Tx desc checksum insertion. + * + * @return none + */ +void ETH_DMATxDescChecksumInsertionConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t DMATxDesc_Checksum) +{ + DMATxDesc->Status |= DMATxDesc_Checksum; +} + +/********************************************************************* + * @fn ETH_DMATxDescCRCCmd + * + * @brief Enables or disables the DMA Tx Desc CRC. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor + * NewState - new state of the specified DMA Tx Desc CRC. + * + * @return none + */ +void ETH_DMATxDescCRCCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_DC); + } + else + { + DMATxDesc->Status |= ETH_DMATxDesc_DC; + } +} + +/********************************************************************* + * @fn ETH_DMATxDescEndOfRingCmd + * + * @brief Enables or disables the DMA Tx Desc end of ring. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor. + * NewState - new state of the specified DMA Tx Desc end of ring. + * + * @return none + */ +void ETH_DMATxDescEndOfRingCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status |= ETH_DMATxDesc_TER; + } + else + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_TER); + } +} + +/********************************************************************* + * @fn ETH_DMATxDescSecondAddressChainedCmd + * + * @brief Enables or disables the DMA Tx Desc second address chained. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor + * NewState - new state of the specified DMA Tx Desc second address chained. + * + * @return none + */ +void ETH_DMATxDescSecondAddressChainedCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status |= ETH_DMATxDesc_TCH; + } + else + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_TCH); + } +} + +/********************************************************************* + * @fn ETH_DMATxDescShortFramePaddingCmd + * + * @brief Enables or disables the DMA Tx Desc padding for frame shorter than 64 bytes. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor. + * NewState - new state of the specified DMA Tx Desc padding for frame shorter than 64 bytes. + * + * @return none + */ +void ETH_DMATxDescShortFramePaddingCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_DP); + } + else + { + DMATxDesc->Status |= ETH_DMATxDesc_DP; + } +} + +/********************************************************************* + * @fn ETH_DMATxDescTimeStampCmd + * + * @brief Enables or disables the DMA Tx Desc time stamp. + * + * @param DMATxDesc - pointer on a DMA Tx descriptor + * NewState - new state of the specified DMA Tx Desc time stamp. + * + * @return none + */ +void ETH_DMATxDescTimeStampCmd(ETH_DMADESCTypeDef *DMATxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMATxDesc->Status |= ETH_DMATxDesc_TTSE; + } + else + { + DMATxDesc->Status &= (~(uint32_t)ETH_DMATxDesc_TTSE); + } +} + +/********************************************************************* + * @fn ETH_DMATxDescBufferSizeConfig + * + * @brief Configures the specified DMA Tx Desc buffer1 and buffer2 sizes. + * + * @param DMATxDesc - Pointer on a Tx desc. + * BufferSize1 - specifies the Tx desc buffer1 size. + * RxBuff2 - Pointer on the first RxBuffer2 list + * BufferSize2 - specifies the Tx desc buffer2 size (put "0" if not used). + * + * @return none + */ +void ETH_DMATxDescBufferSizeConfig(ETH_DMADESCTypeDef *DMATxDesc, uint32_t BufferSize1, uint32_t BufferSize2) +{ + DMATxDesc->ControlBufferSize |= (BufferSize1 | (BufferSize2 << ETH_DMATXDESC_BUFFER2_SIZESHIFT)); +} + +/********************************************************************* + * @fn ETH_DMARxDescChainInit + * + * @brief Initializes the DMA Rx descriptors in chain mode. + * + * @param DMARxDescTab - Pointer on the first Rx desc list. + * RxBuff - Pointer on the first RxBuffer list. + * RxBuffCount - Number of the used Rx desc in the list. + * + * @return none + */ +void ETH_DMARxDescChainInit(ETH_DMADESCTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMARxDesc; + + DMARxDescToGet = DMARxDescTab; + + for(i = 0; i < RxBuffCount; i++) + { + DMARxDesc = DMARxDescTab + i; + DMARxDesc->Status = ETH_DMARxDesc_OWN; + DMARxDesc->ControlBufferSize = ETH_DMARxDesc_RCH | (uint32_t)ETH_MAX_PACKET_SIZE; + DMARxDesc->Buffer1Addr = (uint32_t)(&RxBuff[i * ETH_MAX_PACKET_SIZE]); + + if(i < (RxBuffCount - 1)) + { + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab + i + 1); + } + else + { + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab); + } + } + + ETH->DMARDLAR = (uint32_t)DMARxDescTab; +} + +/********************************************************************* + * @fn ETH_DMARxDescRingInit + * + * @brief Initializes the DMA Rx descriptors in ring mode. + * + * @param DMARxDescTab - Pointer on the first Rx desc list. + * RxBuff1 - Pointer on the first RxBuffer1 list. + * RxBuff2 - Pointer on the first RxBuffer2 list + * RxBuffCount - Number of the used Rx desc in the list. + * + * @return none + */ +void ETH_DMARxDescRingInit(ETH_DMADESCTypeDef *DMARxDescTab, uint8_t *RxBuff1, uint8_t *RxBuff2, uint32_t RxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMARxDesc; + + DMARxDescToGet = DMARxDescTab; + + for(i = 0; i < RxBuffCount; i++) + { + DMARxDesc = DMARxDescTab + i; + DMARxDesc->Status = ETH_DMARxDesc_OWN; + DMARxDesc->ControlBufferSize = ETH_MAX_PACKET_SIZE; + DMARxDesc->Buffer1Addr = (uint32_t)(&RxBuff1[i * ETH_MAX_PACKET_SIZE]); + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(&RxBuff2[i * ETH_MAX_PACKET_SIZE]); + + if(i == (RxBuffCount - 1)) + { + DMARxDesc->ControlBufferSize |= ETH_DMARxDesc_RER; + } + } + + ETH->DMARDLAR = (uint32_t)DMARxDescTab; +} + +/********************************************************************* + * @fn ETH_GetDMARxDescFlagStatus + * + * @brief Checks whether the specified ETHERNET Rx Desc flag is set or not. + * + * @param DMARxDesc - pointer on a DMA Rx descriptor. + * ETH_DMARxDescFlag - specifies the flag to check. + * ETH_DMARxDesc_OWN - OWN bit: descriptor is owned by DMA engine + * ETH_DMARxDesc_AFM - DA Filter Fail for the rx frame + * ETH_DMARxDesc_ES - Error summary + * ETH_DMARxDesc_DE - Desciptor error: no more descriptors for receive frame + * ETH_DMARxDesc_SAF - SA Filter Fail for the received frame + * ETH_DMARxDesc_LE - Frame size not matching with length field + * ETH_DMARxDesc_OE - Overflow Error: Frame was damaged due to buffer overflow + * ETH_DMARxDesc_VLAN - VLAN Tag: received frame is a VLAN frame + * ETH_DMARxDesc_FS - First descriptor of the frame + * ETH_DMARxDesc_LS - Last descriptor of the frame + * ETH_DMARxDesc_IPV4HCE - IPC Checksum Error/Giant Frame: Rx Ipv4 header checksum error + * ETH_DMARxDesc_LC - Late collision occurred during reception + * ETH_DMARxDesc_FT - Frame type - Ethernet, otherwise 802.3 + * ETH_DMARxDesc_RWT - Receive Watchdog Timeout: watchdog timer expired during reception + * ETH_DMARxDesc_RE - Receive error: error reported by MII interface + * ETH_DMARxDesc_DE - Dribble bit error: frame contains non int multiple of 8 bits + * ETH_DMARxDesc_CE - CRC error + * ETH_DMARxDesc_MAMPCE - Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error + * + * @return The new state of ETH_DMARxDescFlag (SET or RESET). + */ +FlagStatus ETH_GetDMARxDescFlagStatus(ETH_DMADESCTypeDef *DMARxDesc, uint32_t ETH_DMARxDescFlag) +{ + FlagStatus bitstatus = RESET; + + if((DMARxDesc->Status & ETH_DMARxDescFlag) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_SetDMARxDescOwnBit + * + * @brief Set the specified DMA Rx Desc Own bit. + * + * @param DMARxDesc - Pointer on a Rx desc + * + * @return none + */ +void ETH_SetDMARxDescOwnBit(ETH_DMADESCTypeDef *DMARxDesc) +{ + DMARxDesc->Status |= ETH_DMARxDesc_OWN; +} + +/********************************************************************* + * @fn ETH_GetDMARxDescFrameLength + * + * @brief Returns the specified DMA Rx Desc frame length. + * + * @param DMARxDesc - pointer on a DMA Rx descriptor + * + * @return The Rx descriptor received frame length. + */ +uint32_t ETH_GetDMARxDescFrameLength(ETH_DMADESCTypeDef *DMARxDesc) +{ + return ((DMARxDesc->Status & ETH_DMARxDesc_FL) >> ETH_DMARXDESC_FRAME_LENGTHSHIFT); +} + +/********************************************************************* + * @fn ETH_DMARxDescReceiveITConfig + * + * @brief Enables or disables the specified DMA Rx Desc receive interrupt. + * + * @param DMARxDesc - Pointer on a Rx desc + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void ETH_DMARxDescReceiveITConfig(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMARxDesc->ControlBufferSize &= (~(uint32_t)ETH_DMARxDesc_DIC); + } + else + { + DMARxDesc->ControlBufferSize |= ETH_DMARxDesc_DIC; + } +} + +/********************************************************************* + * @fn ETH_DMARxDescEndOfRingCmd + * + * @brief Enables or disables the DMA Rx Desc end of ring. + * + * @param DMARxDesc - pointer on a DMA Rx descriptor. + * NewState - new state of the specified DMA Rx Desc end of ring. + * + * @return none + */ +void ETH_DMARxDescEndOfRingCmd(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMARxDesc->ControlBufferSize |= ETH_DMARxDesc_RER; + } + else + { + DMARxDesc->ControlBufferSize &= (~(uint32_t)ETH_DMARxDesc_RER); + } +} + +/********************************************************************* + * @fn ETH_DMARxDescSecondAddressChainedCmd + * + * @brief Returns the specified ETHERNET DMA Rx Desc buffer size. + * + * @param DMARxDesc - pointer on a DMA Rx descriptor. + * NewState - new state of the specified DMA Rx Desc second address chained. + * + * @return none + */ +void ETH_DMARxDescSecondAddressChainedCmd(ETH_DMADESCTypeDef *DMARxDesc, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + DMARxDesc->ControlBufferSize |= ETH_DMARxDesc_RCH; + } + else + { + DMARxDesc->ControlBufferSize &= (~(uint32_t)ETH_DMARxDesc_RCH); + } +} + +/********************************************************************* + * @fn ETH_GetDMARxDescBufferSize + * + * @brief Returns the specified ETHERNET DMA Rx Desc buffer size. + * + * @param DMARxDesc - pointer on a DMA Rx descriptor. + * DMARxDesc_Buffer - specifies the DMA Rx Desc buffer. + * ETH_DMARxDesc_Buffer1 - DMA Rx Desc Buffer1 + * ETH_DMARxDesc_Buffer2 - DMA Rx Desc Buffer2 + * + * @return The Receive descriptor frame length. + */ +uint32_t ETH_GetDMARxDescBufferSize(ETH_DMADESCTypeDef *DMARxDesc, uint32_t DMARxDesc_Buffer) +{ + if(DMARxDesc_Buffer != ETH_DMARxDesc_Buffer1) + { + return ((DMARxDesc->ControlBufferSize & ETH_DMARxDesc_RBS2) >> ETH_DMARXDESC_BUFFER2_SIZESHIFT); + } + else + { + return (DMARxDesc->ControlBufferSize & ETH_DMARxDesc_RBS1); + } +} + +/********************************************************************* + * @fn ETH_SoftwareReset + * + * @brief Resets all MAC subsystem internal registers and logic. + * + * @return none + */ +void ETH_SoftwareReset(void) +{ + ETH->DMABMR |= ETH_DMABMR_SR; +} + +/********************************************************************* + * @fn ETH_GetSoftwareResetStatus + * + * @brief Checks whether the ETHERNET software reset bit is set or not. + * + * @return The new state of DMA Bus Mode register SR bit (SET or RESET). + */ +FlagStatus ETH_GetSoftwareResetStatus(void) +{ + FlagStatus bitstatus = RESET; + if((ETH->DMABMR & ETH_DMABMR_SR) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetlinkStaus + * + * @brief Checks whether the internal 10BASE-T PHY is link or not. + * + * @return Internal 10BASE-T PHY is link or not. + */ +FlagStatus ETH_GetlinkStaus(void) +{ + FlagStatus bitstatus = RESET; + + if((ETH->DMASR & 0x80000000) != (uint32_t)RESET) + { + bitstatus = PHY_10BASE_T_LINKED; + } + else + { + bitstatus = PHY_10BASE_T_NOT_LINKED; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetDMAFlagStatus + * + * @brief Checks whether the specified ETHERNET DMA flag is set or not. + * + * @param ETH_DMA_FLAG - specifies the flag to check. + * ETH_DMA_FLAG_TST - Time-stamp trigger flag + * ETH_DMA_FLAG_PMT - PMT flag + * ETH_DMA_FLAG_MMC - MMC flag + * ETH_DMA_FLAG_DataTransferError - Error bits 0-data buffer, 1-desc. access + * ETH_DMA_FLAG_ReadWriteError - Error bits 0-write trnsf, 1-read transfr + * ETH_DMA_FLAG_AccessError - Error bits 0-Rx DMA, 1-Tx DMA + * ETH_DMA_FLAG_NIS - Normal interrupt summary flag + * ETH_DMA_FLAG_AIS - Abnormal interrupt summary flag + * ETH_DMA_FLAG_ER - Early receive flag + * ETH_DMA_FLAG_FBE - Fatal bus error flag + * ETH_DMA_FLAG_ET - Early transmit flag + * ETH_DMA_FLAG_RWT - Receive watchdog timeout flag + * ETH_DMA_FLAG_RPS - Receive process stopped flag + * ETH_DMA_FLAG_RBU - Receive buffer unavailable flag + * ETH_DMA_FLAG_R - Receive flag + * ETH_DMA_FLAG_TU - Underflow flag + * ETH_DMA_FLAG_RO - Overflow flag + * ETH_DMA_FLAG_TJT - Transmit jabber timeout flag + * ETH_DMA_FLAG_TBU - Transmit buffer unavailable flag + * ETH_DMA_FLAG_TPS - Transmit process stopped flag + * ETH_DMA_FLAG_T - Transmit flag + * + * @return Internal 10BASE-T PHY is link or not. + */ +FlagStatus ETH_GetDMAFlagStatus(uint32_t ETH_DMA_FLAG) +{ + FlagStatus bitstatus = RESET; + + if((ETH->DMASR & ETH_DMA_FLAG) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_DMAClearFlag + * + * @brief Checks whether the specified ETHERNET DMA interrupt has occured or not. + * + * @param ETH_DMA_FLAG - specifies the flag to clear. + * ETH_DMA_FLAG_NIS - Normal interrupt summary flag + * ETH_DMA_FLAG_AIS - Abnormal interrupt summary flag + * ETH_DMA_FLAG_ER - Early receive flag + * ETH_DMA_FLAG_FBE - Fatal bus error flag + * ETH_DMA_FLAG_ETI - Early transmit flag + * ETH_DMA_FLAG_RWT - Receive watchdog timeout flag + * ETH_DMA_FLAG_RPS - Receive process stopped flag + * ETH_DMA_FLAG_RBU - Receive buffer unavailable flag + * ETH_DMA_FLAG_R - Receive flag + * ETH_DMA_FLAG_TU - Transmit Underflow flag + * ETH_DMA_FLAG_RO - Receive Overflow flag + * ETH_DMA_FLAG_TJT - Transmit jabber timeout flag + * ETH_DMA_FLAG_TBU - Transmit buffer unavailable flag + * ETH_DMA_FLAG_TPS - Transmit process stopped flag + * ETH_DMA_FLAG_T - Transmit flag + * + * @return none + */ +void ETH_DMAClearFlag(uint32_t ETH_DMA_FLAG) +{ + ETH->DMASR = (uint32_t)ETH_DMA_FLAG; +} + +/********************************************************************* + * @fn ETH_GetDMAITStatus + * + * @brief Checks whether the specified ETHERNET DMA interrupt has occured or not. + * + * @param ETH_DMA_IT - specifies the interrupt pending bit to clear. + * ETH_DMA_IT_TST - Time-stamp trigger interrupt + * ETH_DMA_IT_PMT - PMT interrupt + * ETH_DMA_IT_MMC - MMC interrupt + * ETH_DMA_IT_NIS - Normal interrupt summary + * ETH_DMA_IT_AIS - Abnormal interrupt summary + * ETH_DMA_IT_ER - Early receive interrupt + * ETH_DMA_IT_FBE - Fatal bus error interrupt + * ETH_DMA_IT_ET - Early transmit interrupt + * ETH_DMA_IT_RWT - Receive watchdog timeout interrupt + * ETH_DMA_IT_RPS - Receive process stopped interrupt + * ETH_DMA_IT_RBU - Receive buffer unavailable interrupt + * ETH_DMA_IT_R - Receive interrupt + * ETH_DMA_IT_TU - Underflow interrupt + * ETH_DMA_IT_RO - Overflow interrupt + * ETH_DMA_IT_TJT - Transmit jabber timeout interrupt + * ETH_DMA_IT_TBU - Transmit buffer unavailable interrupt + * ETH_DMA_IT_TPS - Transmit process stopped interrupt + * ETH_DMA_IT_T - Transmit interrupt + * + * @return The new state of ETH_DMA_IT (SET or RESET). + */ +ITStatus ETH_GetDMAITStatus(uint32_t ETH_DMA_IT) +{ + ITStatus bitstatus = RESET; + + if((ETH->DMASR & ETH_DMA_IT) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_DMAClearITPendingBit + * + * @brief Clears the ETHERNET"s DMA IT pending bit. + * + * @param ETH_DMA_IT - specifies the interrupt pending bit to clear. + * ETH_DMA_IT_NIS - Normal interrupt summary + * ETH_DMA_IT_AIS - Abnormal interrupt summary + * ETH_DMA_IT_ER - Early receive interrupt + * ETH_DMA_IT_FBE - Fatal bus error interrupt + * ETH_DMA_IT_ETI - Early transmit interrupt + * ETH_DMA_IT_RWT - Receive watchdog timeout interrupt + * ETH_DMA_IT_RPS - Receive process stopped interrupt + * ETH_DMA_IT_RBU - Receive buffer unavailable interrupt + * ETH_DMA_IT_R - Receive interrupt + * ETH_DMA_IT_TU - Transmit Underflow interrupt + * ETH_DMA_IT_RO - Receive Overflow interrupt + * ETH_DMA_IT_TJT - Transmit jabber timeout interrupt + * ETH_DMA_IT_TBU - Transmit buffer unavailable interrupt + * ETH_DMA_IT_TPS - Transmit process stopped interrupt + * ETH_DMA_IT_T - Transmit interrupt + * + * @return none + */ +void ETH_DMAClearITPendingBit(uint32_t ETH_DMA_IT) +{ + ETH->DMASR = (uint32_t)ETH_DMA_IT; +} + +/********************************************************************* + * @fn ETH_GetTransmitProcessState + * + * @brief Returns the ETHERNET DMA Transmit Process State. + * + * @return The new ETHERNET DMA Transmit Process State - + * ETH_DMA_TransmitProcess_Stopped - Stopped - Reset or Stop Tx Command issued + * ETH_DMA_TransmitProcess_Fetching - Running - fetching the Tx descriptor + * ETH_DMA_TransmitProcess_Waiting - Running - waiting for status + * ETH_DMA_TransmitProcess_Reading - unning - reading the data from host memory + * ETH_DMA_TransmitProcess_Suspended - Suspended - Tx Desciptor unavailabe + * ETH_DMA_TransmitProcess_Closing - Running - closing Rx descriptor + */ +uint32_t ETH_GetTransmitProcessState(void) +{ + return ((uint32_t)(ETH->DMASR & ETH_DMASR_TS)); +} + +/********************************************************************* + * @fn ETH_GetReceiveProcessState + * + * @brief Returns the ETHERNET DMA Receive Process State. + * + * @return The new ETHERNET DMA Receive Process State: + * ETH_DMA_ReceiveProcess_Stopped - Stopped - Reset or Stop Rx Command issued + * ETH_DMA_ReceiveProcess_Fetching - Running - fetching the Rx descriptor + * ETH_DMA_ReceiveProcess_Waiting - Running - waiting for packet + * ETH_DMA_ReceiveProcess_Suspended - Suspended - Rx Desciptor unavailable + * ETH_DMA_ReceiveProcess_Closing - Running - closing descriptor + * ETH_DMA_ReceiveProcess_Queuing - Running - queuing the recieve frame into host memory + */ +uint32_t ETH_GetReceiveProcessState(void) +{ + return ((uint32_t)(ETH->DMASR & ETH_DMASR_RS)); +} + +/********************************************************************* + * @fn ETH_FlushTransmitFIFO + * + * @brief Clears the ETHERNET transmit FIFO. + * + * @return none + */ +void ETH_FlushTransmitFIFO(void) +{ + ETH->DMAOMR |= ETH_DMAOMR_FTF; +} + +/********************************************************************* + * @fn ETH_GetFlushTransmitFIFOStatus + * + * @brief Checks whether the ETHERNET transmit FIFO bit is cleared or not. + * + * @return The new state of ETHERNET flush transmit FIFO bit (SET or RESET). + */ +FlagStatus ETH_GetFlushTransmitFIFOStatus(void) +{ + FlagStatus bitstatus = RESET; + if((ETH->DMAOMR & ETH_DMAOMR_FTF) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_DMATransmissionCmd + * + * @brief Enables or disables the DMA transmission. + * + * @param NewState - new state of the DMA transmission. + * + * @return none + */ +void ETH_DMATransmissionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->DMAOMR |= ETH_DMAOMR_ST; + } + else + { + ETH->DMAOMR &= ~ETH_DMAOMR_ST; + } +} + +/********************************************************************* + * @fn ETH_DMAReceptionCmd + * + * @brief Enables or disables the DMA reception. + * + * @param NewState - new state of the DMA reception. + * + * @return none + */ +void ETH_DMAReceptionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->DMAOMR |= ETH_DMAOMR_SR; + } + else + { + ETH->DMAOMR &= ~ETH_DMAOMR_SR; + } +} + +/********************************************************************* + * @fn ETH_DMAITConfig + * + * @brief Enables or disables the specified ETHERNET DMA interrupts. + * + * @param ETH_DMA_IT - specifies the ETHERNET DMA interrupt sources to be enabled or disabled. + * ETH_DMA_IT_NIS - Normal interrupt summary + * ETH_DMA_IT_AIS - Abnormal interrupt summary + * ETH_DMA_IT_ER - Early receive interrupt + * ETH_DMA_IT_FBE - Fatal bus error interrupt + * ETH_DMA_IT_ET - Early transmit interrupt + * ETH_DMA_IT_RWT - Receive watchdog timeout interrupt + * ETH_DMA_IT_RPS - Receive process stopped interrupt + * ETH_DMA_IT_RBU - Receive buffer unavailable interrupt + * ETH_DMA_IT_R - Receive interrupt + * ETH_DMA_IT_TU - Underflow interrupt + * ETH_DMA_IT_RO - Overflow interrupt + * ETH_DMA_IT_TJT - Transmit jabber timeout interrupt + * ETH_DMA_IT_TBU - Transmit buffer unavailable interrupt + * ETH_DMA_IT_TPS - Transmit process stopped interrupt + * ETH_DMA_IT_T - Transmit interrupt + * ETH_DMA_Overflow_RxFIFOCounter - Overflow for FIFO Overflow Counter + * ETH_DMA_Overflow_MissedFrameCounter - Overflow for Missed Frame Counter + * NewState - new state of the specified ETHERNET DMA interrupts. + * + * @return new state of the specified ETHERNET DMA interrupts. + */ +void ETH_DMAITConfig(uint32_t ETH_DMA_IT, FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->DMAIER |= ETH_DMA_IT; + } + else + { + ETH->DMAIER &= (~(uint32_t)ETH_DMA_IT); + } +} + +/********************************************************************* + * @fn ETH_GetDMAOverflowStatus + * + * @brief Checks whether the specified ETHERNET DMA overflow flag is set or not. + * + * @param ETH_DMA_Overflow - specifies the DMA overflow flag to check. + * ETH_DMA_Overflow_RxFIFOCounter - Overflow for FIFO Overflow Counter + * ETH_DMA_Overflow_MissedFrameCounter - Overflow for Missed Frame Counter + * + * @return The new state of ETHERNET DMA overflow Flag (SET or RESET). + */ +FlagStatus ETH_GetDMAOverflowStatus(uint32_t ETH_DMA_Overflow) +{ + FlagStatus bitstatus = RESET; + + if((ETH->DMAMFBOCR & ETH_DMA_Overflow) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetRxOverflowMissedFrameCounter + * + * @brief Get the ETHERNET DMA Rx Overflow Missed Frame Counter value. + * + * @return The value of Rx overflow Missed Frame Counter. + */ +uint32_t ETH_GetRxOverflowMissedFrameCounter(void) +{ + return ((uint32_t)((ETH->DMAMFBOCR & ETH_DMAMFBOCR_MFA) >> ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT)); +} + +/********************************************************************* + * @fn ETH_GetBufferUnavailableMissedFrameCounter + * + * @brief Get the ETHERNET DMA Buffer Unavailable Missed Frame Counter value. + * + * @return The value of Buffer unavailable Missed Frame Counter. + */ +uint32_t ETH_GetBufferUnavailableMissedFrameCounter(void) +{ + return ((uint32_t)(ETH->DMAMFBOCR) & ETH_DMAMFBOCR_MFC); +} + +/********************************************************************* + * @fn ETH_GetCurrentTxDescStartAddress + * + * @brief Get the ETHERNET DMA DMACHTDR register value. + * + * @return The value of the current Tx desc start address. + */ +uint32_t ETH_GetCurrentTxDescStartAddress(void) +{ + return ((uint32_t)(ETH->DMACHTDR)); +} + +/********************************************************************* + * @fn ETH_GetCurrentRxDescStartAddress + * + * @brief Get the ETHERNET DMA DMACHRDR register value. + * + * @return The value of the current Rx desc start address. + */ +uint32_t ETH_GetCurrentRxDescStartAddress(void) +{ + return ((uint32_t)(ETH->DMACHRDR)); +} + +/********************************************************************* + * @fn ETH_GetCurrentTxBufferAddress + * + * @brief Get the ETHERNET DMA DMACHTBAR register value. + * + * @return The value of the current Tx buffer address. + */ +uint32_t ETH_GetCurrentTxBufferAddress(void) +{ + return (DMATxDescToSet->Buffer1Addr); +} + +/********************************************************************* + * @fn ETH_GetCurrentRxBufferAddress + * + * @brief Get the ETHERNET DMA DMACHRBAR register value. + * + * @return The value of the current Rx buffer address. + */ +uint32_t ETH_GetCurrentRxBufferAddress(void) +{ + return ((uint32_t)(ETH->DMACHRBAR)); +} + +/********************************************************************* + * @fn ETH_ResumeDMATransmission + * + * @brief Resumes the DMA Transmission by writing to the DmaTxPollDemand register + * + * @return none + */ +void ETH_ResumeDMATransmission(void) +{ + ETH->DMATPDR = 0; +} + +/********************************************************************* + * @fn ETH_ResumeDMAReception + * + * @brief Resumes the DMA Transmission by writing to the DmaRxPollDemand register. + * + * @return none + */ +void ETH_ResumeDMAReception(void) +{ + ETH->DMARPDR = 0; +} + +/********************************************************************* + * @fn ETH_ResetWakeUpFrameFilterRegisterPointer + * + * @brief Reset Wakeup frame filter register pointer. + * + * @return none + */ +void ETH_ResetWakeUpFrameFilterRegisterPointer(void) +{ + ETH->MACPMTCSR |= ETH_MACPMTCSR_WFFRPR; +} + +/********************************************************************* + * @fn ETH_SetWakeUpFrameFilterRegister + * + * @brief Populates the remote wakeup frame registers. + * + * @param Buffer - Pointer on remote WakeUp Frame Filter Register buffer data (8 words). + * + * @return none + */ +void ETH_SetWakeUpFrameFilterRegister(uint32_t *Buffer) +{ + uint32_t i = 0; + + for(i = 0; i < ETH_WAKEUP_REGISTER_LENGTH; i++) + { + ETH->MACRWUFFR = Buffer[i]; + } +} + +/********************************************************************* + * @fn ETH_GlobalUnicastWakeUpCmd + * + * @brief Enables or disables any unicast packet filtered by the MAC address. + * + * @param NewState - new state of the MAC Global Unicast Wake-Up. + * + * @return none + */ +void ETH_GlobalUnicastWakeUpCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACPMTCSR |= ETH_MACPMTCSR_GU; + } + else + { + ETH->MACPMTCSR &= ~ETH_MACPMTCSR_GU; + } +} + +/********************************************************************* + * @fn ETH_GetPMTFlagStatus + * + * @brief Checks whether the specified ETHERNET PMT flag is set or not. + * + * @param ETH_PMT_FLAG - specifies the flag to check. + * + * @return The new state of ETHERNET PMT Flag (SET or RESET). + */ +FlagStatus ETH_GetPMTFlagStatus(uint32_t ETH_PMT_FLAG) +{ + FlagStatus bitstatus = RESET; + + if((ETH->MACPMTCSR & ETH_PMT_FLAG) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_WakeUpFrameDetectionCmd + * + * @brief Enables or disables the MAC Wake-Up Frame Detection. + * + * @param NewState - new state of the MAC Wake-Up Frame Detection. + * + * @return none + */ +void ETH_WakeUpFrameDetectionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACPMTCSR |= ETH_MACPMTCSR_WFE; + } + else + { + ETH->MACPMTCSR &= ~ETH_MACPMTCSR_WFE; + } +} + +/********************************************************************* + * @fn ETH_MagicPacketDetectionCmd + * + * @brief Enables or disables the MAC Magic Packet Detection. + * + * @param NewState - new state of the MAC Magic Packet Detection. + * + * @return none + */ +void ETH_MagicPacketDetectionCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACPMTCSR |= ETH_MACPMTCSR_MPE; + } + else + { + ETH->MACPMTCSR &= ~ETH_MACPMTCSR_MPE; + } +} + +/********************************************************************* + * @fn ETH_PowerDownCmd + * + * @brief Enables or disables the MAC Power Down. + * + * @param NewState - new state of the MAC Power Down. + * + * @return none + */ +void ETH_PowerDownCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MACPMTCSR |= ETH_MACPMTCSR_PD; + } + else + { + ETH->MACPMTCSR &= ~ETH_MACPMTCSR_PD; + } +} + +/********************************************************************* + * @fn ETH_MMCCounterFreezeCmd + * + * @brief Enables or disables the MMC Counter Freeze. + * + * @param NewState - new state of the MMC Counter Freeze. + * + * @return none + */ +void ETH_MMCCounterFreezeCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MMCCR |= ETH_MMCCR_MCF; + } + else + { + ETH->MMCCR &= ~ETH_MMCCR_MCF; + } +} + +/********************************************************************* + * @fn ETH_MMCResetOnReadCmd + * + * @brief Enables or disables the MMC Reset On Read. + * + * @param NewState - new state of the MMC Reset On Read. + * + * @return none + */ +void ETH_MMCResetOnReadCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MMCCR |= ETH_MMCCR_ROR; + } + else + { + ETH->MMCCR &= ~ETH_MMCCR_ROR; + } +} + +/********************************************************************* + * @fn ETH_MMCCounterRolloverCmd + * + * @brief Enables or disables the MMC Counter Stop Rollover. + * + * @param NewState - new state of the MMC Counter Stop Rollover. + * + * @return none + */ +void ETH_MMCCounterRolloverCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->MMCCR &= ~ETH_MMCCR_CSR; + } + else + { + ETH->MMCCR |= ETH_MMCCR_CSR; + } +} + +/********************************************************************* + * @fn ETH_MMCCountersReset + * + * @brief Resets the MMC Counters. + * + * @return none + */ +void ETH_MMCCountersReset(void) +{ + ETH->MMCCR |= ETH_MMCCR_CR; +} + +/********************************************************************* + * @fn ETH_MMCITConfig + * + * @brief Enables or disables the specified ETHERNET MMC interrupts. + * + * @param ETH_MMC_IT - specifies the ETHERNET MMC interrupt. + * ETH_MMC_IT_TGF - When Tx good frame counter reaches half the maximum value. + * ETH_MMC_IT_TGFMSC - When Tx good multi col counter reaches half the maximum value. + * ETH_MMC_IT_TGFSC - When Tx good single col counter reaches half the maximum value. + * ETH_MMC_IT_RGUF - When Rx good unicast frames counter reaches half the maximum value. + * ETH_MMC_IT_RFAE - When Rx alignment error counter reaches half the maximum value. + * ETH_MMC_IT_RFCE - When Rx crc error counter reaches half the maximum value. + * NewState - new state of the specified ETHERNET MMC interrupts. + * + * @return none + */ +void ETH_MMCITConfig(uint32_t ETH_MMC_IT, FunctionalState NewState) +{ + if((ETH_MMC_IT & (uint32_t)0x10000000) != (uint32_t)RESET) + { + ETH_MMC_IT &= 0xEFFFFFFF; + + if(NewState != DISABLE) + { + ETH->MMCRIMR &= (~(uint32_t)ETH_MMC_IT); + } + else + { + ETH->MMCRIMR |= ETH_MMC_IT; + } + } + else + { + if(NewState != DISABLE) + { + ETH->MMCTIMR &= (~(uint32_t)ETH_MMC_IT); + } + else + { + ETH->MMCTIMR |= ETH_MMC_IT; + } + } +} + +/********************************************************************* + * @fn ETH_GetMMCITStatus + * + * @brief Checks whether the specified ETHERNET MMC IT is set or not. + * + * @param ETH_MMC_IT - specifies the ETHERNET MMC interrupt. + * ETH_MMC_IT_TxFCGC - When Tx good frame counter reaches half the maximum value. + * ETH_MMC_IT_TxMCGC - When Tx good multi col counter reaches half the maximum value. + * ETH_MMC_IT_TxSCGC - When Tx good single col counter reaches half the maximum value . + * ETH_MMC_IT_RxUGFC - When Rx good unicast frames counter reaches half the maximum value. + * ETH_MMC_IT_RxAEC - When Rx alignment error counter reaches half the maximum value. + * ETH_MMC_IT_RxCEC - When Rx crc error counter reaches half the maximum value. + * + * @return The value of ETHERNET MMC IT (SET or RESET). + */ +ITStatus ETH_GetMMCITStatus(uint32_t ETH_MMC_IT) +{ + ITStatus bitstatus = RESET; + + if((ETH_MMC_IT & (uint32_t)0x10000000) != (uint32_t)RESET) + { + if((((ETH->MMCRIR & ETH_MMC_IT) != (uint32_t)RESET)) && ((ETH->MMCRIMR & ETH_MMC_IT) != (uint32_t)RESET)) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + } + else + { + if((((ETH->MMCTIR & ETH_MMC_IT) != (uint32_t)RESET)) && ((ETH->MMCRIMR & ETH_MMC_IT) != (uint32_t)RESET)) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + } + + return bitstatus; +} + +/********************************************************************* + * @fn ETH_GetMMCRegister + * + * @brief Get the specified ETHERNET MMC register value. + * + * @param ETH_MMCReg - specifies the ETHERNET MMC register. + * ETH_MMCCR - MMC CR register + * ETH_MMCRIR - MMC RIR register + * ETH_MMCTIR - MMC TIR register + * ETH_MMCRIMR - MMC RIMR register + * ETH_MMCTIMR - MMC TIMR register + * ETH_MMCTGFSCCR - MMC TGFSCCR register + * ETH_MMCTGFMSCCR - MMC TGFMSCCR register + * ETH_MMCTGFCR - MMC TGFCR register + * ETH_MMCRFCECR - MMC RFCECR register + * ETH_MMCRFAECR - MMC RFAECR register + * ETH_MMCRGUFCR - MMC RGUFCRregister + * + * @return The value of ETHERNET MMC Register value. + */ +uint32_t ETH_GetMMCRegister(uint32_t ETH_MMCReg) +{ + return (*(__IO uint32_t *)(ETH_MAC_BASE + ETH_MMCReg)); +} + +/********************************************************************* + * @fn ETH_EnablePTPTimeStampAddend + * + * @brief Updated the PTP block for fine correction with the Time Stamp Addend register value. + * + * @return none + */ +void ETH_EnablePTPTimeStampAddend(void) +{ + ETH->PTPTSCR |= ETH_PTPTSCR_TSARU; +} + +/********************************************************************* + * @fn ETH_EnablePTPTimeStampInterruptTrigger + * + * @brief Enable the PTP Time Stamp interrupt trigger + * + * @return none + */ +void ETH_EnablePTPTimeStampInterruptTrigger(void) +{ + ETH->PTPTSCR |= ETH_PTPTSCR_TSITE; +} + +/********************************************************************* + * @fn ETH_EnablePTPTimeStampUpdate + * + * @brief Updated the PTP system time with the Time Stamp Update register value. + * + * @return none + */ +void ETH_EnablePTPTimeStampUpdate(void) +{ + ETH->PTPTSCR |= ETH_PTPTSCR_TSSTU; +} + +/********************************************************************* + * @fn ETH_InitializePTPTimeStamp + * + * @brief Initialize the PTP Time Stamp. + * + * @return none + */ +void ETH_InitializePTPTimeStamp(void) +{ + ETH->PTPTSCR |= ETH_PTPTSCR_TSSTI; +} + +/********************************************************************* + * @fn ETH_PTPUpdateMethodConfig + * + * @brief Selects the PTP Update method. + * + * @param UpdateMethod - the PTP Update method. + * + * @return none + */ +void ETH_PTPUpdateMethodConfig(uint32_t UpdateMethod) +{ + if(UpdateMethod != ETH_PTP_CoarseUpdate) + { + ETH->PTPTSCR |= ETH_PTPTSCR_TSFCU; + } + else + { + ETH->PTPTSCR &= (~(uint32_t)ETH_PTPTSCR_TSFCU); + } +} + +/********************************************************************* + * @fn ETH_PTPTimeStampCmd + * + * @brief Enables or disables the PTP time stamp for transmit and receive frames. + * + * @param NewState - new state of the PTP time stamp for transmit and receive frames. + * + * @return none + */ +void ETH_PTPTimeStampCmd(FunctionalState NewState) +{ + if(NewState != DISABLE) + { + ETH->PTPTSCR |= ETH_PTPTSCR_TSE; + } + else + { + ETH->PTPTSCR &= (~(uint32_t)ETH_PTPTSCR_TSE); + } +} + +/********************************************************************* + * @fn ETH_GetPTPFlagStatus + * + * @brief Checks whether the specified ETHERNET PTP flag is set or not. + * + * @param The new state of ETHERNET PTP Flag (SET or RESET). + * + * @return none + */ +FlagStatus ETH_GetPTPFlagStatus(uint32_t ETH_PTP_FLAG) +{ + FlagStatus bitstatus = RESET; + + if((ETH->PTPTSCR & ETH_PTP_FLAG) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + return bitstatus; +} + +/********************************************************************* + * @fn ETH_SetPTPSubSecondIncrement + * + * @brief Sets the system time Sub-Second Increment value. + * + * @param SubSecondValue - specifies the PTP Sub-Second Increment Register value. + * + * @return none + */ +void ETH_SetPTPSubSecondIncrement(uint32_t SubSecondValue) +{ + ETH->PTPSSIR = SubSecondValue; +} + +/********************************************************************* + * @fn ETH_SetPTPTimeStampUpdate + * + * @brief Sets the Time Stamp update sign and values. + * + * @param Sign - specifies the PTP Time update value sign. + * SecondValue - specifies the PTP Time update second value. + * SubSecondValue - specifies the PTP Time update sub-second value. + * + * @return none + */ +void ETH_SetPTPTimeStampUpdate(uint32_t Sign, uint32_t SecondValue, uint32_t SubSecondValue) +{ + ETH->PTPTSHUR = SecondValue; + ETH->PTPTSLUR = Sign | SubSecondValue; +} + +/********************************************************************* + * @fn ETH_SetPTPTimeStampAddend + * + * @brief Sets the Time Stamp Addend value. + * + * @param Value - specifies the PTP Time Stamp Addend Register value. + * + * @return none + */ +void ETH_SetPTPTimeStampAddend(uint32_t Value) +{ + /* Set the PTP Time Stamp Addend Register */ + ETH->PTPTSAR = Value; +} + +/********************************************************************* + * @fn ETH_SetPTPTargetTime + * + * @brief Sets the Target Time registers values. + * + * @param HighValue - specifies the PTP Target Time High Register value. + * LowValue - specifies the PTP Target Time Low Register value. + * + * @return none + */ +void ETH_SetPTPTargetTime(uint32_t HighValue, uint32_t LowValue) +{ + ETH->PTPTTHR = HighValue; + ETH->PTPTTLR = LowValue; +} + +/********************************************************************* + * @fn ETH_GetPTPRegister + * + * @brief Get the specified ETHERNET PTP register value. + * + * @param ETH_PTPReg - specifies the ETHERNET PTP register. + * ETH_PTPTSCR - Sub-Second Increment Register + * ETH_PTPSSIR - Sub-Second Increment Register + * ETH_PTPTSHR - Time Stamp High Register + * ETH_PTPTSLR - Time Stamp Low Register + * ETH_PTPTSHUR - Time Stamp High Update Register + * ETH_PTPTSLUR - Time Stamp Low Update Register + * ETH_PTPTSAR - Time Stamp Addend Register + * ETH_PTPTTHR - Target Time High Register + * ETH_PTPTTLR - Target Time Low Register + * + * @return The value of ETHERNET PTP Register value. + */ +uint32_t ETH_GetPTPRegister(uint32_t ETH_PTPReg) +{ + return (*(__IO uint32_t *)(ETH_MAC_BASE + ETH_PTPReg)); +} + +/********************************************************************* + * @fn ETH_DMAPTPTxDescChainInit + * + * @brief Initializes the DMA Tx descriptors in chain mode with PTP. + * + * @param DMATxDescTab - Pointer on the first Tx desc list. + * DMAPTPTxDescTab - Pointer on the first PTP Tx desc list. + * TxBuff - Pointer on the first TxBuffer list. + * TxBuffCount - Number of the used Tx desc in the list. + * + * @return none. + */ +void ETH_DMAPTPTxDescChainInit(ETH_DMADESCTypeDef *DMATxDescTab, ETH_DMADESCTypeDef *DMAPTPTxDescTab, + uint8_t *TxBuff, uint32_t TxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMATxDesc; + + DMATxDescToSet = DMATxDescTab; + DMAPTPTxDescToSet = DMAPTPTxDescTab; + + for(i = 0; i < TxBuffCount; i++) + { + DMATxDesc = DMATxDescTab + i; + DMATxDesc->Status = ETH_DMATxDesc_TCH | ETH_DMATxDesc_TTSE; + DMATxDesc->Buffer1Addr = (uint32_t)(&TxBuff[i * ETH_MAX_PACKET_SIZE]); + + if(i < (TxBuffCount - 1)) + { + DMATxDesc->Buffer2NextDescAddr = (uint32_t)(DMATxDescTab + i + 1); + } + else + { + DMATxDesc->Buffer2NextDescAddr = (uint32_t)DMATxDescTab; + } + + (&DMAPTPTxDescTab[i])->Buffer1Addr = DMATxDesc->Buffer1Addr; + (&DMAPTPTxDescTab[i])->Buffer2NextDescAddr = DMATxDesc->Buffer2NextDescAddr; + } + + (&DMAPTPTxDescTab[i - 1])->Status = (uint32_t)DMAPTPTxDescTab; + + ETH->DMATDLAR = (uint32_t)DMATxDescTab; +} + +/********************************************************************* + * @fn ETH_DMAPTPRxDescChainInit + * + * @brief Initializes the DMA Rx descriptors in chain mode. + * + * @param DMARxDescTab - Pointer on the first Rx desc list. + * DMAPTPRxDescTab - Pointer on the first PTP Rx desc list. + * RxBuff - Pointer on the first RxBuffer list. + * RxBuffCount - Number of the used Rx desc in the list. + * + * @return none. + */ +void ETH_DMAPTPRxDescChainInit(ETH_DMADESCTypeDef *DMARxDescTab, ETH_DMADESCTypeDef *DMAPTPRxDescTab, + uint8_t *RxBuff, uint32_t RxBuffCount) +{ + uint32_t i = 0; + ETH_DMADESCTypeDef *DMARxDesc; + + DMARxDescToGet = DMARxDescTab; + DMAPTPRxDescToGet = DMAPTPRxDescTab; + + for(i = 0; i < RxBuffCount; i++) + { + DMARxDesc = DMARxDescTab + i; + DMARxDesc->Status = ETH_DMARxDesc_OWN; + DMARxDesc->ControlBufferSize = ETH_DMARxDesc_RCH | (uint32_t)ETH_MAX_PACKET_SIZE; + DMARxDesc->Buffer1Addr = (uint32_t)(&RxBuff[i * ETH_MAX_PACKET_SIZE]); + + if(i < (RxBuffCount - 1)) + { + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab + i + 1); + } + else + { + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab); + } + + (&DMAPTPRxDescTab[i])->Buffer1Addr = DMARxDesc->Buffer1Addr; + (&DMAPTPRxDescTab[i])->Buffer2NextDescAddr = DMARxDesc->Buffer2NextDescAddr; + } + + (&DMAPTPRxDescTab[i - 1])->Status = (uint32_t)DMAPTPRxDescTab; + ETH->DMARDLAR = (uint32_t)DMARxDescTab; +} + +/********************************************************************* + * @fn ETH_HandlePTPTxPkt + * + * @brief Transmits a packet, from application buffer, pointed by ppkt with Time Stamp values. + * + * @param ppkt - pointer to application packet buffer to transmit. + * FrameLength - Tx Packet size. + * PTPTxTab - Pointer on the first PTP Tx table to store Time stamp values. + * + * @return none. + */ +uint32_t ETH_HandlePTPTxPkt(uint8_t *ppkt, uint16_t FrameLength, uint32_t *PTPTxTab) +{ + uint32_t offset = 0, timeout = 0; + + if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (uint32_t)RESET) + { + return ETH_ERROR; + } + + for(offset = 0; offset < FrameLength; offset++) + { + (*(__IO uint8_t *)((DMAPTPTxDescToSet->Buffer1Addr) + offset)) = (*(ppkt + offset)); + } + + DMATxDescToSet->ControlBufferSize = (FrameLength & (uint32_t)0x1FFF); + DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS; + DMATxDescToSet->Status |= ETH_DMATxDesc_OWN; + + if((ETH->DMASR & ETH_DMASR_TBUS) != (uint32_t)RESET) + { + ETH->DMASR = ETH_DMASR_TBUS; + ETH->DMATPDR = 0; + } + + do + { + timeout++; + } while(!(DMATxDescToSet->Status & ETH_DMATxDesc_TTSS) && (timeout < 0xFFFF)); + + if(timeout == PHY_READ_TO) + { + return ETH_ERROR; + } + + DMATxDescToSet->Status &= ~ETH_DMATxDesc_TTSS; + *PTPTxTab++ = DMATxDescToSet->Buffer1Addr; + *PTPTxTab = DMATxDescToSet->Buffer2NextDescAddr; + + if((DMATxDescToSet->Status & ETH_DMATxDesc_TCH) != (uint32_t)RESET) + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)(DMAPTPTxDescToSet->Buffer2NextDescAddr); + if(DMAPTPTxDescToSet->Status != 0) + { + DMAPTPTxDescToSet = (ETH_DMADESCTypeDef *)(DMAPTPTxDescToSet->Status); + } + else + { + DMAPTPTxDescToSet++; + } + } + else + { + if((DMATxDescToSet->Status & ETH_DMATxDesc_TER) != (uint32_t)RESET) + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)(ETH->DMATDLAR); + DMAPTPTxDescToSet = (ETH_DMADESCTypeDef *)(ETH->DMATDLAR); + } + else + { + DMATxDescToSet = (ETH_DMADESCTypeDef *)((uint32_t)DMATxDescToSet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + DMAPTPTxDescToSet = (ETH_DMADESCTypeDef *)((uint32_t)DMAPTPTxDescToSet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + } + } + + return ETH_SUCCESS; +} + +/********************************************************************* + * @fn ETH_HandlePTPRxPkt + * + * @brief Receives a packet and copies it to memory pointed by ppkt with Time Stamp values. + * + * @param ppkt - pointer to application packet receive buffer. + * PTPRxTab - Pointer on the first PTP Rx table to store Time stamp values. + * + * @return ETH_ERROR - if there is error in reception. + * framelength - received packet size if packet reception is correct. + */ +uint32_t ETH_HandlePTPRxPkt(uint8_t *ppkt, uint32_t *PTPRxTab) +{ + uint32_t offset = 0, framelength = 0; + + if((DMARxDescToGet->Status & ETH_DMARxDesc_OWN) != (uint32_t)RESET) + { + return ETH_ERROR; + } + if(((DMARxDescToGet->Status & ETH_DMARxDesc_ES) == (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_LS) != (uint32_t)RESET) && + ((DMARxDescToGet->Status & ETH_DMARxDesc_FS) != (uint32_t)RESET)) + { + framelength = ((DMARxDescToGet->Status & ETH_DMARxDesc_FL) >> ETH_DMARXDESC_FRAME_LENGTHSHIFT) - 4; + + for(offset = 0; offset < framelength; offset++) + { + (*(ppkt + offset)) = (*(__IO uint8_t *)((DMAPTPRxDescToGet->Buffer1Addr) + offset)); + } + } + else + { + framelength = ETH_ERROR; + } + + if((ETH->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET) + { + ETH->DMASR = ETH_DMASR_RBUS; + ETH->DMARPDR = 0; + } + + *PTPRxTab++ = DMARxDescToGet->Buffer1Addr; + *PTPRxTab = DMARxDescToGet->Buffer2NextDescAddr; + DMARxDescToGet->Status |= ETH_DMARxDesc_OWN; + + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RCH) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(DMAPTPRxDescToGet->Buffer2NextDescAddr); + if(DMAPTPRxDescToGet->Status != 0) + { + DMAPTPRxDescToGet = (ETH_DMADESCTypeDef *)(DMAPTPRxDescToGet->Status); + } + else + { + DMAPTPRxDescToGet++; + } + } + else + { + if((DMARxDescToGet->ControlBufferSize & ETH_DMARxDesc_RER) != (uint32_t)RESET) + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)(ETH->DMARDLAR); + } + else + { + DMARxDescToGet = (ETH_DMADESCTypeDef *)((uint32_t)DMARxDescToGet + 0x10 + ((ETH->DMABMR & ETH_DMABMR_DSL) >> 2)); + } + } + + return (framelength); +} + +/********************************************************************* + * @fn RGMII_TXC_Delay + * + * @brief Delay time. + * + * @return none + */ +void RGMII_TXC_Delay(uint8_t clock_polarity, uint8_t delay_time) +{ + if(clock_polarity) + { + ETH->MACCR |= (uint32_t)(1 << 1); + } + else + { + ETH->MACCR &= ~(uint32_t)(1 << 1); + } + if(delay_time <= 7) + { + ETH->MACCR |= (uint32_t)(delay_time << 29); + } +} + diff --git a/Peripheral/src/ch564_gpio.c b/Peripheral/src/ch564_gpio.c new file mode 100644 index 0000000..dfe6982 --- /dev/null +++ b/Peripheral/src/ch564_gpio.c @@ -0,0 +1,409 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_gpio.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the GPIO firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_gpio.h" +#include "ISP564.h" + +/******************************************************************************* + * @fn GPIOA_ModeCfg + * + * @brief GPIOA port pin mode configuration + * + * @param pin - PA0-PA15 + * GPIO_Pin_0 - GPIO_Pin_15 + * mode - + * GPIO_ModeIN_Floating - Floating input/high impedance input + * GPIO_ModeIN_PU - input with pull-up resistor + * GPIO_ModeIN_PD - input with pull-down resistor + * GPIO_ModeOut_OP - Drain output + * GPIO_ModeOut_PP - Push-pull output + * + * @return none + */ + +void GPIOA_ModeCfg(uint32_t pin, GPIOModeTypeDef mode) +{ + + switch (mode) + { + case GPIO_ModeIN_Floating: + R32_PA_PD &= ~pin; + R32_PA_PU &= ~pin; + R32_PA_DIR &= ~pin; + break; + + case GPIO_ModeIN_PU: + R32_PA_PD &= ~pin; + R32_PA_PU |= pin; + R32_PA_DIR &= ~pin; + break; + + case GPIO_ModeIN_PD: + R32_PA_PD |= pin; + R32_PA_PU &= ~pin; + R32_PA_DIR &= ~pin; + break; + + case GPIO_ModeOut_OP: + R32_PA_PD |= pin; + R32_PA_DIR |= pin; + break; + + case GPIO_ModeOut_PP: + R32_PA_DIR |= pin; + R32_PA_PU &= ~pin; + R32_PA_PD &= ~pin; + break; + + default: + break; + } +} + +/******************************************************************************* + * @fn GPIOB_ModeCfg + * + * @brief GPIOB port pin mode configuration + * + * @param pin - PB0-PB15 + * GPIO_Pin_0 - GPIO_Pin_15 + * mode - + * GPIO_ModeIN_Floating - Floating input/high impedance input + * GPIO_ModeIN_PU - input with pull-up resistor + * GPIO_ModeIN_PD - input with pull-down resistor + * GPIO_ModeOut_OP - Drain output + * GPIO_ModeOut_PP - Push-pull output + * + * @return none + */ + +void GPIOB_ModeCfg(uint32_t pin, GPIOModeTypeDef mode) +{ + switch (mode) + { + case GPIO_ModeIN_Floating: + R32_PB_PD &= ~pin; + R32_PB_PU &= ~pin; + R32_PB_DIR &= ~pin; + break; + + case GPIO_ModeIN_PU: + R32_PB_PD &= ~pin; + R32_PB_PU |= pin; + R32_PB_DIR &= ~pin; + break; + + case GPIO_ModeIN_PD: + R32_PB_PD |= pin; + R32_PB_PU &= ~pin; + R32_PB_DIR &= ~pin; + break; + + case GPIO_ModeOut_OP: + R32_PB_PD |= pin; + R32_PB_DIR |= pin; + break; + + case GPIO_ModeOut_PP: + R32_PB_DIR |= pin; + R32_PB_PU &= ~pin; + R32_PB_PD &= ~pin; + break; + + default: + break; + } +} + +/******************************************************************************* + * @fn GPIOD_ModeCfg + * + * @brief GPIOD port pin mode configuration + * + * @param pin - PD0-PD15 + * GPIO_Pin_0 - GPIO_Pin_15 + * mode - + * GPIO_ModeIN_Floating - Floating input/high impedance input + * GPIO_ModeIN_PU - input with pull-up resistor + * GPIO_ModeIN_PD - input with pull-down resistor + * GPIO_ModeOut_OP - Drain output + * GPIO_ModeOut_PP - Push-pull output + * + * @return none + */ + +void GPIOD_ModeCfg(uint32_t pin, GPIOModeTypeDef mode) +{ + switch (mode) + { + case GPIO_ModeIN_Floating: + R32_PD_PD &= ~pin; + R32_PD_PU &= ~pin; + R32_PD_DIR &= ~pin; + break; + + case GPIO_ModeIN_PU: + R32_PD_PD &= ~pin; + R32_PD_PU |= pin; + R32_PD_DIR &= ~pin; + break; + + case GPIO_ModeIN_PD: + R32_PD_PD |= pin; + R32_PD_PU &= ~pin; + R32_PD_DIR &= ~pin; + break; + + case GPIO_ModeOut_OP: + R32_PD_PD |= pin; + R32_PD_DIR |= pin; + break; + + case GPIO_ModeOut_PP: + R32_PD_DIR |= pin; + R32_PD_PU &= ~pin; + R32_PD_PD &= ~pin; + break; + + default: + break; + } +} + +/******************************************************************************* + * @fn GPIOA_ITModeCfg + * + * @brief GPIOA pin interrupt mode configuration + * + * @param pin - PAx + * mode - + * GPIO_ITMode_LowLevel - Low level trigger + * GPIO_ITMode_HighLevel - High level trigger + * GPIO_ITMode_FallEdge - Falling edge trigger + * GPIO_ITMode_RiseEdge - Rising edge trigger + * + * @return none + */ +void GPIOA_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode) +{ + switch (mode) + { + case GPIO_ITMode_FallEdge: + R32_INT_MODE_PA |= pin; + R32_INT_POLAR_PA &= ~pin; + R32_INT_ENABLE_PA |= pin; + break; + + case GPIO_ITMode_RiseEdge: + R32_INT_MODE_PA |= pin; + R32_INT_POLAR_PA |= pin; + R32_INT_ENABLE_PA |= pin; + break; + + case GPIO_ITMode_HighLevel: + R32_INT_MODE_PA &= ~pin; + R32_INT_POLAR_PA |= pin; + R32_INT_ENABLE_PA |= pin; + break; + + case GPIO_ITMode_LowLevel: + R32_INT_MODE_PA &= ~pin; + R32_INT_POLAR_PA &= ~pin; + R32_INT_ENABLE_PA |= pin; + break; + + case GPIO_ITMode_None: + R32_INT_ENABLE_PA |= pin; + R32_INT_ENABLE_PA &= ~pin; + break; + + default: + break; + } + R32_INT_STATUS_PA = pin; +} + +/******************************************************************************* + * @fn GPIOB_ITModeCfg + * + * @brief GPIOB pin interrupt mode configuration + * + * @param pin - PBx + * mode - + * GPIO_ITMode_LowLevel - Low level trigger + * GPIO_ITMode_HighLevel - High level trigger + * GPIO_ITMode_FallEdge - Falling edge trigger + * GPIO_ITMode_RiseEdge - Rising edge trigger + * + * @return none + */ +void GPIOB_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode) +{ + switch (mode) + { + case GPIO_ITMode_FallEdge: + R32_INT_MODE_PB |= pin; + R32_INT_POLAR_PB &= ~pin; + R32_INT_ENABLE_PB |= pin; + break; + + case GPIO_ITMode_RiseEdge: + R32_INT_MODE_PB |= pin; + R32_INT_POLAR_PB |= pin; + R32_INT_ENABLE_PB |= pin; + break; + + case GPIO_ITMode_HighLevel: + R32_INT_MODE_PB &= ~pin; + R32_INT_POLAR_PB |= pin; + R32_INT_ENABLE_PB |= pin; + break; + + case GPIO_ITMode_LowLevel: + R32_INT_MODE_PB &= ~pin; + R32_INT_POLAR_PB &= ~pin; + R32_INT_ENABLE_PB |= pin; + break; + + case GPIO_ITMode_None: + R32_INT_ENABLE_PB |= pin; + R32_INT_ENABLE_PB &= ~pin; + break; + + default: + break; + } + R32_INT_STATUS_PB = pin; +} + +/******************************************************************************* + * @fn GPIOD_ITModeCfg + * + * @brief GPIOD pin interrupt mode configuration + * + * @param pin - PDx + * mode - + * GPIO_ITMode_LowLevel - Low level trigger + * GPIO_ITMode_HighLevel - High level trigger + * GPIO_ITMode_FallEdge - Falling edge trigger + * GPIO_ITMode_RiseEdge - Rising edge trigger + * + * @return none + */ +void GPIOD_ITModeCfg(uint32_t pin, GPIOITModeTpDef mode) +{ + switch (mode) + { + case GPIO_ITMode_FallEdge: + R32_INT_MODE_PD |= pin; + R32_INT_POLAR_PD &= ~pin; + R32_INT_ENABLE_PD |= pin; + break; + + case GPIO_ITMode_RiseEdge: + R32_INT_MODE_PD |= pin; + R32_INT_POLAR_PD |= pin; + R32_INT_ENABLE_PD |= pin; + break; + + case GPIO_ITMode_HighLevel: + R32_INT_MODE_PD &= ~pin; + R32_INT_POLAR_PD |= pin; + R32_INT_ENABLE_PD |= pin; + break; + + case GPIO_ITMode_LowLevel: + R32_INT_MODE_PD &= ~pin; + R32_INT_POLAR_PD &= ~pin; + R32_INT_ENABLE_PD |= pin; + break; + + case GPIO_ITMode_None: + R32_INT_ENABLE_PD |= pin; + R32_INT_ENABLE_PD &= ~pin; + break; + + default: + break; + } + R32_INT_STATUS_PD = pin; +} + +/******************************************************************************* + * @fn GPIO_PinRemapConfig + * + * @brief Remap GPIO function + * + * @param GPIO_Remap - GPIO_Remap_x + * NewSTA - ENABLE + * - DISABLE + * + * @return none + */ +void GPIO_PinRemapConfig(uint32_t GPIO_Remap, FunctionalState NewSTA) +{ + uint32_t tempr = R32_AFIO_PCFR1; + /*GPIO_Remap fomat: + bit[31]: Choose register R32_AFIO_PCFR1(0x0) or R32_AFIO_PCFR2(0x80000000) to be write + bit[24:20]: Position of bits low anchor + bit[19:16]: Size of bits + bit[15:0]: Specific value of remap + */ + if (GPIO_Remap & 0x80000000) + { + tempr = R32_AFIO_PCFR2; + } + /*Clear bits*/ + tempr &= ~((~(0xffffffff << ((GPIO_Remap >> 16) & 0xf))) << ((GPIO_Remap >> 20) & 0x1f)); + /*Write bits*/ + if (NewSTA == ENABLE) + { + tempr |= (GPIO_Remap & (~(0xffffffff << ((GPIO_Remap >> 16) & 0xf)))) << ((GPIO_Remap >> 20) & 0x1f); + } + if (GPIO_Remap & 0x80000000) + R32_AFIO_PCFR2 = tempr; + else + R32_AFIO_PCFR1 = tempr; +} + +/********************************************************************* + * @fn GPIO_IPD_Unused + * + * @brief Configure unused GPIO as input pull-down. + * + * @param none + * + * @return none + */ +void GPIO_IPD_Unused(void) +{ + uint32_t ChipID; + GetCHIPID(&ChipID); + switch (ChipID & 0xffffff0f) + { + case 0x56410508: + GPIOD_ModeCfg(0xFFFFFFFF, GPIO_ModeIN_PD); + GPIOB_ModeCfg(GPIO_Pin_22, GPIO_ModeIN_PD); + GPIOA_ModeCfg(0xFFFFFFFF ^ (GPIO_Pin_7 | GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_8 | GPIO_Pin_11 | GPIO_Pin_17 | + GPIO_Pin_18 | GPIO_Pin_19), + GPIO_ModeIN_PD); + break; + + case 0x56430508: + GPIOD_ModeCfg(0xFFFFFFFF ^ (GPIO_Pin_20), GPIO_ModeIN_PD); + GPIOB_ModeCfg(0xFFFFFFFF ^ (GPIO_Pin_6 | GPIO_Pin_17 | GPIO_Pin_18 | GPIO_Pin_19 | 0xFF00), GPIO_ModeIN_PD); + GPIOA_ModeCfg(0xFFFFFFFF ^ (GPIO_Pin_7 | GPIO_Pin_12 | GPIO_Pin_11), GPIO_ModeIN_PD); + break; + + default: + break; + } +} diff --git a/Peripheral/src/ch564_i2c.c b/Peripheral/src/ch564_i2c.c new file mode 100644 index 0000000..ef07d8e --- /dev/null +++ b/Peripheral/src/ch564_i2c.c @@ -0,0 +1,930 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_i2c.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the I2C firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_i2c.h" + +/* I2C SPE mask */ +#define CTLR1_PE_Set ((uint16_t)0x0001) +#define CTLR1_PE_Reset ((uint16_t)0xFFFE) + +/* I2C START mask */ +#define CTLR1_START_Set ((uint16_t)0x0100) +#define CTLR1_START_Reset ((uint16_t)0xFEFF) + +/* I2C STOP mask */ +#define CTLR1_STOP_Set ((uint16_t)0x0200) +#define CTLR1_STOP_Reset ((uint16_t)0xFDFF) + +/* I2C ACK mask */ +#define CTLR1_ACK_Set ((uint16_t)0x0400) +#define CTLR1_ACK_Reset ((uint16_t)0xFBFF) + +/* I2C ENGC mask */ +#define CTLR1_ENGC_Set ((uint16_t)0x0040) +#define CTLR1_ENGC_Reset ((uint16_t)0xFFBF) + +/* I2C SWRST mask */ +#define CTLR1_SWRST_Set ((uint16_t)0x8000) +#define CTLR1_SWRST_Reset ((uint16_t)0x7FFF) + +/* I2C PEC mask */ +#define CTLR1_PEC_Set ((uint16_t)0x1000) +#define CTLR1_PEC_Reset ((uint16_t)0xEFFF) + +/* I2C ENPEC mask */ +#define CTLR1_ENPEC_Set ((uint16_t)0x0020) +#define CTLR1_ENPEC_Reset ((uint16_t)0xFFDF) + +/* I2C ENARP mask */ +#define CTLR1_ENARP_Set ((uint16_t)0x0010) +#define CTLR1_ENARP_Reset ((uint16_t)0xFFEF) + +/* I2C NOSTRETCH mask */ +#define CTLR1_NOSTRETCH_Set ((uint16_t)0x0080) +#define CTLR1_NOSTRETCH_Reset ((uint16_t)0xFF7F) + +/* I2C registers Masks */ +#define CTLR1_CLEAR_Mask ((uint16_t)0xFBF5) + +/* I2C DMAEN mask */ +#define CTLR2_DMAEN_Set ((uint16_t)0x0800) +#define CTLR2_DMAEN_Reset ((uint16_t)0xF7FF) + +/* I2C LAST mask */ +#define CTLR2_LAST_Set ((uint16_t)0x1000) +#define CTLR2_LAST_Reset ((uint16_t)0xEFFF) + +/* I2C FREQ mask */ +#define CTLR2_FREQ_Reset ((uint16_t)0xFFC0) + +/* I2C ADD0 mask */ +#define OADDR1_ADD0_Set ((uint16_t)0x0001) +#define OADDR1_ADD0_Reset ((uint16_t)0xFFFE) + +/* I2C ENDUAL mask */ +#define OADDR2_ENDUAL_Set ((uint16_t)0x0001) +#define OADDR2_ENDUAL_Reset ((uint16_t)0xFFFE) + +/* I2C ADD2 mask */ +#define OADDR2_ADD2_Reset ((uint16_t)0xFF01) + +/* I2C F/S mask */ +#define CKCFGR_FS_Set ((uint16_t)0x8000) + +/* I2C CCR mask */ +#define CKCFGR_CCR_Set ((uint16_t)0x0FFF) + +/* I2C FLAG mask */ +#define FLAG_Mask ((uint32_t)0x00FFFFFF) + +/* I2C Interrupt Enable mask */ +#define ITEN_Mask ((uint32_t)0x07000000) + +/********************************************************************* + * @fn I2C_DeInit + * + * @brief Deinitializes the I2Cx peripheral registers to their default + * reset values. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * + * @return none + */ +void I2C_DeInit(I2C_Typedef *I2Cx) +{ + if (I2Cx == I2C) + { + R8_SLP_CLK_OFF1 &= ~RB_SLP_CLK_I2C; + } +} + +/********************************************************************* + * @fn I2C_Init + * + * @brief Initializes the I2Cx peripheral according to the specified + * parameters in the I2C_InitStruct. + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_InitStruct - pointer to a I2C_InitTypeDef structure that + * contains the configuration information for the specified I2C peripheral. + * + * @return none + */ +void I2C_Init(I2C_Typedef *I2Cx, I2C_InitTypeDef *I2C_InitStruct) +{ + uint16_t tmpreg = 0, freqrange = 0; + uint16_t result = 0x04; + uint32_t pclk1 = 8000000; + + pclk1 = SystemCoreClock; + tmpreg = I2Cx->CTLR2; + tmpreg &= CTLR2_FREQ_Reset; + + freqrange = (uint16_t)(pclk1 / 1000000); + tmpreg |= freqrange; + I2Cx->CTLR2 = tmpreg; + + I2Cx->CTLR1 &= CTLR1_PE_Reset; + tmpreg = 0; + + if (I2C_InitStruct->I2C_ClockSpeed <= 100000) + { + result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed << 1)); + + if (result < 0x04) + { + result = 0x04; + } + + tmpreg |= result; + } + else + { + if (I2C_InitStruct->I2C_DutyCycle == I2C_DutyCycle_2) + { + result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 3)); + } + else + { + result = (uint16_t)(pclk1 / (I2C_InitStruct->I2C_ClockSpeed * 25)); + result |= I2C_DutyCycle_16_9; + } + + if ((result & CKCFGR_CCR_Set) == 0) + { + result |= (uint16_t)0x0001; + } + + tmpreg |= (uint16_t)(result | CKCFGR_FS_Set); + } + + I2Cx->CKCFGR = tmpreg; + I2Cx->CTLR1 |= CTLR1_PE_Set; + + tmpreg = I2Cx->CTLR1; + tmpreg &= CTLR1_CLEAR_Mask; + tmpreg |= (uint16_t)((uint32_t)I2C_InitStruct->I2C_Mode | I2C_InitStruct->I2C_Ack); + I2Cx->CTLR1 = tmpreg; + + I2Cx->OADDR1 = (I2C_InitStruct->I2C_AcknowledgedAddress | I2C_InitStruct->I2C_OwnAddress1); +} + +/********************************************************************* + * @fn I2C_StructInit + * + * @brief Fills each I2C_InitStruct member with its default value. + * + * @param I2C_InitStruct - pointer to an I2C_InitTypeDef structure which + * will be initialized. + * + * @return none + */ +void I2C_StructInit(I2C_InitTypeDef *I2C_InitStruct) +{ + I2C_InitStruct->I2C_ClockSpeed = 5000; + I2C_InitStruct->I2C_Mode = I2C_Mode_I2C; + I2C_InitStruct->I2C_DutyCycle = I2C_DutyCycle_2; + I2C_InitStruct->I2C_OwnAddress1 = 0; + I2C_InitStruct->I2C_Ack = I2C_Ack_Disable; + I2C_InitStruct->I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; +} + +/********************************************************************* + * @fn I2C_Cmd + * + * @brief Enables or disables the specified I2C peripheral. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_Cmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_PE_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_PE_Reset; + } +} + +/********************************************************************* + * @fn I2C_DMACmd + * + * @brief Enables or disables the specified I2C DMA requests. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_DMACmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR2 |= CTLR2_DMAEN_Set; + } + else + { + I2Cx->CTLR2 &= CTLR2_DMAEN_Reset; + } +} + +/********************************************************************* + * @fn I2C_DMALastTransferCmd + * + * @brief Specifies if the next DMA transfer will be the last one. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_DMALastTransferCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR2 |= CTLR2_LAST_Set; + } + else + { + I2Cx->CTLR2 &= CTLR2_LAST_Reset; + } +} + +/********************************************************************* + * @fn I2C_GenerateSTART + * + * @brief Generates I2Cx communication START condition. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_GenerateSTART(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_START_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_START_Reset; + } +} + +/********************************************************************* + * @fn I2C_GenerateSTOP + * + * @brief Generates I2Cx communication STOP condition. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_GenerateSTOP(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_STOP_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_STOP_Reset; + } +} + +/********************************************************************* + * @fn I2C_AcknowledgeConfig + * + * @brief Enables or disables the specified I2C acknowledge feature. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_AcknowledgeConfig(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_ACK_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_ACK_Reset; + } +} + +/********************************************************************* + * @fn I2C_OwnAddress2Config + * + * @brief Configures the specified I2C own address2. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * Address - specifies the 7bit I2C own address2. + * + * @return none + */ +void I2C_OwnAddress2Config(I2C_Typedef *I2Cx, uint8_t Address) +{ + uint16_t tmpreg = 0; + + tmpreg = I2Cx->OADDR2; + tmpreg &= OADDR2_ADD2_Reset; + tmpreg |= (uint16_t)((uint16_t)Address & (uint16_t)0x00FE); + I2Cx->OADDR2 = tmpreg; +} + +/********************************************************************* + * @fn I2C_DualAddressCmd + * + * @brief Enables or disables the specified I2C dual addressing mode. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_DualAddressCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->OADDR2 |= OADDR2_ENDUAL_Set; + } + else + { + I2Cx->OADDR2 &= OADDR2_ENDUAL_Reset; + } +} + +/********************************************************************* + * @fn I2C_GeneralCallCmd + * + * @brief Enables or disables the specified I2C general call feature. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_GeneralCallCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_ENGC_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_ENGC_Reset; + } +} + +/********************************************************************* + * @fn I2C_ITConfig + * + * @brief Enables or disables the specified I2C interrupts. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_IT - specifies the I2C interrupts sources to be enabled or disabled. + * I2C_IT_BUF - Buffer interrupt mask. + * I2C_IT_EVT - Event interrupt mask. + * I2C_IT_ERR - Error interrupt mask. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_ITConfig(I2C_Typedef *I2Cx, uint16_t I2C_IT, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR2 |= I2C_IT; + } + else + { + I2Cx->CTLR2 &= (uint16_t)~I2C_IT; + } +} + +/********************************************************************* + * @fn I2C_SendData + * + * @brief Sends a data byte through the I2Cx peripheral. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * Data - Byte to be transmitted. + * + * @return none + */ +void I2C_SendData(I2C_Typedef *I2Cx, uint8_t Data) +{ + I2Cx->DATAR = Data; +} + +/********************************************************************* + * @fn I2C_ReceiveData + * + * @brief Returns the most recent received data by the I2Cx peripheral. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * + * @return The value of the received data. + */ +uint8_t I2C_ReceiveData(I2C_Typedef *I2Cx) +{ + return (uint8_t)I2Cx->DATAR; +} + +/********************************************************************* + * @fn I2C_Send7bitAddress + * + * @brief Transmits the address byte to select the slave device. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * Address - specifies the slave address which will be transmitted. + * I2C_Direction - specifies whether the I2C device will be a + * Transmitter or a Receiver. + * I2C_Direction_Transmitter - Transmitter mode. + * I2C_Direction_Receiver - Receiver mode. + * + * @return none + */ +void I2C_Send7bitAddress(I2C_Typedef *I2Cx, uint8_t Address, uint8_t I2C_Direction) +{ + if (I2C_Direction != I2C_Direction_Transmitter) + { + Address |= OADDR1_ADD0_Set; + } + else + { + Address &= OADDR1_ADD0_Reset; + } + + I2Cx->DATAR = Address; +} + +/********************************************************************* + * @fn I2C_ReadRegister + * + * @brief Reads the specified I2C register and returns its value. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_Register - specifies the register to read. + * I2C_Register_CTLR1. + * I2C_Register_CTLR2. + * I2C_Register_OADDR1. + * I2C_Register_OADDR2. + * I2C_Register_DATAR. + * I2C_Register_STAR1. + * I2C_Register_STAR2. + * I2C_Register_CKCFGR. + * + * @return none + */ +uint16_t I2C_ReadRegister(I2C_Typedef *I2Cx, uint8_t I2C_Register) +{ + __IO uint32_t tmp = 0; + + tmp = (uint32_t)I2Cx; + tmp += I2C_Register; + + return (*(__IO uint16_t *)tmp); +} + +/********************************************************************* + * @fn I2C_SoftwareResetCmd + * + * @brief Enables or disables the specified I2C software reset. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_SoftwareResetCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_SWRST_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_SWRST_Reset; + } +} + +/********************************************************************* + * @fn I2C_NACKPositionConfig + * + * @brief Selects the specified I2C NACK position in master receiver mode. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_NACKPosition - specifies the NACK position. + * I2C_NACKPosition_Next - indicates that the next byte will be + * the last received byte. + * I2C_NACKPosition_Current - indicates that current byte is the + * last received byte. + * + * @return none + */ +void I2C_NACKPositionConfig(I2C_Typedef *I2Cx, uint16_t I2C_NACKPosition) +{ + if (I2C_NACKPosition == I2C_NACKPosition_Next) + { + I2Cx->CTLR1 |= I2C_NACKPosition_Next; + } + else + { + I2Cx->CTLR1 &= I2C_NACKPosition_Current; + } +} + +/********************************************************************* + * @fn I2C_TransmitPEC + * + * @brief Enables or disables the specified I2C PEC transfer. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_TransmitPEC(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_PEC_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_PEC_Reset; + } +} + +/********************************************************************* + * @fn I2C_PECPositionConfig + * + * @brief Selects the specified I2C PEC position. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_PECPosition - specifies the PEC position. + * I2C_PECPosition_Next - indicates that the next byte is PEC. + * I2C_PECPosition_Current - indicates that current byte is PEC. + * + * @return none + */ +void I2C_PECPositionConfig(I2C_Typedef *I2Cx, uint16_t I2C_PECPosition) +{ + if (I2C_PECPosition == I2C_PECPosition_Next) + { + I2Cx->CTLR1 |= I2C_PECPosition_Next; + } + else + { + I2Cx->CTLR1 &= I2C_PECPosition_Current; + } +} + +/********************************************************************* + * @fn I2C_CalculatePEC + * + * @brief Enables or disables the PEC value calculation of the transferred bytes. + * + * @param I2Cx- where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_CalculatePEC(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_ENPEC_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_ENPEC_Reset; + } +} + +/********************************************************************* + * @fn I2C_GetPEC + * + * @brief Returns the PEC value for the specified I2C. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * + * @return The PEC value. + */ +uint8_t I2C_GetPEC(I2C_Typedef *I2Cx) +{ + return ((I2Cx->STAR2) >> 8); +} + +/********************************************************************* + * @fn I2C_ARPCmd + * + * @brief Enables or disables the specified I2C ARP. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return The PEC value. + */ +void I2C_ARPCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState != DISABLE) + { + I2Cx->CTLR1 |= CTLR1_ENARP_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_ENARP_Reset; + } +} + +/********************************************************************* + * @fn I2C_StretchClockCmd + * + * @brief Enables or disables the specified I2C Clock stretching. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * NewState - ENABLE or DISABLE. + * + * @return none + */ +void I2C_StretchClockCmd(I2C_Typedef *I2Cx, FunctionalState NewState) +{ + if (NewState == DISABLE) + { + I2Cx->CTLR1 |= CTLR1_NOSTRETCH_Set; + } + else + { + I2Cx->CTLR1 &= CTLR1_NOSTRETCH_Reset; + } +} + +/********************************************************************* + * @fn I2C_FastModeDutyCycleConfig + * + * @brief Selects the specified I2C fast mode duty cycle. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_DutyCycle - specifies the fast mode duty cycle. + * I2C_DutyCycle_2 - I2C fast mode Tlow/Thigh = 2. + * I2C_DutyCycle_16_9 - I2C fast mode Tlow/Thigh = 16/9. + * + * @return none + */ +void I2C_FastModeDutyCycleConfig(I2C_Typedef *I2Cx, uint16_t I2C_DutyCycle) +{ + if (I2C_DutyCycle != I2C_DutyCycle_16_9) + { + I2Cx->CKCFGR &= I2C_DutyCycle_2; + } + else + { + I2Cx->CKCFGR |= I2C_DutyCycle_16_9; + } +} + +/********************************************************************* + * @fn I2C_CheckEvent + * + * @brief Checks whether the last I2Cx Event is equal to the one passed + * as parameter. + * + * @param I2Cx- where x can be 1 to select the I2C peripheral. + * I2C_EVENT: specifies the event to be checked. + * I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED - EV1. + * I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED - EV1. + * I2C_EVENT_SLAVE_TRANSMITTER_SECONDADDRESS_MATCHED - EV1. + * I2C_EVENT_SLAVE_RECEIVER_SECONDADDRESS_MATCHED - EV1. + * I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED - EV1. + * I2C_EVENT_SLAVE_BYTE_RECEIVED - EV2. + * (I2C_EVENT_SLAVE_BYTE_RECEIVED | I2C_FLAG_DUALF) - EV2. + * (I2C_EVENT_SLAVE_BYTE_RECEIVED | I2C_FLAG_GENCALL) - EV2. + * I2C_EVENT_SLAVE_BYTE_TRANSMITTED - EV3. + * (I2C_EVENT_SLAVE_BYTE_TRANSMITTED | I2C_FLAG_DUALF) - EV3. + * (I2C_EVENT_SLAVE_BYTE_TRANSMITTED | I2C_FLAG_GENCALL) - EV3. + * I2C_EVENT_SLAVE_ACK_FAILURE - EV3_2. + * I2C_EVENT_SLAVE_STOP_DETECTED - EV4. + * I2C_EVENT_MASTER_MODE_SELECT - EV5. + * I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED - EV6. + * I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED - EV6. + * I2C_EVENT_MASTER_BYTE_RECEIVED - EV7. + * I2C_EVENT_MASTER_BYTE_TRANSMITTING - EV8. + * I2C_EVENT_MASTER_BYTE_TRANSMITTED - EV8_2. + * I2C_EVENT_MASTER_MODE_ADDRESS10 - EV9. + * + * @return none + */ +ErrorStatus I2C_CheckEvent(I2C_Typedef *I2Cx, uint32_t I2C_EVENT) +{ + uint32_t lastevent = 0; + uint32_t flag1 = 0, flag2 = 0; + ErrorStatus status = NoREADY; + + flag1 = I2Cx->STAR1; + flag2 = I2Cx->STAR2; + flag2 = flag2 << 16; + + lastevent = (flag1 | flag2) & FLAG_Mask; + + if ((lastevent & I2C_EVENT) == I2C_EVENT) + { + status = READY; + } + else + { + status = NoREADY; + } + + return status; +} + +/********************************************************************* + * @fn I2C_GetLastEvent + * + * @brief Returns the last I2Cx Event. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * + * @return none + */ +uint32_t I2C_GetLastEvent(I2C_Typedef *I2Cx) +{ + uint32_t lastevent = 0; + uint32_t flag1 = 0, flag2 = 0; + + flag1 = I2Cx->STAR1; + flag2 = I2Cx->STAR2; + flag2 = flag2 << 16; + lastevent = (flag1 | flag2) & FLAG_Mask; + + return lastevent; +} + +/********************************************************************* + * @fn I2C_GetFlagStatus + * + * @brief Checks whether the last I2Cx Event is equal to the one passed + * as parameter. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_FLAG - specifies the flag to check. + * I2C_FLAG_DUALF - Dual flag (Slave mode). + * I2C_FLAG_GENCALL - General call header flag (Slave mode). + * I2C_FLAG_TRA - Transmitter/Receiver flag. + * I2C_FLAG_BUSY - Bus busy flag. + * I2C_FLAG_MSL - Master/Slave flag. + * I2C_FLAG_PECERR - PEC error in reception flag. + * I2C_FLAG_OVR - Overrun/Underrun flag (Slave mode). + * I2C_FLAG_AF - Acknowledge failure flag. + * I2C_FLAG_ARLO - Arbitration lost flag (Master mode). + * I2C_FLAG_BERR - Bus error flag. + * I2C_FLAG_TXE - Data register empty flag (Transmitter). + * I2C_FLAG_RXNE- Data register not empty (Receiver) flag. + * I2C_FLAG_STOPF - Stop detection flag (Slave mode). + * I2C_FLAG_ADD10 - 10-bit header sent flag (Master mode). + * I2C_FLAG_BTF - Byte transfer finished flag. + * I2C_FLAG_ADDR - Address sent flag (Master mode) "ADSL" + * Address matched flag (Slave mode)"ENDA". + * I2C_FLAG_SB - Start bit flag (Master mode). + * + * @return none + */ +FlagStatus I2C_GetFlagStatus(I2C_Typedef *I2Cx, uint32_t I2C_FLAG) +{ + FlagStatus bitstatus = RESET; + __IO uint32_t i2creg = 0, i2cxbase = 0; + + i2cxbase = (uint32_t)I2Cx; + i2creg = I2C_FLAG >> 28; + I2C_FLAG &= FLAG_Mask; + + if (i2creg != 0) + { + i2cxbase += 0x14; + } + else + { + I2C_FLAG = (uint32_t)(I2C_FLAG >> 16); + i2cxbase += 0x18; + } + + if (((*(__IO uint32_t *)i2cxbase) & I2C_FLAG) != (uint32_t)RESET) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn I2C_ClearFlag + * + * @brief Clears the I2Cx's pending flags. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_FLAG - specifies the flag to clear. + * I2C_FLAG_SMBALERT - SMBus Alert flag. + * I2C_FLAG_TIMEOUT - Timeout or Tlow error flag. + * I2C_FLAG_PECERR - PEC error in reception flag. + * I2C_FLAG_OVR - Overrun/Underrun flag (Slave mode). + * I2C_FLAG_AF - Acknowledge failure flag. + * I2C_FLAG_ARLO - Arbitration lost flag (Master mode). + * I2C_FLAG_BERR - Bus error flag. + * + * @return none + */ +void I2C_ClearFlag(I2C_Typedef *I2Cx, uint32_t I2C_FLAG) +{ + uint32_t flagpos = 0; + + flagpos = I2C_FLAG & FLAG_Mask; + I2Cx->STAR1 = (uint16_t)~flagpos; +} + +/********************************************************************* + * @fn I2C_GetITStatus + * + * @brief Checks whether the specified I2C interrupt has occurred or not. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * II2C_IT - specifies the interrupt source to check. + * I2C_IT_PECERR - PEC error in reception flag. + * I2C_IT_OVR - Overrun/Underrun flag (Slave mode). + * I2C_IT_AF - Acknowledge failure flag. + * I2C_IT_ARLO - Arbitration lost flag (Master mode). + * I2C_IT_BERR - Bus error flag. + * I2C_IT_TXE - Data register empty flag (Transmitter). + * I2C_IT_RXNE - Data register not empty (Receiver) flag. + * I2C_IT_STOPF - Stop detection flag (Slave mode). + * I2C_IT_ADD10 - 10-bit header sent flag (Master mode). + * I2C_IT_BTF - Byte transfer finished flag. + * I2C_IT_ADDR - Address sent flag (Master mode) "ADSL" Address matched + * flag (Slave mode)"ENDAD". + * I2C_IT_SB - Start bit flag (Master mode). + * + * @return none + */ +ITStatus I2C_GetITStatus(I2C_Typedef *I2Cx, uint32_t I2C_IT) +{ + ITStatus bitstatus = RESET; + uint32_t enablestatus = 0; + + enablestatus = (uint32_t)(((I2C_IT & ITEN_Mask) >> 16) & (I2Cx->CTLR2)); + I2C_IT &= FLAG_Mask; + + if (((I2Cx->STAR1 & I2C_IT) != (uint32_t)RESET) && enablestatus) + { + bitstatus = SET; + } + else + { + bitstatus = RESET; + } + + return bitstatus; +} + +/********************************************************************* + * @fn I2C_ClearITPendingBit + * + * @brief Clears the I2Cx interrupt pending bits. + * + * @param I2Cx - where x can be 1 to select the I2C peripheral. + * I2C_IT - specifies the interrupt pending bit to clear. + * I2C_IT_PECERR - PEC error in reception interrupt. + * I2C_IT_OVR - Overrun/Underrun interrupt (Slave mode). + * I2C_IT_AF - Acknowledge failure interrupt. + * I2C_IT_ARLO - Arbitration lost interrupt (Master mode). + * I2C_IT_BERR - Bus error interrupt. + * + * @return none + */ +void I2C_ClearITPendingBit(I2C_Typedef *I2Cx, uint32_t I2C_IT) +{ + uint32_t flagpos = 0; + + flagpos = I2C_IT & FLAG_Mask; + I2Cx->STAR1 = (uint16_t)~flagpos; +} diff --git a/Peripheral/src/ch564_pwr.c b/Peripheral/src/ch564_pwr.c new file mode 100644 index 0000000..c8fa397 --- /dev/null +++ b/Peripheral/src/ch564_pwr.c @@ -0,0 +1,45 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_pwr.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the PWR firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_pwr.h" + +/******************************************************************************* + * @fn LowPower_Idle + * + * @brief Low power consumption - Idle mode + * + * @return none + */ +void PWR_Sleep(uint8_t PWR_STOPEntry) +{ + PFIC->SCTLR &= ~(1 << 2); // Set the SleepDeep field of the core PFIC SCTLR register to 0 + if (PWR_STOPEntry == PWR_STOPEntry_WFE){ + __WFE(); // Execute __WFE() after setting the wake-up condition + } + else + __WFI(); // Execute __WFI() after setting the wake-up condition +} + +/******************************************************************************* + * @fn LowPower_Halt + * + * @brief Low power consumption - Halt mode + * + * @return none + */ +void PWR_DeepSleep(uint8_t PWR_STOPEntry) +{ + PFIC->SCTLR |= 1 << 2; // Set the SleepDeep field of the core PFIC SCTLR register to 1 + if (PWR_STOPEntry == PWR_STOPEntry_WFE) + __WFE(); // Execute __WFE() after setting the wake-up condition + else + __WFI(); // Execute __WFI() after setting the wake-up condition +} diff --git a/Peripheral/src/ch564_rcc.c b/Peripheral/src/ch564_rcc.c new file mode 100644 index 0000000..9cfd54b --- /dev/null +++ b/Peripheral/src/ch564_rcc.c @@ -0,0 +1,142 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_rcc.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the RCC firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_rcc.h" + +/********************************************************************* + * @fn RCC_SetGlobleMem + * + * @brief Config the different memory assignment + * + * @param Cfg - Three choice of memory assignment + * Code16k_Data128k - assign 16k memory for code 128k memory for data + * Code48k_Data96k - assign 48k memory for code 96k memory for data + * Code80k_Data64k - assign 80k memory for code 64k memory for data + * + * @return none + */ +void RCC_SetGlobalMemCFG(GlobMem_Cfg Cfg) +{ + RCC_UNLOCK_SAFE_ACCESS(); + R8_GLOB_MEM_CFG = Cfg; + RCC_LOCK_SAFE_ACCESS(); +} + +/********************************************************************* + * @fn RCC_LockPort + * + * @brief Choose a port and decide whether lock or not + * + * @param globport - choose port + * - RB_GLOB_LOCK_PA + * - RB_GLOB_LOCK_PB + * - RB_GLOB_LOCK_PD + * NewSTA - Enable or disable + * - ENABLE + * - DISABLE + * @return none + */ +void RCC_LockPort(uint8_t globport, FunctionalState NewSTA) +{ + uint8_t temp = R8_GLOB_LOCK_PORT; + NewSTA == ENABLE ? (temp |= globport) : (temp &= ~globport); + R8_GLOB_LOCK_PORT = 0x3f & temp; +} + +/********************************************************************* + * @fn RCC_GlobleRstCFG + * + * @brief Choose Reset function + * + * @param globrst - choose port + * - RB_GLOB_FORCE_RST + * - RB_GLOB_WDOG_EN + * NewSTA - Enable or disable + * - ENABLE + * - DISABLE + * @return none + */ +void RCC_GlobleRstCFG(uint8_t globrst, FunctionalState NewSTA) +{ + uint8_t temp = R8_GLOB_RST_CFG; + NewSTA == ENABLE ? (temp = 0x40 | globrst) : (temp = (0x0F & (~globrst))|0x40); + RCC_UNLOCK_SAFE_ACCESS(); + R8_GLOB_RST_CFG = temp; + RCC_LOCK_SAFE_ACCESS(); +} + +/********************************************************************* + * @fn RCC_SlpClkOff + * + * @brief Choose peripherals' clock to be on or off + * + * @param reg - register pointer to write + * - R8_SLP_CLK_OFF0 + * - R8_SLP_CLK_OFF1 + * - R8_SLP_CTRL_PLL + * slpclk - choose periph clock + * - RB_SLP_CLK_TMR0 + * - RB_SLP_CLK_TMR1 + * - RB_SLP_CLK_TMR2 + * - RB_SLP_CLK_TMR3 + * - RB_SLP_CLK_SPI0 + * - RB_SLP_CLK_SPI1 + * - RB_SLP_CLK_UART0 + * - RB_SLP_CLK_UART1 + * + * - RB_SLP_CLK_UTMI + * - RB_SLP_CLK_I2C + * - RB_SLP_CLK_UDP + * - RB_SLP_CLK_ADC + * - RB_SLP_CLK_GPIO + * - RB_SLP_CLK_USB + * - RB_SLP_CLK_ETH + * + * - RB_SLP_CTRL_PLL_UART2 + * - RB_SLP_CTRL_PLL_UART3 + * NewSTA - Enable or disable + * - ENABLE + * - DISABLE + * @return none + */ +void RCC_SlpClkOff(volatile uint8_t *reg, uint8_t slpclk, FunctionalState NewSTA) +{ + if (reg != &R8_SLP_CLK_OFF0 && reg != &R8_SLP_CLK_OFF1 && reg != &R8_SLP_CTRL_PLL) + return; + RCC_UNLOCK_SAFE_ACCESS(); + NewSTA == ENABLE ? (*reg |= slpclk) : (*reg &= ~slpclk); + RCC_LOCK_SAFE_ACCESS(); +} + +/********************************************************************* + * @fn RCC_SlpWakeCtrl + * + * @brief Choose Reset function + * + * @param slpwake - choose periph to wake the device + * - RB_SLP_PA_WAKE + * - RB_SLP_PB_WAKE + * - RB_SLP_PD_WAKE + * - RB_SLP_USB_WAKE + * - RB_SLP_AP_WAK_USB + * - RB_SLP_WOL_WAKE + * - RB_SLP_ETH_PWR_DN + * NewSTA - Enable or disable + * - ENABLE + * - DISABLE + * @return none + */ +void RCC_SlpWakeCtrl(uint8_t slpwake, FunctionalState NewSTA) +{ + RCC_UNLOCK_SAFE_ACCESS(); + NewSTA == ENABLE ? (R8_SLP_WAKE_CTRL |= slpwake) : (R8_SLP_WAKE_CTRL &= ~slpwake); + RCC_LOCK_SAFE_ACCESS(); +} diff --git a/Peripheral/src/ch564_slv.c b/Peripheral/src/ch564_slv.c new file mode 100644 index 0000000..c3d266a --- /dev/null +++ b/Peripheral/src/ch564_slv.c @@ -0,0 +1,129 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_slv.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the SLV firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_slv.h" + +/********************************************************************** + * @fn SLV_Read + * @brief The function SLV_Read reads data from a slave device with a specified data size and timeout. + * + * @param dataAddress A pointer to the memory location where the received data will be stored. + * dataSize The dataSize parameter represents the number of bytes to be read from the SLV + * (slave) device. + * timeout The "timeout" parameter is the maximum amount of time (in milliseconds) that the + * function will wait for data to be received before returning with a timeout error. + * + * @return a value of type SLV_STA. + * --slv_data data read right now is a data + * --slv_cmd data read right now is a command + * --slv_timeout read data timeout + */ +SLV_STA SLV_Read(uint8_t *dataAddress, uint16_t dataSize, uint16_t timeout) +{ + SLV_STA SLV_TYPE; + + SLV_TYPE = slv_data; + + while (dataSize--) + { + uint16_t t = timeout; + while (t--) + { + if (SLV_GET_IF(RB_IF_SLV_WR)) + { + if (SLV_GET_IF(RB_IF_SLV_CMD)) + SLV_TYPE = slv_cmd; + else + SLV_TYPE = slv_data; + } + + *(dataAddress++) = SLV_GET_DATA(); + } + if (t == 0) + { + SLV_TYPE = slv_timeout; + break; + } + } + + return SLV_TYPE; +} + +/********************************************************************** + * @fn SLV_SendDATA + * + * @brief The function SLV_SendDATA sends data over a communication interface and returns the status of the + * operation. + * + * @param data The "data" parameter is a pointer to an array of uint8_t (unsigned 8-bit integer) + * values. It represents the data that needs to be sent. + * datasize The parameter "datasize" is the size of the data array that is being sent. It + * represents the number of elements in the array. + * + * @return ErrorStatus value. If the timeout value reaches 0 before the condition "R8_INT_FLAG_SLV & + * RB_IF_SLV_RD" is true, the function will return NoREADY. Otherwise, it will return READY. + */ +ErrorStatus SLV_SendDATA(uint8_t *data, uint16_t datasize) +{ + uint16_t timeout; + + while (datasize--) + { + timeout = 100; + SLV_SEND_DATA(*(data++)); + while (timeout--) + { + if (SLV_GET_IF(RB_IF_SLV_RD)) + { + break; + } + } + if (timeout == 0) + { + return NoREADY; + } + } + return READY; +} + +/********************************************************************** + * @fn SLV_SendSTA + * + * @brief The function SLV_SendSTA sends a series of data bytes to a slave device and returns a status + * indicating if the operation was successful or not. + * + * @param sta A pointer to an array of uint8_t values that represent the data to be sent. + * datasize datasize is the number of bytes in the sta array that need to be sent. + * + * @return ErrorStatus. + */ +ErrorStatus SLV_SendSTA(uint8_t *sta, uint16_t datasize) +{ + uint16_t timeout; + + while (datasize--) + { + timeout = 100; + SLV_SEND_STA(*(sta++)); + while (timeout--) + { + if (SLV_GET_IF(RB_IF_SLV_RD)) + { + break; + } + } + if (timeout == 0) + { + return NoREADY; + } + } + return READY; +} diff --git a/Peripheral/src/ch564_spi.c b/Peripheral/src/ch564_spi.c new file mode 100644 index 0000000..2664f1a --- /dev/null +++ b/Peripheral/src/ch564_spi.c @@ -0,0 +1,678 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_spi.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the SPI firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_spi.h" +#include "debug.h" + +uint32_t spi_comm_tick = 0; +#define SPICOMM_TIMEOUT 10 + +static void delay() +{ + for (uint16_t i = 0; i < (SystemCoreClock / 1000000) * 1000; i++); +} + +/******************************************************************************* + * @fn SPI0_MasterDefInit + * + * @brief Host mode default initialization + * + * @return none + */ +void SPI0_MasterInit(uint32_t clockRate) +{ + SPI0_MODE_CFG(RB_SPI_MODE_SLAVE, DISABLE); + SPI0_MODE_CFG(RB_SPI_MOSI_OE | RB_SPI_SCK_OE | RB_SPI_ALL_CLEAR | RB_SPI_FIFO_DIR, ENABLE); + SPI0_MODE_CFG(RB_SPI_MISO_OE | RB_SPI_ALL_CLEAR, DISABLE); + SPI0_SET_CLOCK_DIV((SystemCoreClock / clockRate) < 2 ? (2) : (SystemCoreClock / clockRate)); + SPI0_SET_DMA_MODE(0xff, DISABLE); +} + +/******************************************************************************* + * @fn SPI0_DataMode + * + * @brief Set data flow mode + * + * @param mode - data flow mode + * + * @return none + */ +void SPI0_DataMode(ModeBitOrderTypeDef mode) +{ + switch (mode) + { + case Mode0_HighBitINFront: // Mode 0, high bit first + SPI0_MODE_CFG(RB_SPI_MST_SCK_MOD, DISABLE); + break; + case Mode3_HighBitINFront: // Mode 3, high bit first + SPI0_MODE_CFG(RB_SPI_MST_SCK_MOD, ENABLE); + break; + default: + break; + } +} + +/******************************************************************************* + * @fn SPI0_MasterSendByte + * + * @brief Send a single byte (buffer) + * + * @param data - send bytes + * + * @return none + */ +void SPI0_MasterSendByte(uint8_t data) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); + SPI0_SET_TOTAL_CNT(1); + SPI0_SET_FIFO(data); + spi_comm_tick = SysTick_100us; + while (SPI0_GET_TOTAL_CNT() != 0) + { + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } +} + +/******************************************************************************* + * @fn SPI0_MasterRecvByte + * + * @brief Receive a single byte (buffer) + * + * @return bytes received + */ +uint8_t SPI0_MasterRecvByte(void) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); + SPI0_SET_TOTAL_CNT(1); + SPI0_SET_BUFFER(0xff); + spi_comm_tick = SysTick_100us; + while (!SPI0_GET_FIFO_CNT()) + { + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } + return (SPI0_GET_FIFO()); +} + +/******************************************************************************* + * @fn SPI0_MasterTrans + * + * @brief Continuously send multiple bytes using FIFO + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + */ +void SPI0_MasterTrans(uint8_t *pbuf, uint16_t len) +{ + uint16_t sendlen; + + sendlen = len; + SPI0_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI0_ClearITFlag(RB_SPI_IF_CNT_END); + spi_comm_tick = SysTick_100us; + while (sendlen) + { + if (SPI0_GET_FIFO_CNT() < SPI0_FIFO_SIZE) + { + SPI0_SET_FIFO(*pbuf); + pbuf++; + sendlen--; + } + + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } + spi_comm_tick = SysTick_100us; + while (SPI0_GET_TOTAL_CNT() != 0) // Wait for all the data in the FIFO to be sent + { + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } +} + +/******************************************************************************* + * @fn SPI0_MasterRecv + * + * @brief Receive multiple bytes continuously using FIFO + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + **/ +void SPI0_MasterRecv(uint8_t *pbuf, uint16_t len) +{ + uint16_t readlen; + + readlen = len; + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set data direction to input + SPI0_SET_TOTAL_CNT(len); // Set the length of the data to be received, the FIFO direction will start the + // transmission if the input length is not 0 + R8_SPI0_INT_FLAG = RB_SPI_IF_CNT_END; + SPI0_SET_BUFFER(0xff); + + spi_comm_tick = SysTick_100us; + while (readlen) + { + if (SPI0_GET_FIFO_CNT()) + { + *pbuf = SPI0_GET_FIFO(); + SPI0_SET_BUFFER(0xff); + pbuf++; + readlen--; + } + + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } +} + +/******************************************************************************* + * @fn SPI0_MasterTransRecv + * + * @brief Continuously send/receive multiple bytes + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + */ +void SPI0_MasterTransRecv(uint8_t *ptbuf, uint8_t *prbuf, uint16_t len) +{ + uint16_t sendlen; + + sendlen = len; + SPI0_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI0_ClearITFlag(RB_SPI_IF_CNT_END); + + spi_comm_tick = SysTick_100us; + while (sendlen) + { + if (SPI0_GET_FIFO_CNT() == 0) + { + SPI0_SET_FIFO(*ptbuf); + while (SPI0_GET_FIFO_CNT() != 0); + ptbuf++; + *prbuf = SPI0_GET_BUFFER(); + prbuf++; + sendlen--; + } + + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } + +} + +/******************************************************************************* + * @fn SPI0_DMATrans + * + * @brief Continuously send data in DMA mode + * + * @param pbuf: The starting address of the data to be sent + * + * @return none + */ +void SPI0_DMATrans(uint8_t *pbuf, uint32_t len) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); + + SPI0_SET_DMA_RANGE(pbuf, pbuf + len); + SPI0_SET_TOTAL_CNT(len); + SPI0_SET_DMA_MODE(RB_SPI_DMA_ENABLE, ENABLE); + spi_comm_tick = SysTick_100us; + while (SPI0_GET_TOTAL_CNT()) + { + if(SysTick_100us - spi_comm_tick >= SPICOMM_TIMEOUT) break; + } + SPI0_SET_DMA_MODE(RB_SPI_DMA_ENABLE, DISABLE); + + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); +} + +/******************************************************************************* + * @fn SPI0_DMARecv + * + * @brief Receive data continuously in DMA mode + * + * @param pbuf: The starting address for storing the data to be received + * + * @return none + **/ +void SPI0_DMARecv(uint8_t *pbuf, uint32_t len) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); + SPI0_SET_DMA_RANGE(pbuf, pbuf + len); + SPI0_SET_TOTAL_CNT(len); + SPI0_SET_DMA_MODE(RB_SPI_DMA_ENABLE, ENABLE); + spi_comm_tick = SysTick_100us; + while (SPI0_GET_TOTAL_CNT()) + { + if(SysTick_100us - spi_comm_tick >= 1000) break; + } + SPI0_SET_DMA_MODE(RB_SPI_DMA_ENABLE, DISABLE); +} + +/******************************************************************************* + * @fn SPI0_SlaveInit + * + * @brief Device mode default initialization + * + * @return none + */ +void SPI0_SlaveInit(uint32_t clockRate) +{ + SPI0_MODE_CFG(RB_SPI_MODE_SLAVE | RB_SPI_ALL_CLEAR, ENABLE); + SPI0_MODE_CFG(RB_SPI_MOSI_OE | RB_SPI_ALL_CLEAR | RB_SPI_SCK_OE, DISABLE); + SPI0_MODE_CFG(RB_SPI_MISO_OE, ENABLE); + + SPI0_SET_DMA_MODE(0xff, DISABLE); +} + +/******************************************************************************* + * @fn SPI0_SlaveRecvByte + * + * @brief Slave mode, receive one byte of data + * + * @return received data + */ +uint8_t SPI0_SlaveRecvByte(void) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set to input mode, receive data + while (!SPI0_GET_FIFO_CNT()); + return SPI0_GET_FIFO(); +} + +/******************************************************************************* + * @fn SPI0_SlaveRecvByte + * + * @brief Slave mode, send one byte of data + * + * @param data: data will be sent + * + * @return received data + **/ +void SPI0_SlaveSendByte(uint8_t data) +{ + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set to output mode, send data + SPI0_SET_FIFO(data); + SPI0_SET_TOTAL_CNT(1); + while (SPI0_GET_FIFO_CNT()); +} + +/******************************************************************************* + * @fn SPI0_SlaveRecv + * + * @brief Slave mode, receive multi-byte data + * + * @param pbuf: Receive data storage starting address + * + * @return 0/1 0 means receive failed,1 means receive success. + **/ +uint8_t SPI0_SlaveRecv(uint8_t *pbuf, uint16_t len, uint16_t timeouts) +{ + uint16_t revlen; + + revlen = len; + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set to input mode, receive data + SPI0_SET_TOTAL_CNT(revlen); // Assign a value to the SPI send and receive data total length register + while (revlen && timeouts) + { + if (!(timeouts & SPI_MAX_DELAY)) + { + delay(); + timeouts--; + } + if (SPI0_GET_FIFO_CNT()) // Byte count in the current FIFO + { + *pbuf = SPI0_GET_FIFO(); + pbuf++; + revlen--; + } + } + if (!revlen) + { + return 0; + } + else + { + return 1; + } +} + +/******************************************************************************* + * @fn SPI0_SlaveTrans + * + * @brief Slave mode, send multi-byte data + * + * @param pbuf: The first address of the data content to be sent + * + * @return 0/1 0 means receive failed,1 means receive success. + */ +uint8_t SPI0_SlaveTrans(uint8_t *pbuf, uint16_t len, uint16_t timeouts) +{ + uint16_t sendlen; + + sendlen = len; + SPI0_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI0_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + while (sendlen) + { + if (!(timeouts & SPI_MAX_DELAY)) + { + delay(); + timeouts--; + } + if (SPI0_GET_FIFO_CNT() < SPI0_FIFO_SIZE) // Compare the byte count size in the current FIFO + { + SPI0_SET_FIFO(*pbuf); + pbuf++; + sendlen--; + } + } + if (!sendlen) + { + return 0; + } + else + { + return 1; + } +} + +/******************************************************************************* + * @fn SPI1_MasterDefInit + * + * @brief Host mode default initialization + * + * @return none + */ +void SPI1_MasterInit(uint32_t clockRate) +{ + SPI1_MODE_CFG(RB_SPI_MODE_SLAVE, DISABLE); + SPI1_MODE_CFG(RB_SPI_MOSI_OE | RB_SPI_SCK_OE | RB_SPI_ALL_CLEAR, ENABLE); + SPI1_MODE_CFG(RB_SPI_MISO_OE | RB_SPI_ALL_CLEAR, DISABLE); + SPI1_SET_CLOCK_DIV((SystemCoreClock / clockRate) < 2 ? (2) : (SystemCoreClock / clockRate)); + SPI1_SET_DMA_MODE(0xff, DISABLE); +} + +/******************************************************************************* + * @fn SPI1_DataMode + * + * @brief Set data flow mode + * + * @param mode - data flow mode + * + * @return none + */ +void SPI1_DataMode(ModeBitOrderTypeDef mode) +{ + switch (mode) + { + case Mode0_HighBitINFront: // Mode 0, high bit first + SPI1_MODE_CFG(RB_SPI_MST_SCK_MOD, DISABLE); + break; + case Mode3_HighBitINFront: // Mode 3, high bit first + SPI1_MODE_CFG(RB_SPI_MST_SCK_MOD, ENABLE); + break; + default: + break; + } +} + +/******************************************************************************* + * @fn SPI1_MasterSendByte + * + * @brief Send a single byte (buffer) + * + * @param data - send bytes + * + * @return none + */ +void SPI1_MasterSendByte(uint8_t data) +{ + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); + SPI1_SET_TOTAL_CNT(1); + SPI1_SET_FIFO(data); + + while (SPI1_GET_TOTAL_CNT() != 0); +} + +/******************************************************************************* + * @fn SPI1_MasterRecvByte + * + * @brief Receive a single byte (buffer) + * + * @return bytes received + */ +uint8_t SPI1_MasterRecvByte(void) +{ + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); + SPI1_SET_TOTAL_CNT(1); + SPI1_SET_FIFO(0xff); + while (!SPI1_GET_FIFO_CNT()); + return (SPI1_GET_FIFO()); +} + +/******************************************************************************* + * @fn SPI1_MasterTrans + * + * @brief Continuously send multiple bytes using FIFO + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + */ +void SPI1_MasterTrans(uint8_t *pbuf, uint16_t len) +{ + uint16_t sendlen; + + sendlen = len; + SPI1_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI1_ClearITFlag(RB_SPI_IF_CNT_END); + while (sendlen) + { + if (SPI1_GET_FIFO_CNT() < SPI1_FIFO_SIZE) + { + SPI1_SET_FIFO(*pbuf); + pbuf++; + sendlen--; + } + } + while (SPI1_GET_TOTAL_CNT() != 0); // Wait for all the data in the FIFO to be sent + +} + +/******************************************************************************* + * @fn SPI1_MasterRecv + * + * @brief Receive multiple bytes continuously using FIFO + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + **/ +void SPI1_MasterRecv(uint8_t *pbuf, uint16_t len) +{ + uint16_t readlen; + + readlen = len; + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set data direction to input + SPI1_SET_TOTAL_CNT(len); // Set the length of the data to be received, the FIFO direction will start the + // transmission if the input length is not 0 + R8_SPI1_INT_FLAG = RB_SPI_IF_CNT_END; + SPI1_SET_FIFO(0xff); + while (readlen) + { + if (SPI1_GET_FIFO_CNT()) + { + *pbuf = SPI1_GET_FIFO(); + SPI1_SET_FIFO(0xff); + pbuf++; + readlen--; + } + } +} + +/******************************************************************************* + * @fn SPI1_MasterTransRecv + * + * @brief Continuously send/receive multiple bytes + * + * @param pbuf: The first address of the data content to be sent + * + * @return none + */ +void SPI1_MasterTransRecv(uint8_t *ptbuf, uint8_t *prbuf, uint16_t len) +{ + uint16_t sendlen; + + sendlen = len; + SPI1_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI1_ClearITFlag(RB_SPI_IF_CNT_END); + while (sendlen) + { + if (SPI1_GET_FIFO_CNT() == 0) + { + SPI1_SET_FIFO(*ptbuf); + while (SPI1_GET_FIFO_CNT() != 0); + ptbuf++; + *prbuf = SPI1_GET_BUFFER(); + prbuf++; + sendlen--; + } + } +} + +/******************************************************************************* + * @fn SPI1_SlaveInit + * + * @brief Device mode default initialization + * + * @return none + */ +void SPI1_SlaveInit() +{ + SPI1_MODE_CFG(RB_SPI_MODE_SLAVE | RB_SPI_ALL_CLEAR, ENABLE); + SPI1_MODE_CFG(RB_SPI_MOSI_OE | RB_SPI_SCK_OE | RB_SPI_ALL_CLEAR, DISABLE); + SPI1_MODE_CFG(RB_SPI_MISO_OE, ENABLE); + + SPI1_SET_DMA_MODE(0xff, DISABLE); +} + +/******************************************************************************* + * @fn SPI1_SlaveRecvByte + * + * @brief Slave mode, receive one byte of data + * + * @return received data + */ +uint8_t SPI1_SlaveRecvByte(void) +{ + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set to input mode, receive data + while (!SPI1_GET_FIFO_CNT()); + return SPI1_GET_FIFO(); +} + +/******************************************************************************* + * @fn SPI1_SlaveRecvByte + * + * @brief Slave mode, send one byte of data + * + * @param data: data will be sent + * + * @return send data + **/ +void SPI1_SlaveSendByte(uint8_t data) +{ + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set to output mode, send data + SPI1_SET_FIFO(data); + SPI1_SET_TOTAL_CNT(1); + while (SPI1_GET_FIFO_CNT()); +} + +/******************************************************************************* + * @fn SPI1_SlaveRecv + * + * @brief Slave mode, receive multi-byte data + * + * @param pbuf: Receive data storage starting address + * + * @return 0/1 0 means receive failed,1 means receive success. + **/ +uint8_t SPI1_SlaveRecv(uint8_t *pbuf, uint16_t len, uint16_t timeouts) +{ + uint16_t revlen; + + revlen = len; + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, ENABLE); // Set to input mode, receive data + SPI1_SET_TOTAL_CNT(revlen); // Assign a value to the SPI send and receive data total length register + while (revlen && timeouts) + { + if (!(timeouts & SPI_MAX_DELAY)) + { + delay(); + timeouts--; + } + if (SPI1_GET_FIFO_CNT()) // Byte count in the current FIFO + { + *pbuf = SPI1_GET_FIFO(); + pbuf++; + revlen--; + } + } + if (!revlen) + { + return 0; + } + else + { + return 1; + } +} + +/******************************************************************************* + * @fn SPI1_SlaveTrans + * + * @brief Slave mode, send multi-byte data + * + * @param pbuf: The first address of the data content to be sent + * + * @return 0/1 0 means receive failed,1 means receive success. + */ +uint8_t SPI1_SlaveTrans(uint8_t *pbuf, uint16_t len, uint16_t timeouts) +{ + uint16_t sendlen; + + sendlen = len; + SPI1_MODE_CFG(RB_SPI_FIFO_DIR, DISABLE); // Set data direction to output + SPI1_SET_TOTAL_CNT(sendlen); // Set the length of the data to be sent + while (sendlen) + { + if (!(timeouts & SPI_MAX_DELAY)) + { + delay(); + timeouts--; + } + if (SPI1_GET_FIFO_CNT() < SPI1_FIFO_SIZE) // Compare the byte count size in the current FIFO + { + SPI1_SET_FIFO(*pbuf); + pbuf++; + sendlen--; + } + } + if (!sendlen) + { + return 0; + } + else + { + return 1; + } +} diff --git a/Peripheral/src/ch564_tim.c b/Peripheral/src/ch564_tim.c new file mode 100644 index 0000000..ace4ee3 --- /dev/null +++ b/Peripheral/src/ch564_tim.c @@ -0,0 +1,377 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_tim.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the TIM firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_tim.h" + +/******************************************************************************* + * @fn TMR0_TimerInit + * + * @brief Counting Function on TIM PeriPheral + * + * @param arr - the Most End Value counting to + * + * @return none + */ +void TMR0_TimerInit(uint32_t arr) +{ + R32_TMR0_CNT_END = arr; +} + +/******************************************************************************* + * @fn TMR1_TimerInit + * + * @brief Counting Function on TIM PeriPheral + * + * @param arr - the Most End Value counting to + * + * @return none + */ +void TMR1_TimerInit(uint32_t arr) +{ + R32_TMR1_CNT_END = arr; +} + +/******************************************************************************* + * @fn TMR2_TimerInit + * + * @brief Counting Function on TIM PeriPheral + * + * @param arr - the Most End Value counting to + * + * @return none + */ +void TMR2_TimerInit(uint32_t arr) +{ + R32_TMR2_CNT_END = arr; +} + +/******************************************************************************* + * @fn TMR3_TimerInit + * + * @brief Counting Function on TIM PeriPheral + * + * @param arr - the Most End Value counting to + * + * @return none + */ +void TMR3_TimerInit(uint32_t arr) +{ + R32_TMR3_CNT_END = arr; +} + +/******************************************************************************* + * @fn TMR3_EXTSignalCounterInit + * + * @brief external signal count + * + * @param arr - the most end value contting to + * capedge - capture edge + * CAP_NULL + * Edge_To_Edge + * FallEdge_To_FallEdge + * RiseEdge_To_RiseEdge + * capwidth - the shortest width can be captured + * clock16 = 0, + * clock8 + * + * @return none + */ +void TMR3_EXTSignalCounterInit(uint32_t arr, CapModeTypeDef capedge, CapWidthTypedef capwidth) +{ + R32_TMR3_CNT_END = arr; + R8_TMR3_CTRL_MOD = RB_TMR_ALL_CLEAR; + R8_TMR3_CTRL_MOD = RB_TMR3_MODE_COUNT; + R8_TMR3_CTRL_MOD &= ~(0x03 << 6); + R8_TMR3_CTRL_MOD |= (capedge << 6); + R8_TMR3_CTRL_MOD &= ~(0x01 << 4); + R8_TMR3_CTRL_MOD |= (capwidth << 4); +} + +/******************************************************************************* + * @fn TMR0_PWMInit + * + * @brief PWM Output Init + * + * @param polarities - PWM output polarity + * high_on_low + * low_on_high + * repeattime - Number of repetitions of PWM + * PWM_Times_1 + * PWM_Times_4 + * PWM_Times_8 + * PWM_Times_16 + * + * @return none + */ +void TMR0_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime) +{ + uint8_t tmp = 0; + tmp = RB_TMR_OUT_EN | (polarities << 4) | (repeattime << 6); + R8_TMR0_CTRL_MOD = tmp; +} + +/********** ********************************************************************* + * @fn TMR1_PWMInit + * + * @brief PWM Output Init + * + * @param polarities - PWM output polarity + * high_on_low + * low_on_high + * repeattime - Number of repetitions of PWM + * PWM_Times_1 + * PWM_Times_4 + * PWM_Times_8 + * PWM_Times_16 + * + * @return none + */ +void TMR1_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime) +{ + uint8_t tmp = 0; + tmp = RB_TMR_OUT_EN | (polarities << 4) | (repeattime << 6); + R8_TMR1_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR2_PWMInit + * + * @brief PWM Output Init + * + * @param polarities - PWM output polarity + * high_on_low + * low_on_high + * repeattime - Number of repetitions of PWM + * PWM_Times_1 + * PWM_Times_4 + * PWM_Times_8 + * PWM_Times_16 + * + * @return none + */ +void TMR2_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime) +{ + uint8_t tmp = 0; + tmp = RB_TMR_OUT_EN | (polarities << 4) | (repeattime << 6); + R8_TMR2_CTRL_MOD = tmp; +} + +/********** ********************************************************************* + * @fn TMR3_PWMInit + * + * @brief PWM Output Init + * + * @param polarities - PWM output polarity + * high_on_low + * low_on_high + * repeattime - Number of repetitions of PWM + * PWM_Times_1 + * PWM_Times_4 + * PWM_Times_8 + * PWM_Times_16 + * + * @return none + */ +void TMR3_PWMInit(PWM_PolarTypeDef polarities, PWM_RepeatTsTypeDef repeattime) +{ + uint8_t tmp = 0; + tmp = RB_TMR_OUT_EN | (polarities << 4) | (repeattime << 6); + R8_TMR3_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR0_CapInit + * + * @brief Timer capture function initialization + * + * @param capedge - capture edge + * CAP_NULL + * Edge_To_Edge + * FallEdge_To_FallEdge + * RiseEdge_To_RiseEdge + * capwidth - the shortest width can be captured + * clock16 = 0, + * clock8 + * + * @return none + */ +void TMR0_CapInit(CapModeTypeDef capedge, CapWidthTypedef widt) +{ + uint8_t tmp = 0; + tmp = RB_TMR_MODE_IN | (capedge << 6) | (widt << 4); + R8_TMR0_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR1_CapInit + * + * @brief Timer capture function initialization + * + * @param capedge - capture edge + * CAP_NULL + * Edge_To_Edge + * FallEdge_To_FallEdge + * RiseEdge_To_RiseEdge + * capwidth - the shortest width can be captured + * clock16 = 0, + * clock8 + * + * @return none + */ +void TMR1_CapInit(CapModeTypeDef capedge, CapWidthTypedef widt) +{ + uint8_t tmp = 0; + tmp = RB_TMR_MODE_IN | (capedge << 6) | (widt << 4); + R8_TMR1_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR2_CapInit + * + * @brief Timer capture function initialization + * + * @param capedge - capture edge + * CAP_NULL + * Edge_To_Edge + * FallEdge_To_FallEdge + * RiseEdge_To_RiseEdge + * capwidth - the shortest width can be captured + * clock16 = 0, + * clock8 + * + * @return none + */ +void TMR2_CapInit(CapModeTypeDef capedge, CapWidthTypedef widt) +{ + uint8_t tmp = 0; + tmp = RB_TMR_MODE_IN | (capedge << 6) | (widt << 4); + R8_TMR2_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR3_CapInit + * + * @brief Timer capture function initialization + * + * @param capedge - capture edge + * CAP_NULL + * Edge_To_Edge + * FallEdge_To_FallEdge + * RiseEdge_To_RiseEdge + * capwidth - the shortest width can be captured + * clock16 = 0, + * clock8 + * + * @return none + */ +void TMR3_CapInit(CapModeTypeDef capedge, CapWidthTypedef widt) +{ + uint8_t tmp = 0; + tmp = RB_TMR_MODE_IN | (capedge << 6) | (widt << 4); + R8_TMR3_CTRL_MOD = tmp; +} + +/******************************************************************************* + * @fn TMR0_DMACfg + * + * @brief TMR DMA Configuration + * + * @param NewSTA + * - ENABLE/DISABLE + * startAddr + * - DMA start address + * endAddr + * - DMA end address + * DMAMode + * - DMA mode + * @return none + **/ +void TMR0_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode) +{ + if (NewSTA == DISABLE) + { + R8_TMR0_CTRL_DMA = 0; + } + else + { + TMR0_DMA_SET_RANGE(startAddr, endAddr); + if (DMAMode & Mode_LOOP) + R8_TMR0_CTRL_DMA |= RB_TMR_DMA_LOOP; + if (DMAMode & Mode_Burst) + R8_TMR0_CTRL_DMA |= RB_TMR_DMA_BURST; + R8_TMR0_CTRL_DMA |= RB_TMR_DMA_ENABLE; + } +} + +/******************************************************************************* + * @fn TMR1_DMACfg + * + * @brief TMR DMA Configuration + * + * @param NewSTA + * - ENABLE/DISABLE + * startAddr + * - DMA start address + * endAddr + * - DMA end address + * DMAMode + * - DMA mode + * @return none + **/ +void TMR1_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode) +{ + if (NewSTA == DISABLE) + { + R8_TMR1_CTRL_DMA = 0; + } + else + { + TMR1_DMA_SET_RANGE(startAddr, endAddr); + if (DMAMode & Mode_LOOP) + R8_TMR1_CTRL_DMA |= RB_TMR_DMA_LOOP; + if (DMAMode & Mode_Burst) + R8_TMR1_CTRL_DMA |= RB_TMR_DMA_BURST; + R8_TMR1_CTRL_DMA |= RB_TMR_DMA_ENABLE; + } +} + +/******************************************************************************* + * @fn TMR2_DMACfg + * + * @brief TMR DMA Configuration + * + * @param NewSTA + * - ENABLE/DISABLE + * startAddr + * - DMA start address + * endAddr + * - DMA end address + * DMAMode + * - DMA mode + * @return none + **/ + +void TMR2_DMACfg(FunctionalState NewSTA, uint32_t startAddr, uint32_t endAddr, DMAModeTypeDef DMAMode) +{ + if (NewSTA == DISABLE) + { + R8_TMR2_CTRL_DMA = 0; + } + else + { + TMR2_DMA_SET_RANGE(startAddr, endAddr); + if (DMAMode & Mode_LOOP) + R8_TMR2_CTRL_DMA |= RB_TMR_DMA_LOOP; + if (DMAMode & Mode_Burst) + R8_TMR2_CTRL_DMA |= RB_TMR_DMA_BURST; + R8_TMR2_CTRL_DMA |= RB_TMR_DMA_ENABLE; + } +} diff --git a/Peripheral/src/ch564_uart.c b/Peripheral/src/ch564_uart.c new file mode 100644 index 0000000..0578428 --- /dev/null +++ b/Peripheral/src/ch564_uart.c @@ -0,0 +1,843 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_uart.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the UART firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_uart.h" +#include "debug.h" + +static uint8_t Best_DIV; +/****************************************************************************** + * @fn Less_Loss_DIV_Calcu + * + * @brief Caculate the most fit DIV value + * + * @return none + */ +void Less_Loss_DIV_Calcu(uint64_t targetbaud) +{ + uint64_t extranum, result_keeper = 1; + extranum = targetbaud; + for (unsigned int i = 1; i < 128; i++) + { + if (!((SystemCoreClock * 2 / 16 / i) * 2 / targetbaud)) + break; + long tmpextra = (SystemCoreClock * 2 / 16 / i) % targetbaud; + tmpextra = tmpextra > targetbaud / 2 ? targetbaud - tmpextra : tmpextra; + + if (tmpextra < extranum) + { + result_keeper = i; + extranum = tmpextra; + } + } + Best_DIV = result_keeper; +} +/****************************************************************************** + * @fn UART0_DefInit + * + * @brief Serial port default initialization configuration: FIFO enabled, trigger point byte count, serial port data + * length setting, baud rate and frequency division coefficient + * + * @return none + */ +void UART0_DefInit(void) +{ + + UART0_BaudRateCfg(115200); + R8_UART0_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; // FIFO open, trigger point 14 bytes + R8_UART0_LCR = RB_LCR_WORD_SZ; + R8_UART0_IER = RB_IER_TXD_EN; + R8_UART0_MCR = RB_MCR_OUT1; +} + +/******************************************************************************* + * @fn UART1_DefInit + * + * @brief Serial port default initialization configuration: FIFO enabled, trigger point byte count, serial port data + *length setting, baud rate and frequency division coefficient + * + * @return none + **/ +void UART1_DefInit(void) +{ + UART1_BaudRateCfg(115200); + R8_UART1_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART1_LCR = RB_LCR_WORD_SZ; + R8_UART1_IER = RB_IER_TXD_EN; + R8_UART1_MCR = RB_MCR_OUT1; +} + +/******************************************************************************* + * @fn UART2_DefInit + * + * @brief Serial port default initialization configuration: FIFO enabled, trigger point byte count, serial port data + * length setting, baud rate and frequency division coefficient + * + * @return none + */ +void UART2_DefInit(void) +{ + + UART2_BaudRateCfg(115200); + R8_UART2_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART2_LCR = RB_LCR_WORD_SZ; + R8_UART2_IER = RB_IER_TXD_EN; + R8_UART2_MCR = RB_MCR_OUT1; +} + +/******************************************************************************* + * @fn UART3_DefInit + * + * @brief Serial port default initialization configuration: FIFO enabled, trigger point byte count, serial port data + * length setting, baud rate and frequency division coefficient + * + * @return none + */ +void UART3_DefInit(void) +{ + UART3_BaudRateCfg(115200); + R8_UART3_FCR = RB_FCR_FIFO_TRIG | RB_FCR_TX_FIFO_CLR | RB_FCR_RX_FIFO_CLR | RB_FCR_FIFO_EN; + // FIFO open, trigger point 14 bytes + R8_UART3_LCR = RB_LCR_WORD_SZ; + R8_UART3_IER = RB_IER_TXD_EN; + R8_UART3_MCR = RB_MCR_OUT1; +} + +/******************************************************************************* + * @fn UART0_BaudRateCfg + * + * @brief Serial port baud rate configuration + * + * @return none + */ +void UART0_BaudRateCfg(uint32_t baudrate) +{ + uint64_t x; + Less_Loss_DIV_Calcu(baudrate); + x = 10 * (SystemCoreClock / Best_DIV) / 8 / baudrate; + x += 5; + x /= 10; + x = x == 0 ? 1 : x; + R8_UART0_LCR |= RB_LCR_DLAB; + UART0_SET_DLV(Best_DIV); + R8_UART0_DLM = x >> 8; + R8_UART0_DLL = x; + R8_UART0_LCR &= ~RB_LCR_DLAB; +} + +/******************************************************************************* + * @fn UART1_BaudRateCfg + * + * @brief Serial port baud rate configuration + * + * @return none + */ +void UART1_BaudRateCfg(uint32_t baudrate) +{ + uint64_t x; + Less_Loss_DIV_Calcu(baudrate); + x = 10 * (SystemCoreClock / Best_DIV) / 8 / baudrate; + x += 5; + x /= 10; + x = x == 0 ? 1 : x; + R8_UART1_LCR |= RB_LCR_DLAB; + UART1_SET_DLV(Best_DIV); + R8_UART1_DLM = x >> 8; + R8_UART1_DLL = x; + R8_UART1_LCR &= ~RB_LCR_DLAB; +} + +/******************************************************************************* + * @fn UART2_BaudRateCfg + * + * @brief Serial port baud rate configuration + * + * @return none + */ +void UART2_BaudRateCfg(uint32_t baudrate) +{ + uint64_t x; + Less_Loss_DIV_Calcu(baudrate); + x = 10 * (SystemCoreClock / Best_DIV) / 8 / baudrate; + x += 5; + x /= 10; + x = x == 0 ? 1 : x; + R8_UART2_LCR |= RB_LCR_DLAB; + UART2_SET_DLV(Best_DIV); + R8_UART2_DLM = x >> 8; + R8_UART2_DLL = x; + R8_UART2_LCR &= ~RB_LCR_DLAB; +} + +/******************************************************************************* + * @fn UART3_BaudRateCfg + * + * @brief Serial port baud rate configuration + * + * @return none + */ +void UART3_BaudRateCfg(uint32_t baudrate) +{ + uint64_t x; + Less_Loss_DIV_Calcu(baudrate); + x = 10 * (SystemCoreClock / Best_DIV) / 8 / baudrate; + x += 5; + x /= 10; + x = x == 0 ? 1 : x; + R8_UART3_LCR |= RB_LCR_DLAB; + UART3_SET_DLV(Best_DIV); + R8_UART3_DLM = x >> 8; + R8_UART3_DLL = x; + R8_UART3_LCR &= ~RB_LCR_DLAB; +} + +/******************************************************************************* + * @fn UART0_ByteTrigCfg + * + * @brief Serial byte trigger interrupt configuration + * + * @param UARTByteTRIG - trigger bytes + * refer to UARTByteTRIGTypeDef + * @return none + */ +void UART0_ByteTrigCfg(UARTByteTRIGTypeDef UARTByteTRIG) +{ + R8_UART0_FCR = (R8_UART0_FCR & ~RB_FCR_FIFO_TRIG) | (UARTByteTRIG << 6); +} + +/******************************************************************************* + * @fn UART1_ByteTrigCfg + * + * @brief Serial byte trigger interrupt configuration + * + * @param UARTByteTRIG - trigger bytes + * refer to UARTByteTRIGTypeDef + * @return none + **/ +void UART1_ByteTrigCfg(UARTByteTRIGTypeDef UARTByteTRIG) +{ + R8_UART1_FCR = (R8_UART1_FCR & ~RB_FCR_FIFO_TRIG) | (UARTByteTRIG << 6); +} + +/******************************************************************************* + * @fn UART2_ByteTrigCfg + * + * @brief Serial byte trigger interrupt configuration + * + * @param UARTByteTRIG - trigger bytes + * refer to UARTByteTRIGTypeDef + * @return none + */ +void UART2_ByteTrigCfg(UARTByteTRIGTypeDef UARTByteTRIG) +{ + R8_UART2_FCR = (R8_UART2_FCR & ~RB_FCR_FIFO_TRIG) | (UARTByteTRIG << 6); +} + +/******************************************************************************* + * @fn UART3_ByteTrigCfg + * + * @brief Serial byte trigger interrupt configuration + * + * @param UARTByteTRIG - trigger bytes + * refer to UARTByteTRIGTypeDef + * @return none + ***/ +void UART3_ByteTrigCfg(UARTByteTRIGTypeDef UARTByteTRIG) +{ + R8_UART3_FCR = (R8_UART3_FCR & ~RB_FCR_FIFO_TRIG) | (UARTByteTRIG << 6); +} + +/******************************************************************************* + * @fn UART0_INTCfg + * + * @brief Serial port interrupt configuration + * + * @param NewSTA - interrupt control status + * ENABLE - Enable the corresponding interrupt + * DISABLE - Disable the corresponding interrupt + * @param RB_IER - interrupt type + * RB_IER_MODEM_CHG - Modem input status change interrupt enable bit (supported on UART0 only) + * RB_IER_LINE_STAT - Receive Line Status Interrupt + * RB_IER_THR_EMPTY - Send Holding Register Empty Interrupt + * RB_IER_RECV_RDY - receive data interrupt + * @return none + **/ +void UART0_INTCfg(FunctionalState NewSTA, uint8_t RB_IER) +{ + if (NewSTA) + { + R8_UART0_IER |= RB_IER; + + R8_UART0_MCR |= RB_MCR_OUT2; + } + else + { + R8_UART0_IER &= ~RB_IER; + } +} + +/******************************************************************************* + * @fn UART1_INTCfg + * + * @brief Serial port interrupt configuration + * + * @param NewSTA - interrupt control status + * ENABLE - Enable the corresponding interrupt + * DISABLE - Disable the corresponding interrupt + * @param RB_IER - interrupt type + * RB_IER_MODEM_CHG - Modem input status change interrupt enable bit (supported on UART0 only) + * RB_IER_LINE_STAT - Receive Line Status Interrupt + * RB_IER_THR_EMPTY - Send Holding Register Empty Interrupt + * RB_IER_RECV_RDY - receive data interrupt + * @return none + **/ +void UART1_INTCfg(FunctionalState NewSTA, uint8_t RB_IER) +{ + if (NewSTA) + { + R8_UART1_IER |= RB_IER; + R8_UART1_MCR |= RB_MCR_OUT2; + } + else + { + R8_UART1_IER &= ~RB_IER; + } +} + +/******************************************************************************* + * @fn UART2_INTCfg + * + * @brief Serial port interrupt configuration + * + * @param NewSTA - interrupt control status + * ENABLE - Enable the corresponding interrupt + * DISABLE - Disable the corresponding interrupt + * @param RB_IER - interrupt type + * RB_IER_MODEM_CHG - Modem input status change interrupt enable bit (supported on UART0 only) + * RB_IER_LINE_STAT - Receive Line Status Interrupt + * RB_IER_THR_EMPTY - Send Holding Register Empty Interrupt + * RB_IER_RECV_RDY - receive data interrupt + * @return none + **/ +void UART2_INTCfg(FunctionalState NewSTA, uint8_t RB_IER) +{ + if (NewSTA) + { + R8_UART2_IER |= RB_IER; + R8_UART2_MCR |= RB_MCR_OUT2; + } + else + { + R8_UART2_IER &= ~RB_IER; + } +} + +/******************************************************************************* + * @fn UART3_INTCfg + * + * @brief Serial port interrupt configuration + * + * @param NewSTA - interrupt control status + * ENABLE - Enable the corresponding interrupt + * DISABLE - Disable the corresponding interrupt + * @param RB_IER - interrupt type + * RB_IER_MODEM_CHG - Modem input status change interrupt enable bit (supported on UART0 only) + * RB_IER_LINE_STAT - Receive Line Status Interrupt + * RB_IER_THR_EMPTY - Send Holding Register Empty Interrupt + * RB_IER_RECV_RDY - receive data interrupt + * @return none + **/ +void UART3_INTCfg(FunctionalState NewSTA, uint8_t RB_IER) +{ + if (NewSTA) + { + R8_UART3_IER |= RB_IER; + R8_UART3_MCR |= RB_MCR_OUT2; + } + else + { + R8_UART3_IER &= ~RB_IER; + } +} + +/******************************************************************************* + * @fn UART0_Reset + * + * @brief Serial port software reset + * + * @return none + **/ +void UART0_Reset(void) +{ + R8_UART0_IER = RB_IER_RESET; +} + +/******************************************************************************* + * @fn UART1_Reset + * + * @brief Serial port software reset + * + * @return none + **/ +void UART1_Reset(void) +{ + R8_UART1_IER = RB_IER_RESET; +} + +/******************************************************************************* + * @fn UART2_Reset + * + * @brief Serial port software reset + * + * @return none + **/ +void UART2_Reset(void) +{ + R8_UART2_IER = RB_IER_RESET; +} + +/******************************************************************************* + * @fn UART3_Reset + * + * @brief Serial port software reset + * + * @return none + **/ +void UART3_Reset(void) +{ + R8_UART3_IER = RB_IER_RESET; +} + +/******************************************************************************* + * @fn UART0_SendString + * + * @brief Serial multi-byte transmission + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART0_SendString(uint8_t *buf, uint16_t length) +{ + uint16_t len = length; + uint32_t delay_num = 0; + + while (len) + { + //ι + + if ((R8_UART0_LSR & RB_LSR_TX_FIFO_EMP)) + { + R8_UART0_THR = *buf++; + len--; + } + Delay_Us(1); + delay_num++; + if(delay_num > 20000) break; + } +} + +/******************************************************************************* + * @fn UART1_SendString + * + * @brief Serial multi-byte transmission + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART1_SendString(uint8_t *buf, uint16_t length) +{ + uint16_t len = length; + uint32_t delay_num = 0; + + while (len) + { + //ι + + if ((R8_UART1_LSR & RB_LSR_TX_FIFO_EMP)) + { + R8_UART1_THR = *buf++; + len--; + } + Delay_Us(1); + delay_num++; + if(delay_num > 20000) break; + } +} + +/******************************************************************************* + * @fn UART2_SendString + * + * @brief Serial multi-byte transmission + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART2_SendString(uint8_t *buf, uint16_t length) +{ + uint16_t len = length; + uint32_t delay_num = 0; + + while (len) + { + //ι + + if ((R8_UART2_LSR & RB_LSR_TX_FIFO_EMP)) + { + R8_UART2_THR = *buf++; + len--; + } + Delay_Us(1); + delay_num++; + if(delay_num > 20000) break; + } +} + +/******************************************************************************* + * @fn UART3_SendString + * + * @brief Serial multi-byte transmission + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART3_SendString(uint8_t *buf, uint16_t length) +{ + uint16_t len = length; + uint32_t delay_num = 0; + + while (len) + { + //ι + + if ((R8_UART3_LSR & RB_LSR_TX_FIFO_EMP)) + { + R8_UART3_THR = *buf++; + len--; + } + Delay_Us(1); + delay_num++; + if(delay_num > 20000) break; + } +} + +/******************************************************************************* + * @fn UART0_RecvString + * + * @brief Serial port read multibyte + * + * @param buf - The first address of the read data storage buffer + * + * @return read data length + */ +uint16_t UART0_RecvString(uint8_t *buf) +{ + uint16_t len = 0; + + if (!((R8_UART0_LSR) & (RB_LSR_OVER_ERR | RB_LSR_PAR_ERR | RB_LSR_FRAME_ERR | RB_LSR_BREAK_ERR))) + { + while ((R8_UART0_LSR & RB_LSR_DATA_RDY) == 0) + ; + do + { + *buf++ = R8_UART0_RBR; + len++; + } while ((R8_UART0_LSR & RB_LSR_DATA_RDY)); + } + + return (len); +} + +/******************************************************************************* + * @fn UART1_RecvString + * + * @brief Serial port read multibyte + * + * @param buf - The first address of the read data storage buffer + * + * @return read data length + */ + +uint16_t UART1_RecvString(uint8_t *buf) +{ + uint16_t len = 0; + + if (!((R8_UART1_LSR) & (RB_LSR_OVER_ERR | RB_LSR_PAR_ERR | RB_LSR_FRAME_ERR | RB_LSR_BREAK_ERR))) + { + while ((R8_UART1_LSR & RB_LSR_DATA_RDY) == 0) + ; + do + { + *buf++ = R8_UART1_RBR; + len++; + } while ((R8_UART1_LSR & RB_LSR_DATA_RDY)); + } + + return (len); +} + +/******************************************************************************* + * @fn UART2_RecvString + * + * @brief Serial port read multibyte + * + * @param buf - The first address of the read data storage buffer + * + * @return read data length + */ + +uint16_t UART2_RecvString(uint8_t *buf) +{ + uint16_t len = 0; + + if (!((R8_UART2_LSR) & (RB_LSR_OVER_ERR | RB_LSR_PAR_ERR | RB_LSR_FRAME_ERR | RB_LSR_BREAK_ERR))) + { + while ((R8_UART2_LSR & RB_LSR_DATA_RDY) == 0) + ; + do + { + *buf++ = R8_UART2_RBR; + len++; + } while ((R8_UART2_LSR & RB_LSR_DATA_RDY)); + } + + return (len); +} + +/******************************************************************************* + * @fn UART3_RecvString + * + * @brief Serial port read multibyte + * + * @param buf - The first address of the read data storage buffer + * + * @return read data length + */ + +uint16_t UART3_RecvString(uint8_t *buf) +{ + uint16_t len = 0; + + if (!((R8_UART3_LSR) & (RB_LSR_OVER_ERR | RB_LSR_PAR_ERR | RB_LSR_FRAME_ERR | RB_LSR_BREAK_ERR))) + { + while ((R8_UART3_LSR & RB_LSR_DATA_RDY) == 0) + ; + do + { + *buf++ = R8_UART3_RBR; + len++; + } while ((R8_UART3_LSR & RB_LSR_DATA_RDY)); + } + return (len); +} + +/******************************************************************************* + * @fn UART0_Send_DMA + * + * @brief Serial multi-byte transmission via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART0_Send_DMA(uint8_t *buf, uint32_t lenth) +{ + UART0_DMA_SET_RD_RANGE(buf, buf + lenth); + UART0_DMACFG(RB_DMA_RD_EN, ENABLE); +} +/******************************************************************************* + * @fn UART1_Send_DMA + * + * @brief Serial multi-byte transmission via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART1_Send_DMA(uint8_t *buf, uint32_t lenth) +{ + UART1_DMA_SET_RD_RANGE(buf, buf + lenth); + UART1_DMACFG(RB_DMA_RD_EN, ENABLE); +} +/******************************************************************************* + * @fn UART2_Send_DMA + * + * @brief Serial multi-byte transmission via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART2_Send_DMA(uint8_t *buf, uint32_t lenth) +{ + UART2_DMA_SET_RD_RANGE(buf, buf + lenth); + UART2_DMACFG(RB_DMA_RD_EN, ENABLE); +} +/******************************************************************************* + * @fn UART3_Send_DMA + * + * @brief Serial multi-byte transmission via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART3_Send_DMA(uint8_t *buf, uint32_t lenth) +{ + UART3_DMA_SET_RD_RANGE(buf, buf + lenth); + UART3_DMACFG(RB_DMA_RD_EN, ENABLE); +} + +/******************************************************************************* + * @fn UART0_Recv_DMA + * + * @brief Serial multi-byte receive via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART0_Recv_DMA(uint8_t *buf, uint32_t lenth) +{ + UART0_DMA_SET_WR_RANGE(buf, buf + lenth); + UART0_DMACFG(RB_DMA_WR_EN, ENABLE); +} +/******************************************************************************* + * @fn UART1_Recv_DMA + * + * @brief Serial multi-byte receive via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART1_Recv_DMA(uint8_t *buf, uint32_t lenth) +{ + UART1_DMA_SET_WR_RANGE(buf, buf + lenth); + UART1_DMACFG(RB_DMA_WR_EN, ENABLE); +} +/******************************************************************************* + * @fn UART2_Recv_DMA + * + * @brief Serial multi-byte receive via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART2_Recv_DMA(uint8_t *buf, uint32_t lenth) +{ + UART2_DMA_SET_WR_RANGE(buf, buf + lenth); + UART2_DMACFG(RB_DMA_WR_EN, ENABLE); +} +/******************************************************************************* + * @fn UART3_Recv_DMA + * + * @brief Serial multi-byte receive via DMA + * + * @param buf - The first address of the data content to be sent + * length - length of data to be sent + * @return none + */ +void UART3_Recv_DMA(uint8_t *buf, uint32_t lenth) +{ + UART3_DMA_SET_WR_RANGE(buf, buf + lenth); + UART3_DMACFG(RB_DMA_WR_EN, ENABLE); +} + +/******************************************************************************* + * @fn UART0_DTRDSR_Cfg + * + * @brief Enable or disable DTR/DSR function + * + * @param en - ENABLE/DISABLE + * + * @return none + */ +void UART0_DTRDSR_Cfg (FunctionalState en) { + UART0_SET_MCR (RB_MCR_DTR, en); +} + +/******************************************************************************* + * @fn UART0_CTSRTS_Cfg + * + * @brief Enable or disable CTS/RTS function + * + * @param en - ENABLE/DISABLE + * + * @return none + */ +void UART0_CTSRTS_Cfg (GPIO_Typedef* GPIOx, FunctionalState en, FunctionalState auto_ctrl_en) { + if(GPIOx == GPIOA) + UART0_INTCfg (DISABLE, RB_IER_MODEM_IO); + else if(GPIOx == GPIOB) + UART0_INTCfg (ENABLE, RB_IER_MODEM_IO); + UART0_INTCfg (en, RB_IER_MOUT_EN | RB_IER_MOUT_EN | RB_IER_MODEM_CHG); + UART0_SET_MCR ((auto_ctrl_en == ENABLE) ? RB_MCR_AU_FLOW_EN : 0, ENABLE); +} + +/******************************************************************************* + * @fn UART1_CTSRTS_Cfg + * + * @brief Enable or disable CTS/RTS function + * + * @param en - ENABLE/DISABLE + * + * @return none + */ +void UART1_CTSRTS_Cfg (GPIO_Typedef* GPIOx, FunctionalState en, FunctionalState auto_ctrl_en) { + if(GPIOx == GPIOA) + UART1_INTCfg (DISABLE, RB_IER_MODEM_IO); + else if(GPIOx == GPIOB) + UART1_INTCfg (ENABLE, RB_IER_MODEM_IO); + UART1_INTCfg (en, RB_IER_MOUT_EN | RB_IER_MOUT_EN | RB_IER_MODEM_CHG); + UART1_SET_MCR ((auto_ctrl_en == ENABLE) ? RB_MCR_AU_FLOW_EN : 0, ENABLE); +} + +/******************************************************************************* + * @fn UART2_CTSRTS_Cfg + * + * @brief Enable or disable CTS/RTS function + * + * @param en - ENABLE/DISABLE + * + * @return none + */ +void UART2_CTSRTS_Cfg (GPIO_Typedef* GPIOx, FunctionalState en, FunctionalState auto_ctrl_en) { + if(GPIOx == GPIOA) + UART2_INTCfg (DISABLE, RB_IER_MODEM_IO); + else if(GPIOx == GPIOB) + UART2_INTCfg (ENABLE, RB_IER_MODEM_IO); + UART2_INTCfg (en, RB_IER_MOUT_EN | RB_IER_MOUT_EN | RB_IER_MODEM_CHG); + UART2_SET_MCR ((auto_ctrl_en == ENABLE) ? RB_MCR_AU_FLOW_EN : 0, ENABLE); +} + +/******************************************************************************* + * @fn UART3_CTSRTS_Cfg + * + * @brief Enable or disable CTS/RTS function + * + * @param en - ENABLE/DISABLE + * + * @return none + */ +void UART3_CTSRTS_Cfg (GPIO_Typedef* GPIOx, FunctionalState en, FunctionalState auto_ctrl_en) { + if(GPIOx == GPIOA) + UART3_INTCfg (DISABLE, RB_IER_MODEM_IO); + else if(GPIOx == GPIOB) + UART3_INTCfg (ENABLE, RB_IER_MODEM_IO); + UART3_INTCfg (en, RB_IER_MOUT_EN | RB_IER_MOUT_EN | RB_IER_MODEM_CHG); + UART3_SET_MCR ((auto_ctrl_en == ENABLE) ? RB_MCR_AU_FLOW_EN : 0, ENABLE); +} diff --git a/Peripheral/src/ch564_xbus.c b/Peripheral/src/ch564_xbus.c new file mode 100644 index 0000000..dc5cad5 --- /dev/null +++ b/Peripheral/src/ch564_xbus.c @@ -0,0 +1,62 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : ch564_xbus.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : This file provides all the XBUS firmware functions. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#include "ch564_xbus.h" + +/********************************************************************** + * @fn XbusInit + * + * @brief The XbusInit function initializes the Xbus configuration by setting the address bit, enabling or + * disabling 32-bit mode, and enabling or disabling the Xbus. + * + * @param AddrBit The AddrBit parameter is of type XbusOutputADDrBit, which is likely an enumeration or + * a typedef for a specific type. It represents the address bit configuration for the Xbus module. + * NoOutput No Xbus address output + * - AddrNum_6bit PA[5:0] part of address output + * - AddrNum_12bit PA[11:0] part of address output + * - AddrNum_ALL PA[19:0] part of address output + * Bit32En The Bit32En parameter is used to enable or disable the 32-bit mode of the Xbus. If + * Bit32En is set to ENABLE, the 32-bit mode is enabled. If Bit32En is set to DISABLE, the 32-bit mode + * is disabled. + * Stat The "Stat" parameter is used to enable or disable the Xbus. If "Stat" is set to ENABLE, + * the Xbus will be enabled. If "Stat" is set to DISABLE, the Xbus will be disabled. + */ +void XbusInit(XbusOutputADDrBit AddrBit, FunctionalState Bit32En, FunctionalState Stat) +{ + + RCC_UNLOCK_SAFE_ACCESS(); + R8_XBUS_CONFIG = AddrBit << 2; + RCC_UNLOCK_SAFE_ACCESS(); + R8_XBUS_CONFIG |= (Bit32En == ENABLE ? 0 : RB_XBUS_EN_32BIT); + RCC_UNLOCK_SAFE_ACCESS(); + R8_XBUS_CONFIG |= (Stat == ENABLE ? 0 : RB_XBUS_ENABLE); + RCC_LOCK_SAFE_ACCESS(); /* lock, to prevent unexpected writing */ +} + +/********************************************************************** + * @fn XbusHoldInit + * + * @brief The function XbusHoldInit initializes the Xbus setup hold time and sets the hold time value based on + * the input parameters. + * + * @param setuptm The parameter "setuptm" is of type XbusSetupTime, which is an enumeration type. It + * represents the setup time for the XbusHoldInit function. The possible values for setuptm are: + * - Setuptime_1clk 1 clock cycle + * - Setuptime_2clk 2 clock cycle + * holdtm The holdtm parameter is a uint8_t variable that represents the hold time for the Xbus + * setup. It is used to set the R8_XBUS_SETUP_HOLD register. + */ +void XbusHoldInit(XbusSetupTime setuptm, uint8_t holdtm) +{ + holdtm = holdtm > 0x1f ? 0x1f : holdtm; + R8_XBUS_SETUP_HOLD = holdtm; + R8_XBUS_SETUP_HOLD |= setuptm == Setuptime_1clk ? 0 : 0x80; +} diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..2ce22c1 --- /dev/null +++ b/Readme.md @@ -0,0 +1,13 @@ +BLV-C1P Launcher˵ + + + +״ύ + +Է֣ + FLASH_ROMA_ERASE EEPROM_ERASE ǿСΪ4096 + + +2025-07-30 + Launcherַ 0x00000000 ~ 0x00004000 + \ No newline at end of file diff --git a/Startup/startup_ch564_ram_128k.S b/Startup/startup_ch564_ram_128k.S new file mode 100644 index 0000000..2c13f6b --- /dev/null +++ b/Startup/startup_ch564_ram_128k.S @@ -0,0 +1,240 @@ +;/********************************** (C) COPYRIGHT ******************************* +;* File Name : startup_CH564.S +;* Author : WCH +;* Version : V1.0.0 +;* Date : 2024/05/05 +;* Description : vector table for eclipse toolchain for CH564. +;********************************************************************************* +;* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. +;* Attention: This software (modified or not) and binary are used for +;* microcontroller manufactured by Nanjing Qinheng Microelectronics. +*******************************************************************************/ + + .section .init, "ax", @progbits + .globl _start + .align 2 + +_start: + .option norvc; + j handle_reset + + .section .vector,"ax",@progbits + .align 2 +_vector_base: + .option norvc; + .word _start + .word 0 + .word NMI_Handler + .word HardFault_Handler + .word 0x40000000 + .word Ecall_M_Handler + .word 0 + .word 0 + .word Ecall_U_Handler + .word BreakPoint_Handler + .word 0 + .word 0 + .word SysTick_Handler + .word 0 + .word SW_Handler + .word 0 + /*External Interrupts*/ + .word I2C_EV_IRQHandler + .word I2C_ER_IRQHandler + .word ETH_IRQHandler + .word USBPD_IRQHandler + .word TIM0_IRQHandler + .word TIM1_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word SPI0_IRQHandler + .word SPI1_IRQHandler + .word UART0_IRQHandler + .word UART1_IRQHandler + .word PA_IRQHandler + .word PB_IRQHandler + .word PD_IRQHandler + .word ADC_IRQHandler + .word SLV_IRQHandler + .word USBHS_HOST_IRQHandler + .word USBHS_DEV_IRQHandler + .word UART2_IRQHandler + .word UART3_IRQHandler + .word ETHWakeUp_IRQHandler + .word USBHSWakeUp_IRQHandler + .word USBPDWakeUp_IRQHandler + .word 0x08800513 + .word 0x80051073 + .word 0xe000f537 + .word 0xd1350513 + .word 0x08000593 + .word 0x0ff0000f + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + + .option rvc; + .section .text.vector_handler, "ax", @progbits + .weak NMI_Handler + .weak HardFault_Handler + .weak Ecall_M_Handler + .weak Ecall_U_Handler + .weak BreakPoint_Handler + .weak SysTick_Handler + .weak SW_Handler + .weak I2C_EV_IRQHandler + .weak I2C_ER_IRQHandler + .weak ETH_IRQHandler + .weak USBPD_IRQHandler + .weak TIM0_IRQHandler + .weak TIM1_IRQHandler + .weak TIM2_IRQHandler + .weak TIM3_IRQHandler + .weak SPI0_IRQHandler + .weak SPI1_IRQHandler + .weak UART0_IRQHandler + .weak UART1_IRQHandler + .weak PA_IRQHandler + .weak PB_IRQHandler + .weak PD_IRQHandler + .weak ADC_IRQHandler + .weak SLV_IRQHandler + .weak USBHS_HOST_IRQHandler + .weak USBHS_DEV_IRQHandler + .weak UART2_IRQHandler + .weak UART3_IRQHandler + .weak ETHWakeUp_IRQHandler + .weak USBHSWakeUp_IRQHandler + .weak USBPDWakeUp_IRQHandler + +NMI_Handler: +HardFault_Handler: +Ecall_M_Handler: +Ecall_U_Handler: +BreakPoint_Handler: +SysTick_Handler: +SW_Handler: +I2C_EV_IRQHandler: +I2C_ER_IRQHandler: +ETH_IRQHandler: +USBPD_IRQHandler: +TIM0_IRQHandler: +TIM1_IRQHandler: +TIM2_IRQHandler: +TIM3_IRQHandler: +SPI0_IRQHandler: +SPI1_IRQHandler: +UART0_IRQHandler: +UART1_IRQHandler: +PA_IRQHandler: +PB_IRQHandler: +PD_IRQHandler: +ADC_IRQHandler: +SLV_IRQHandler: +USBHS_HOST_IRQHandler: +USBHS_DEV_IRQHandler: +UART2_IRQHandler: +UART3_IRQHandler: +ETHWakeUp_IRQHandler: +USBHSWakeUp_IRQHandler: +USBPDWakeUp_IRQHandler: +1: + j 1b + + .section .text.handle_reset,"ax",@progbits + .weak handle_reset + .align 1 +handle_reset: +.option push +.option norelax + la gp, __global_pointer$ +.option pop +1: + la sp, _eusrstack +2: +/* Load data section from flash to RAM */ + la a0, _data_lma + la a1, _data_vma + la a2, _edata + bgeu a1, a2, 2f +1: + lw t0, (a0) + sw t0, (a1) + addi a0, a0, 4 + addi a1, a1, 4 + bltu a1, a2, 1b + +2: +/* Clear bss section */ + la a0, _sbss + la a1, _ebss + bgeu a0, a1, 2f +1: + sw zero, (a0) + addi a0, a0, 4 + bltu a0, a1, 1b + +2: +/* Configure pipelining and instruction prediction */ + li t0, 0x1f + csrw 0xbc0, t0 +/* Enable interrupt nesting and hardware stack */ + li t0, 0x3 + csrw 0x804, t0 +/* Enable global interrupt and configure privileged mode */ + li t0, 0x1888 + csrw mstatus, t0 +/* Configure the interrupt vector table recognition mode and entry address mode */ + la t0, _vector_base + ori t0, t0, 3 + csrw mtvec, t0 + +/*Enable the cache to cache the code from __cache_beg to _cache_end */ + /* PMP TOR(pmpaddr0 - pmpaddr1) */ + la t0, _cache_beg + srli t0, t0, 2 + csrw pmpaddr0, t0 + + la t0, _cache_end + srli t0, t0, 2 + csrw pmpaddr1, t0 + + li t0, 0x10 + csrw 0xbc3, t0 + + li t0, 0xAD00 + csrw 0x3a0, t0 + + /* Enable ICache */ + li t0, 0x4 + csrw 0xbd0, t0 + li t0, 0x03000002 + csrc 0xbc2, t0 + +/* Comfigure systemclock */ + jal SystemInit +/* Jump main */ + la t0, main + csrw mepc, t0 + mret diff --git a/Startup/startup_ch564_ram_64k.S b/Startup/startup_ch564_ram_64k.S new file mode 100644 index 0000000..dbb5c15 --- /dev/null +++ b/Startup/startup_ch564_ram_64k.S @@ -0,0 +1,240 @@ +;/********************************** (C) COPYRIGHT ******************************* +;* File Name : startup_CH564.S +;* Author : WCH +;* Version : V1.0.0 +;* Date : 2024/05/05 +;* Description : vector table for eclipse toolchain for CH564. +;********************************************************************************* +;* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. +;* Attention: This software (modified or not) and binary are used for +;* microcontroller manufactured by Nanjing Qinheng Microelectronics. +*******************************************************************************/ + + .section .init, "ax", @progbits + .globl _start + .align 2 + +_start: + .option norvc; + j handle_reset + + .section .vector,"ax",@progbits + .align 2 +_vector_base: + .option norvc; + .word _start + .word 0 + .word NMI_Handler + .word HardFault_Handler + .word 0x60000000 + .word Ecall_M_Handler + .word 0 + .word 0 + .word Ecall_U_Handler + .word BreakPoint_Handler + .word 0 + .word 0 + .word SysTick_Handler + .word 0 + .word SW_Handler + .word 0 + /*External Interrupts*/ + .word I2C_EV_IRQHandler + .word I2C_ER_IRQHandler + .word ETH_IRQHandler + .word USBPD_IRQHandler + .word TIM0_IRQHandler + .word TIM1_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word SPI0_IRQHandler + .word SPI1_IRQHandler + .word UART0_IRQHandler + .word UART1_IRQHandler + .word PA_IRQHandler + .word PB_IRQHandler + .word PD_IRQHandler + .word ADC_IRQHandler + .word SLV_IRQHandler + .word USBHS_HOST_IRQHandler + .word USBHS_DEV_IRQHandler + .word UART2_IRQHandler + .word UART3_IRQHandler + .word ETHWakeUp_IRQHandler + .word USBHSWakeUp_IRQHandler + .word USBPDWakeUp_IRQHandler + .word 0x08800513 + .word 0x80051073 + .word 0xe000f537 + .word 0xd1350513 + .word 0x08000593 + .word 0x0ff0000f + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + + .option rvc; + .section .text.vector_handler, "ax", @progbits + .weak NMI_Handler + .weak HardFault_Handler + .weak Ecall_M_Handler + .weak Ecall_U_Handler + .weak BreakPoint_Handler + .weak SysTick_Handler + .weak SW_Handler + .weak I2C_EV_IRQHandler + .weak I2C_ER_IRQHandler + .weak ETH_IRQHandler + .weak USBPD_IRQHandler + .weak TIM0_IRQHandler + .weak TIM1_IRQHandler + .weak TIM2_IRQHandler + .weak TIM3_IRQHandler + .weak SPI0_IRQHandler + .weak SPI1_IRQHandler + .weak UART0_IRQHandler + .weak UART1_IRQHandler + .weak PA_IRQHandler + .weak PB_IRQHandler + .weak PD_IRQHandler + .weak ADC_IRQHandler + .weak SLV_IRQHandler + .weak USBHS_HOST_IRQHandler + .weak USBHS_DEV_IRQHandler + .weak UART2_IRQHandler + .weak UART3_IRQHandler + .weak ETHWakeUp_IRQHandler + .weak USBHSWakeUp_IRQHandler + .weak USBPDWakeUp_IRQHandler + +NMI_Handler: +HardFault_Handler: +Ecall_M_Handler: +Ecall_U_Handler: +BreakPoint_Handler: +SysTick_Handler: +SW_Handler: +I2C_EV_IRQHandler: +I2C_ER_IRQHandler: +ETH_IRQHandler: +USBPD_IRQHandler: +TIM0_IRQHandler: +TIM1_IRQHandler: +TIM2_IRQHandler: +TIM3_IRQHandler: +SPI0_IRQHandler: +SPI1_IRQHandler: +UART0_IRQHandler: +UART1_IRQHandler: +PA_IRQHandler: +PB_IRQHandler: +PD_IRQHandler: +ADC_IRQHandler: +SLV_IRQHandler: +USBHS_HOST_IRQHandler: +USBHS_DEV_IRQHandler: +UART2_IRQHandler: +UART3_IRQHandler: +ETHWakeUp_IRQHandler: +USBHSWakeUp_IRQHandler: +USBPDWakeUp_IRQHandler: +1: + j 1b + + .section .text.handle_reset,"ax",@progbits + .weak handle_reset + .align 1 +handle_reset: +.option push +.option norelax + la gp, __global_pointer$ +.option pop +1: + la sp, _eusrstack +2: +/* Load data section from flash to RAM */ + la a0, _data_lma + la a1, _data_vma + la a2, _edata + bgeu a1, a2, 2f +1: + lw t0, (a0) + sw t0, (a1) + addi a0, a0, 4 + addi a1, a1, 4 + bltu a1, a2, 1b + +2: +/* Clear bss section */ + la a0, _sbss + la a1, _ebss + bgeu a0, a1, 2f +1: + sw zero, (a0) + addi a0, a0, 4 + bltu a0, a1, 1b + +2: +/* Configure pipelining and instruction prediction */ + li t0, 0x1f + csrw 0xbc0, t0 +/* Enable interrupt nesting and hardware stack */ + li t0, 0x3 + csrw 0x804, t0 +/* Enable global interrupt and configure privileged mode */ + li t0, 0x1888 + csrw mstatus, t0 +/* Configure the interrupt vector table recognition mode and entry address mode */ + la t0, _vector_base + ori t0, t0, 3 + csrw mtvec, t0 + +/*Enable the cache to cache the code from __cache_beg to _cache_end */ + /* PMP TOR(pmpaddr0 - pmpaddr1) */ + la t0, _cache_beg + srli t0, t0, 2 + csrw pmpaddr0, t0 + + la t0, _cache_end + srli t0, t0, 2 + csrw pmpaddr1, t0 + + li t0, 0x10 + csrw 0xbc3, t0 + + li t0, 0xAD00 + csrw 0x3a0, t0 + + /* Enable ICache */ + li t0, 0x4 + csrw 0xbd0, t0 + li t0, 0x03000002 + csrc 0xbc2, t0 + +/* Comfigure systemclock */ + jal SystemInit +/* Jump main */ + la t0, main + csrw mepc, t0 + mret diff --git a/Startup/startup_ch564_ram_96k.S b/Startup/startup_ch564_ram_96k.S new file mode 100644 index 0000000..0e73dcb --- /dev/null +++ b/Startup/startup_ch564_ram_96k.S @@ -0,0 +1,240 @@ +;/********************************** (C) COPYRIGHT ******************************* +;* File Name : startup_CH564.S +;* Author : WCH +;* Version : V1.0.0 +;* Date : 2024/05/05 +;* Description : vector table for eclipse toolchain for CH564. +;********************************************************************************* +;* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. +;* Attention: This software (modified or not) and binary are used for +;* microcontroller manufactured by Nanjing Qinheng Microelectronics. +*******************************************************************************/ + + .section .init, "ax", @progbits + .globl _start + .align 2 + +_start: + .option norvc; + j handle_reset + + .section .vector,"ax",@progbits + .align 2 +_vector_base: + .option norvc; + .word _start + .word 0 + .word NMI_Handler + .word HardFault_Handler + .word 0x50000000 + .word Ecall_M_Handler + .word 0 + .word 0 + .word Ecall_U_Handler + .word BreakPoint_Handler + .word 0 + .word 0 + .word SysTick_Handler + .word 0 + .word SW_Handler + .word 0 + /*External Interrupts*/ + .word I2C_EV_IRQHandler + .word I2C_ER_IRQHandler + .word ETH_IRQHandler + .word USBPD_IRQHandler + .word TIM0_IRQHandler + .word TIM1_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word SPI0_IRQHandler + .word SPI1_IRQHandler + .word UART0_IRQHandler + .word UART1_IRQHandler + .word PA_IRQHandler + .word PB_IRQHandler + .word PD_IRQHandler + .word ADC_IRQHandler + .word SLV_IRQHandler + .word USBHS_HOST_IRQHandler + .word USBHS_DEV_IRQHandler + .word UART2_IRQHandler + .word UART3_IRQHandler + .word ETHWakeUp_IRQHandler + .word USBHSWakeUp_IRQHandler + .word USBPDWakeUp_IRQHandler + .word 0x08800513 + .word 0x80051073 + .word 0xe000f537 + .word 0xd1350513 + .word 0x08000593 + .word 0x0ff0000f + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + .word 0x00b50023 + + + .option rvc; + .section .text.vector_handler, "ax", @progbits + .weak NMI_Handler + .weak HardFault_Handler + .weak Ecall_M_Handler + .weak Ecall_U_Handler + .weak BreakPoint_Handler + .weak SysTick_Handler + .weak SW_Handler + .weak I2C_EV_IRQHandler + .weak I2C_ER_IRQHandler + .weak ETH_IRQHandler + .weak USBPD_IRQHandler + .weak TIM0_IRQHandler + .weak TIM1_IRQHandler + .weak TIM2_IRQHandler + .weak TIM3_IRQHandler + .weak SPI0_IRQHandler + .weak SPI1_IRQHandler + .weak UART0_IRQHandler + .weak UART1_IRQHandler + .weak PA_IRQHandler + .weak PB_IRQHandler + .weak PD_IRQHandler + .weak ADC_IRQHandler + .weak SLV_IRQHandler + .weak USBHS_HOST_IRQHandler + .weak USBHS_DEV_IRQHandler + .weak UART2_IRQHandler + .weak UART3_IRQHandler + .weak ETHWakeUp_IRQHandler + .weak USBHSWakeUp_IRQHandler + .weak USBPDWakeUp_IRQHandler + +NMI_Handler: +HardFault_Handler: +Ecall_M_Handler: +Ecall_U_Handler: +BreakPoint_Handler: +SysTick_Handler: +SW_Handler: +I2C_EV_IRQHandler: +I2C_ER_IRQHandler: +ETH_IRQHandler: +USBPD_IRQHandler: +TIM0_IRQHandler: +TIM1_IRQHandler: +TIM2_IRQHandler: +TIM3_IRQHandler: +SPI0_IRQHandler: +SPI1_IRQHandler: +UART0_IRQHandler: +UART1_IRQHandler: +PA_IRQHandler: +PB_IRQHandler: +PD_IRQHandler: +ADC_IRQHandler: +SLV_IRQHandler: +USBHS_HOST_IRQHandler: +USBHS_DEV_IRQHandler: +UART2_IRQHandler: +UART3_IRQHandler: +ETHWakeUp_IRQHandler: +USBHSWakeUp_IRQHandler: +USBPDWakeUp_IRQHandler: +1: + j 1b + + .section .text.handle_reset,"ax",@progbits + .weak handle_reset + .align 1 +handle_reset: +.option push +.option norelax + la gp, __global_pointer$ +.option pop +1: + la sp, _eusrstack +2: +/* Load data section from flash to RAM */ + la a0, _data_lma + la a1, _data_vma + la a2, _edata + bgeu a1, a2, 2f +1: + lw t0, (a0) + sw t0, (a1) + addi a0, a0, 4 + addi a1, a1, 4 + bltu a1, a2, 1b + +2: +/* Clear bss section */ + la a0, _sbss + la a1, _ebss + bgeu a0, a1, 2f +1: + sw zero, (a0) + addi a0, a0, 4 + bltu a0, a1, 1b + +2: +/* Configure pipelining and instruction prediction */ + li t0, 0x1f + csrw 0xbc0, t0 +/* Enable interrupt nesting and hardware stack */ + li t0, 0x3 + csrw 0x804, t0 +/* Enable global interrupt and configure privileged mode */ + li t0, 0x1888 + csrw mstatus, t0 +/* Configure the interrupt vector table recognition mode and entry address mode */ + la t0, _vector_base + ori t0, t0, 3 + csrw mtvec, t0 +/*Enable the cache to cache the code from _cache_beg to _cache_end */ + /* PMP TOR(pmpaddr0 - pmpaddr1) */ + la t0, _cache_beg + srli t0, t0, 2 + csrw pmpaddr0, t0 + + la t0, _cache_end + srli t0, t0, 2 + csrw pmpaddr1, t0 + + li t0, 0x10 + csrw 0xbc3, t0 + + li t0, 0xAD00 + csrw 0x3a0, t0 + + /* Enable ICache */ + li t0, 0x4 + csrw 0xbd0, t0 + li t0, 0x03000002 + csrc 0xbc2, t0 + +/* Comfigure systemclock */ + jal SystemInit +/* Jump main */ + la t0, main + csrw mepc, t0 + mret diff --git a/User/includes.h b/User/includes.h new file mode 100644 index 0000000..7ca538c --- /dev/null +++ b/User/includes.h @@ -0,0 +1,40 @@ +/* + * includes.h + * + * Created on: May 14, 2025 + * Author: cc + */ + +#ifndef USER_INCLUDES_H_ +#define USER_INCLUDES_H_ + +#include +#include "ch564.h" +#include "system_ch564.h" + +#include "debug.h" +#include "uart.h" +#include "led.h" +#include "timer.h" +#include "spi_sram.h" +#include "spi_flash.h" +#include "rw_logging.h" +#include "log_api.h" +#include "sram_mem_addr.h" +#include "flash_mem_addr.h" +#include "rtc.h" +#include "mcu_flash.h" + +/*Ƽ汾 + ˶ÿб붨壬ʶǰ̶ӦĻ + BootлͨȡEEPROMб豸Ϣжϵǰʲô + EEPROM ûб豸ϢôǰBoot豸ַΪ0x00豸Ϊ0x00 +*/ +#define Project_Area 0x01 //ΪBoot 0x01:Boot0x02:APP +#define Peoject_Name "BLV_C1P_Bootload" // +#define Project_FW_Version 0x01 //̶Ӧ汾 +#define Project_Type 0x00 //̶Ӧ豸 BootĬ豸 + + + +#endif /* USER_INCLUDES_H_ */ diff --git a/User/main.c b/User/main.c new file mode 100644 index 0000000..7b57cfe --- /dev/null +++ b/User/main.c @@ -0,0 +1,185 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : main.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : Main program body. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ + +#include "includes.h" +#include +#include + +uint32_t test_tick = 0; + +/********************************************************************* + * @fn main + * + * @brief Main program. + * + * @return none + */ +int main(void) +{ + uint8_t sys_reset = 0; + uint32_t wdt_reste_tick = 0; + unsigned char Buffer; + + unsigned long DATA_ROM_ADDR; + + SystemCoreClockUpdate(); //ϵͳʼ + Systick_Init(); + + UARTx_Init(UART_0,512000); + UARTx_Init(UART_1,512000); + UARTx_Init(UART_2,512000); + UARTx_Init(UART_3,512000); + + SYS_LED_Init(); + + SPI_SRAM_Init(); + + SPI_FLASH_Init(); + + Get_Flash_Size(&Buffer); + + if(Buffer){ + DATA_ROM_ADDR = 0x70000; + }else { + DATA_ROM_ADDR = 0x30000; + } + + DBG_SYS_Printf("RTC_Init \r\n"); + + RTC_Init(); + + DBG_SYS_Printf("EEPROM_Init - DATA_ROM_ADDR:%x\r\n",DATA_ROM_ADDR); + + EEPROM_Init(); + + DBG_SYS_Printf("G PARA \r\n"); + + memset((uint8_t *)&g_app_feature,0,sizeof(G_SYS_FEATURE_T)); + memset((uint8_t *)&g_mcu_app_feature,0,sizeof(G_SYS_FEATURE_T)); + memset((uint8_t *)&g_update_recode,0,sizeof(UPDATE_RECORD_T)); + + DBG_SYS_Printf("G_SYS_FEATURE_T : %d \r\n",sizeof(G_SYS_FEATURE_T)); + + sys_reset = RCC_GET_GLOB_RST_KEEP(); + if(sys_reset == 0x00) + { + DBG_SYS_Printf("ϵ縴λ \r\n"); + }else if(sys_reset == 0x02){ + + DBG_SYS_Printf("Źλ \r\n"); + }else { + DBG_SYS_Printf("λ \r\n"); + } + + RCC_SET_GLOB_RST_KEEP(0x01); + g_jump_flag = Read_APP_Feature(); + + //ʹõ - ״̬ + if(g_jump_flag == 2) { + MCU_APP_Write(); //MCUҪд + g_jump_flag = 0; + +// printf("Jump APP 1\r\n"); +// +// Delay_Ms(1000); +// +// __disable_irq(); +// Jump_APP(g_mcu_app_feature.app_start_addr); + + NVIC_EnableIRQ( Software_IRQn ); + Delay_Ms( 20 ); + NVIC_SetPendingIRQ( Software_IRQn ); + } + + while (1) + { + SYS_LED_Task(); + + Uart0_Task(); + + UART1_RECEIVE(); + UART2_RECEIVE(); + UART3_RECEIVE(); + + RTC_TASK(); + + //ʹõ - ״̬ + if(SysTick_1ms - g_Boot_Tick >= 5000) + { + g_Boot_Tick = SysTick_1ms; + + if(g_jump_flag == 0x00) //APP УɹתAPP + { + printf("Jump APP 2\r\n"); + + Delay_Ms(1000); + + NVIC_EnableIRQ( Software_IRQn ); + Delay_Ms( 20 ); + NVIC_SetPendingIRQ( Software_IRQn ); + } + } + } +} + +void NMI_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); +void HardFault_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); + +/********************************************************************* + * @fn NMI_Handler + * + * @brief This function handles NMI exception. + * + * @return none + */ +void NMI_Handler(void) +{ + while (1) + { + } +} + +/********************************************************************* + * @fn HardFault_Handler + * + * @brief This function handles Hard Fault exception. + * + * @return none + */ +void HardFault_Handler(void) +{ + /* MRS_HardFault˼· : https://www.cnblogs.com/wchmcu/p/17545931.html */ + uint32_t v_mepc,v_mcause,v_mtval; + //Dbg_Println(DBG_BIT_SYS_STATUS_bit,"hardfault\n"); + + v_mepc = __get_MEPC(); + v_mcause = __get_MCAUSE(); + v_mtval = __get_MTVAL(); + + printf("boot mepc:%x\n",v_mepc); + printf("boot mcause:%x\n",v_mcause); + printf("boot mtval:%x\n",v_mtval); + + while(1); +} + +void SW_Handler(void) { + printf("SW_Handler Jump App\r\n"); + Delay_Ms( 100 ); + + __disable_irq(); + __asm volatile("li a6, 0x07000"); + __asm volatile("jr a6"); + while(1); + +} + diff --git a/User/system_ch564.c b/User/system_ch564.c new file mode 100644 index 0000000..89ad31a --- /dev/null +++ b/User/system_ch564.c @@ -0,0 +1,420 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : system_ch564.c + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : CH564 Device Peripheral Access Layer System Source File. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ + +#include "ch564.h" +#include "debug.h" + +/* + * Uncomment the line corresponding to the desired System clock (SYSCLK) + * frequency (after reset the HSI is used as SYSCLK source). + */ + +#define SYSCLK_FREQ_120MHz_HSI 120000000 +//#define SYSCLK_FREQ_80MHz_HSI 80000000 +//#define SYSCLK_FREQ_60MHz_HSI 60000000 +//#define SYSCLK_FREQ_40MHz_HSI 40000000 +//#define SYSCLK_FREQ_20MHz_HSI HSI_VALUE +//#define SYSCLK_FREQ_120MHz_HSE 120000000 +//#define SYSCLK_FREQ_80MHz_HSE 80000000 +//#define SYSCLK_FREQ_60MHz_HSE 60000000 +//#define SYSCLK_FREQ_40MHz_HSE 40000000 +//#define SYSCLK_FREQ_25MHz_HSE HSE_VALUE + +/* Clock Definitions */ +#ifdef SYSCLK_FREQ_120MHz_HSI +uint32_t SystemCoreClock = SYSCLK_FREQ_120MHz_HSI; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_80MHz_HSI +uint32_t SystemCoreClock = SYSCLK_FREQ_80MHz_HSI; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_60MHz_HSI +uint32_t SystemCoreClock = SYSCLK_FREQ_60MHz_HSI; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_40MHz_HSI +uint32_t SystemCoreClock = SYSCLK_FREQ_40MHz_HSI; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_20MHz_HSI +uint32_t SystemCoreClock = SYSCLK_FREQ_20MHz_HSI; /* System Clock Frequency (Core Clock) */ + +#elif defined SYSCLK_FREQ_120MHz_HSE +uint32_t SystemCoreClock = SYSCLK_FREQ_120MHz_HSE; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_80MHz_HSE +uint32_t SystemCoreClock = SYSCLK_FREQ_80MHz_HSE; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_60MHz_HSE +uint32_t SystemCoreClock = SYSCLK_FREQ_60MHz_HSE; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_40MHz_HSE +uint32_t SystemCoreClock = SYSCLK_FREQ_40MHz_HSE; /* System Clock Frequency (Core Clock) */ +#elif defined SYSCLK_FREQ_25MHz_HSE +uint32_t SystemCoreClock = SYSCLK_FREQ_25MHz_HSE; /* System Clock Frequency (Core Clock) */ +#endif + +/* system_private_function_proto_types */ +static void SetSysClock(void); + +#ifdef SYSCLK_FREQ_120MHz_HSI +static void SetSysClockTo120_HSI(void); +#elif defined SYSCLK_FREQ_80MHz_HSI +static void SetSysClockTo80_HSI(void); +#elif defined SYSCLK_FREQ_60MHz_HSI +static void SetSysClockTo60_HSI(void); +#elif defined SYSCLK_FREQ_40MHz_HSI +static void SetSysClockTo40_HSI(void); +#elif defined SYSCLK_FREQ_20MHz_HSI +static void SetSysClockTo20_HSI(void); +#elif defined SYSCLK_FREQ_120MHz_HSE +static void SetSysClockTo120_HSE(void); +#elif defined SYSCLK_FREQ_80MHz_HSE +static void SetSysClockTo80_HSE(void); +#elif defined SYSCLK_FREQ_60MHz_HSE +static void SetSysClockTo60_HSE(void); +#elif defined SYSCLK_FREQ_40MHz_HSE +static void SetSysClockTo40_HSE(void); +#elif defined SYSCLK_FREQ_25MHz_HSE +static void SetSysClockTo25_HSE(void); +#endif + +/********************************************************************* + * @fn SystemInit + * + * @brief Setup the microcontroller system Initialize the Embedded Flash + * Interface, update the SystemCoreClock variable. + * + * @return none + */ +void SystemInit(void) +{ + if ( SystemCoreClock >= 60000000 ) + { + RCC_UNLOCK_SAFE_ACCESS(); + BITS_CFG( R32_EXTEN_CTLR0 , RB_FLASH_PRE_EN , ENABLE ); + BITS_CFG( R32_EXTEN_CTLR0 , RB_SW_CFG , DISABLE ); + RCC_LOCK_SAFE_ACCESS(); + } + else + { + RCC_UNLOCK_SAFE_ACCESS(); + BITS_CFG( R32_EXTEN_CTLR0 , RB_FLASH_PRE_EN , DISABLE ); + BITS_CFG( R32_EXTEN_CTLR0 , RB_SW_CFG , DISABLE ); + RCC_LOCK_SAFE_ACCESS(); + } + + SystemCoreClockUpdate(); + + HSI_ON(); + + /* Close ETH PHY */ + RCC_SlpWakeCtrl( RB_SLP_ETH_PWR_DN , DISABLE ); + Delay_Us( PLL_STARTUP_TIME ); + ETH->PHY_CR |= ( 1 << 31 ); + ETH->PHY_CR &= ~( 1 << 30 ); + ETH->PHY_CR |= ( 1 << 30 ); + Delay_Us( HSI_STARTUP_TIME ); + RCC_SlpWakeCtrl( RB_SLP_ETH_PWR_DN , ENABLE ); + + CLKSEL_HSI(); + SYSCLK_SOURCE_SELECT( SYSCLK_SOURCE_HSI_HSE ); + USB_PLL_OFF(); + SetSysClock(); +} + +/********************************************************************* + * @fn SystemCoreClockUpdate + * + * @brief Update SystemCoreClock variable according to Clock Register Values. + * + * @return none + */ +void SystemCoreClockUpdate(void) +{ + uint32_t tmp = 0; + + if ( R32_EXTEN_CTLR0 & RB_SW ) + { + if ( R32_EXTEN_CTLR1 & RB_CLKSEL ) + { + tmp = HSE_Value; + } + else + { + tmp = HSI_Value; + } + } + else + { + switch ( R32_EXTEN_CTLR0 & RB_USBPLLSRC ) + { + case 0x60: + tmp = HSI_Value; + break; + case 0x20: + tmp = HSE_Value; + break; + default: + tmp = HSE_Value * 20 / 25; + break; + } + + switch ( R32_EXTEN_CTLR0 & RB_USBPLLCLK ) + { + case 0x0: + tmp *= 24; + break; + case 0x4000: + tmp *= 20; + break; + case 0x8000: + tmp *= 16; + break; + case 0xC000: + tmp *= 15; + break; + default: + break; + } + tmp /= ( R8_PLL_OUT_DIV >> 4 ) + 1; + } + + SystemCoreClock = tmp; +} + +/********************************************************************* + * @fn SetSysClock + * + * @brief Configures the System clock frequency, HCLK prescalers. + * + * @return none + */ +static void SetSysClock(void) +{ + SystemCoreClockUpdate(); + GPIO_IPD_Unused(); + +#ifdef SYSCLK_FREQ_120MHz_HSI + SetSysClockTo120_HSI(); +#elif defined SYSCLK_FREQ_80MHz_HSI + SetSysClockTo80_HSI(); +#elif defined SYSCLK_FREQ_60MHz_HSI + SetSysClockTo60_HSI(); +#elif defined SYSCLK_FREQ_40MHz_HSI + SetSysClockTo40_HSI(); +#elif defined SYSCLK_FREQ_20MHz_HSI + SetSysClockTo20_HSI(); +#elif defined SYSCLK_FREQ_120MHz_HSE + SetSysClockTo120_HSE(); +#elif defined SYSCLK_FREQ_80MHz_HSE + SetSysClockTo80_HSE(); +#elif defined SYSCLK_FREQ_60MHz_HSE + SetSysClockTo60_HSE(); +#elif defined SYSCLK_FREQ_40MHz_HSE + SetSysClockTo40_HSE(); +#elif defined SYSCLK_FREQ_25MHz_HSE + SetSysClockTo25_HSE(); +#endif +} + +#ifdef SYSCLK_FREQ_120MHz_HSI + +/********************************************************************* + * @fn SetSysClockTo120_HSI + * + * @brief Sets System clock frequency to 120MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo120_HSI(void) +{ + RCC_SET_PLL_SYS_OUT_DIV( 0x3 ); + USB_PLL_MUL_SELECT( USB_PLL_MUL_24 ); + USB_PLL_SOURCE_SELECT( USB_PLL_SOURCE_HSI ); + USB_PLL_ON(); + Delay_Us( PLL_STARTUP_TIME ); + SYSCLK_SOURCE_SELECT( SYSCLK_SOURCE_USBPLL ); +} + +#elif defined SYSCLK_FREQ_80MHz_HSI + +/********************************************************************* + * @fn SetSysClockTo80_HSI + * + * @brief Sets System clock frequency to 80MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo80_HSI(void) +{ + RCC_SET_PLL_SYS_OUT_DIV(0x5); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_HSI); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_60MHz_HSI + +/********************************************************************* + * @fn SetSysClockTo60_HSI + * + * @brief Sets System clock frequency to 60MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo60_HSI(void) +{ + RCC_SET_PLL_SYS_OUT_DIV(0x7); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_HSI); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_40MHz_HSI + +/********************************************************************* + * @fn SetSysClockTo8_HSI + * + * @brief Sets System clock frequency to 40MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo40_HSI(void) +{ + RCC_SET_PLL_SYS_OUT_DIV( 0xB ); + USB_PLL_MUL_SELECT( USB_PLL_MUL_24 ); + USB_PLL_SOURCE_SELECT( USB_PLL_SOURCE_HSI ); + USB_PLL_ON(); + Delay_Us( PLL_STARTUP_TIME ); + SYSCLK_SOURCE_SELECT( SYSCLK_SOURCE_USBPLL ); +} + +#elif defined SYSCLK_FREQ_20MHz_HSI + +/********************************************************************* + * @fn SetSysClockTo20_HSI + * + * @brief Sets System clock frequency to 20MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo20_HSI(void) +{ + CLKSEL_HSI(); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_HSI_HSE); +} + +#elif defined SYSCLK_FREQ_120MHz_HSE + +/********************************************************************* + * @fn SetSysClockTo120_HSE + * + * @brief Sets System clock frequency to 24MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo120_HSE(void) +{ + HSE_ON(); + Delay_Us(HSE_STARTUP_TIME); + RCC_SlpWakeCtrl(RB_SLP_ETH_PWR_DN, DISABLE); + RCC_SET_PLL_SYS_OUT_DIV(0x3); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_ETH_PLL_OUT); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_80MHz_HSE + +/********************************************************************* + * @fn SetSysClockTo80_HSE + * + * @brief Sets System clock frequency to 80MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo80_HSE(void) +{ + HSE_ON(); + Delay_Us(HSE_STARTUP_TIME); + RCC_SlpWakeCtrl(RB_SLP_ETH_PWR_DN, DISABLE); + RCC_SET_PLL_SYS_OUT_DIV(0x5); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_ETH_PLL_OUT); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_60MHz_HSE + +/********************************************************************* + * @fn SetSysClockTo60_HSE + * + * @brief Sets System clock frequency to 60MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo60_HSE(void) +{ + HSE_ON(); + Delay_Us(HSE_STARTUP_TIME); + RCC_SlpWakeCtrl(RB_SLP_ETH_PWR_DN, DISABLE); + RCC_SET_PLL_SYS_OUT_DIV(0x7); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_ETH_PLL_OUT); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_40MHz_HSE + +/********************************************************************* + * @fn SetSysClockTo40_HSE + * + * @brief Sets System clock frequency to 40MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo40_HSE(void) +{ + HSE_ON(); + Delay_Us(HSE_STARTUP_TIME); + RCC_SlpWakeCtrl(RB_SLP_ETH_PWR_DN, DISABLE); + RCC_SET_PLL_SYS_OUT_DIV(0xB); + USB_PLL_SOURCE_SELECT(USB_PLL_SOURCE_ETH_PLL_OUT); + USB_PLL_MUL_SELECT(USB_PLL_MUL_24); + USB_PLL_ON(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_USBPLL); +} + +#elif defined SYSCLK_FREQ_25MHz_HSE + +/********************************************************************* + * @fn SetSysClockTo25_HSE + * + * @brief Sets System clock frequency to 25MHz and configure HCLK prescalers. + * + * @return none + */ +static void SetSysClockTo25_HSE(void) +{ + HSE_ON(); + Delay_Us(HSE_STARTUP_TIME); + CLKSEL_HSE(); + SystemCoreClock = HSE_VALUE; + Delay_Init(); + Delay_Us(PLL_STARTUP_TIME); + SYSCLK_SOURCE_SELECT(SYSCLK_SOURCE_HSI_HSE); + +} + +#endif diff --git a/User/system_ch564.h b/User/system_ch564.h new file mode 100644 index 0000000..e348849 --- /dev/null +++ b/User/system_ch564.h @@ -0,0 +1,30 @@ +/********************************** (C) COPYRIGHT ******************************* + * File Name : system_ch564.h + * Author : WCH + * Version : V1.0.0 + * Date : 2024/05/05 + * Description : CH564 Device Peripheral Access Layer System Header File. + ********************************************************************************* + * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. + * Attention: This software (modified or not) and binary are used for + * microcontroller manufactured by Nanjing Qinheng Microelectronics. + *******************************************************************************/ +#ifndef __SYSTEM_CH564_H +#define __SYSTEM_CH564_H + +#ifdef __cplusplus +extern "C" { +#endif + +extern uint32_t SystemCoreClock; /* System Clock Frequency (Core Clock) */ + +/* System_Exported_Functions */ +extern void SystemInit(void); +extern void SystemCoreClockUpdate(void); + +#ifdef __cplusplus +} +#endif + +#endif +