| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| RST | Reserved | WOL | PB | PPPoE | Reserved | FARP | Reserved |
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| CONFLICT | UNREACH | PPPoE | MP | Reserved | Reserved | Reserved | Reserved |
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| IM_IR7 | IM_IR6 | IM_IR5 | IM_IR4 | Reserved | Reserved | Reserved | Reserved |
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| MULTI/MFEN | BCASTB | ND/MC/MMB | UCASTB/MIP6B | Protocol[3] | Protocol[2] | Protocol[1] | Protocol[0] |
| Protocol[3] | Protocol[2] | Protocol[1] | Protocol[0] | @b Meaning |
| 0 | 0 | 0 | 0 | Closed |
| 0 | 0 | 0 | 1 | TCP |
| 0 | 0 | 1 | 0 | UDP |
| 0 | 1 | 0 | 0 | MACRAW |
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| Reserved | Reserved | Reserved | SEND_OK | TIMEOUT | RECV | DISCON | CON |
| \b Sn_MR (P[3:0]) | \b Sn_SR |
| Sn_MR_CLOSE (000) | |
| Sn_MR_TCP (001) | SOCK_INIT (0x13) |
| Sn_MR_UDP (010) | SOCK_UDP (0x22) |
| S0_MR_MACRAW (100) | SOCK_MACRAW (0x02) |
| API | WIZnet | Berkeley |
| socket() | O | O |
| bind() | X | O |
| listen() | O | O |
| connect() | O | O |
| accept() | X | O |
| recv() | O | O |
| send() | O | O |
| recvfrom() | O | O |
| sendto() | O | O |
| closesocket() | O close() & disconnect() | O |
| @b cstype | @b data type | @b value |
| @ref CS_SET_IOMODE \n @ref CS_GET_IOMODE | uint8_t | @ref SOCK_IO_BLOCK @ref SOCK_IO_NONBLOCK |
| @ref CS_GET_MAXTXBUF \n @ref CS_GET_MAXRXBUF | uint16_t | 0 ~ 16K |
| @ref CS_CLR_INTERRUPT \n @ref CS_GET_INTERRUPT \n @ref CS_SET_INTMASK \n @ref CS_GET_INTMASK | @ref sockint_kind | @ref SIK_CONNECTED, etc. |
| @b sotype | @b data type | @b value |
| @ref SO_TTL | uint8_t | 0 ~ 255 |
| @ref SO_TOS | uint8_t | 0 ~ 255 |
| @ref SO_MSS | uint16_t | 0 ~ 65535 |
| @ref SO_DESTIP | uint8_t[4] | |
| @ref SO_DESTPORT | uint16_t | 0 ~ 65535 |
| @ref SO_KEEPALIVESEND | null | null |
| @ref SO_KEEPALIVEAUTO | uint8_t | 0 ~ 255 |
| @b sotype | @b data type | @b value |
| @ref SO_FLAG | uint8_t | @ref SF_ETHER_OWN, etc... |
| @ref SO_TOS | uint8_t | 0 ~ 255 |
| @ref SO_MSS | uint16_t | 0 ~ 65535 |
| @ref SO_DESTIP | uint8_t[4] | |
| @ref SO_DESTPORT | uint16_t | |
| @ref SO_KEEPALIVEAUTO | uint8_t | 0 ~ 255 |
| @ref SO_SENDBUF | uint16_t | 0 ~ 65535 |
| @ref SO_RECVBUF | uint16_t | 0 ~ 65535 |
| @ref SO_STATUS | uint8_t | @ref SOCK_ESTABLISHED, etc.. |
| @ref SO_REMAINSIZE | uint16_t | 0~ 65535 |
| @ref SO_PACKINFO | uint8_t | @ref PACK_FIRST, etc... |
#define \_WIZCHIP_ W5500
+ */
+
+#define W5100 5100
+#define W5100S 5100+5
+#define W5200 5200
+#define W5300 5300
+#define W5500 5500
+
+#ifndef _WIZCHIP_
+#define _WIZCHIP_ W5500 // W5100, W5100S, W5200, W5300, W5500
+#endif
+
+#define _WIZCHIP_IO_MODE_NONE_ 0x0000
+#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */
+#define _WIZCHIP_IO_MODE_SPI_ 0x0200 /**< SPI interface mode */
+//#define _WIZCHIP_IO_MODE_IIC_ 0x0400
+//#define _WIZCHIP_IO_MODE_SDIO_ 0x0800
+// Add to
+//
+
+#define _WIZCHIP_IO_MODE_BUS_DIR_ (_WIZCHIP_IO_MODE_BUS_ + 1) /**< BUS interface mode for direct */
+#define _WIZCHIP_IO_MODE_BUS_INDIR_ (_WIZCHIP_IO_MODE_BUS_ + 2) /**< BUS interface mode for indirect */
+
+#define _WIZCHIP_IO_MODE_SPI_VDM_ (_WIZCHIP_IO_MODE_SPI_ + 1) /**< SPI interface mode for variable length data*/
+#define _WIZCHIP_IO_MODE_SPI_FDM_ (_WIZCHIP_IO_MODE_SPI_ + 2) /**< SPI interface mode for fixed length data mode*/
+#define _WIZCHIP_IO_MODE_SPI_5500_ (_WIZCHIP_IO_MODE_SPI_ + 3) /**< SPI interface mode for fixed length data mode*/
+
+#if (_WIZCHIP_ == W5100)
+ #define _WIZCHIP_ID_ "W5100\0"
+/**
+ * @brief Define interface mode.
+ * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
+ */
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_
+
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
+//A20150401 : Indclude W5100.h file
+ #include "W5100/w5100.h"
+
+#elif (_WIZCHIP_ == W5100S)
+#define _WIZCHIP_ID_ "W5100S\0"
+/**
+* @brief Define interface mode.
+* @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
+*/
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
+ //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_5500_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_
+
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
+//A20150401 : Indclude W5100.h file
+ #include "W5100S/w5100s.h"
+#elif (_WIZCHIP_ == W5200)
+ #define _WIZCHIP_ID_ "W5200\0"
+/**
+ * @brief Define interface mode.
+ * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \ _WIZCHIP_IO_MODE_BUS_INDIR_
+ */
+#ifndef _WIZCHIP_IO_MODE_
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_
+#endif
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
+ #include "W5200/w5200.h"
+#elif (_WIZCHIP_ == W5500)
+ #define _WIZCHIP_ID_ "W5500\0"
+
+/**
+ * @brief Define interface mode. \n
+ * @todo Should select interface mode as chip.
+ * - @ref \_WIZCHIP_IO_MODE_SPI_ \n
+ * -@ref \_WIZCHIP_IO_MODE_SPI_VDM_ : Valid only in @ref \_WIZCHIP_ == W5500 \n
+ * -@ref \_WIZCHIP_IO_MODE_SPI_FDM_ : Valid only in @ref \_WIZCHIP_ == W5500 \n
+ * - @ref \_WIZCHIP_IO_MODE_BUS_ \n
+ * - @ref \_WIZCHIP_IO_MODE_BUS_DIR_ \n
+ * - @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ \n
+ * - Others will be defined in future. \n\n
+ * ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_
+ *
+ */
+#ifndef _WIZCHIP_IO_MODE_
+ //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_
+#endif
+//A20150601 : Define the unit of IO DATA.
+ typedef uint8_t iodata_t;
+ #include "W5500/w5500.h"
+#elif ( _WIZCHIP_ == W5300)
+ #define _WIZCHIP_ID_ "W5300\0"
+/**
+ * @brief Define interface mode.
+ * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_
+ */
+#ifndef _WIZCHIP_IO_MODE_
+ #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_
+// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_
+#endif
+
+//A20150601 : Define the unit and bus width of IO DATA.
+ /**
+ * @brief Select the data width 8 or 16 bits.
+ * @todo you should select the bus width. Select one of 8 or 16.
+ */
+ #ifndef _WIZCHIP_IO_BUS_WIDTH_
+ #define _WIZCHIP_IO_BUS_WIDTH_ 16 // 8
+ #endif
+ #if _WIZCHIP_IO_BUS_WIDTH_ == 8
+ typedef uint8_t iodata_t;
+ #elif _WIZCHIP_IO_BUS_WIDTH_ == 16
+ typedef uint16_t iodata_t;
+ #else
+ #error "Unknown _WIZCHIP_IO_BUS_WIDTH_. It should be 8 or 16."
+ #endif
+//
+ #include "W5300/w5300.h"
+#else
+ #error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!"
+#endif
+
+#ifndef _WIZCHIP_IO_MODE_
+ #error "Undefined _WIZCHIP_IO_MODE_. You should define it !!!"
+#endif
+
+/**
+ * @brief Define I/O base address when BUS IF mode.
+ * @todo Should re-define it to fit your system when BUS IF Mode (@ref \_WIZCHIP_IO_MODE_BUS_,
+ * @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n
+ * ex> #define \_WIZCHIP_IO_BASE_ 0x00008000
+ */
+#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_
+// #define _WIZCHIP_IO_BASE_ 0x60000000 // for 5100S IND
+ #define _WIZCHIP_IO_BASE_ 0x68000000 // for W5300
+#elif _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_SPI_
+ #define _WIZCHIP_IO_BASE_ 0x00000000 // for 5100S SPI
+#endif
+
+#ifndef _WIZCHIP_IO_BASE_
+#define _WIZCHIP_IO_BASE_ 0x00000000 // 0x8000
+#endif
+
+//M20150401 : Typing Error
+//#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS
+#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_
+ #ifndef _WIZCHIP_IO_BASE_
+ #error "You should be define _WIZCHIP_IO_BASE to fit your system memory map."
+ #endif
+#endif
+
+#if _WIZCHIP_ >= W5200
+ #define _WIZCHIP_SOCK_NUM_ 8 ///< The count of independant socket of @b WIZCHIP
+#else
+ #define _WIZCHIP_SOCK_NUM_ 4 ///< The count of independant socket of @b WIZCHIP
+#endif
+
+
+/********************************************************
+* WIZCHIP BASIC IF functions for SPI, SDIO, I2C , ETC.
+*********************************************************/
+/**
+ * @ingroup DATA_TYPE
+ * @brief The set of callback functions for W5500:@ref WIZCHIP_IO_Functions W5200:@ref WIZCHIP_IO_Functions_W5200
+ */
+typedef struct __WIZCHIP
+{
+ uint16_t if_mode; ///< host interface mode
+ uint8_t id[8]; ///< @b WIZCHIP ID such as @b 5100, @b 5100S, @b 5200, @b 5500, and so on.
+ /**
+ * The set of critical section callback func.
+ */
+ struct _CRIS
+ {
+ void (*_enter) (void); ///< crtical section enter
+ void (*_exit) (void); ///< critial section exit
+ }CRIS;
+ /**
+ * The set of @ref \_WIZCHIP_ select control callback func.
+ */
+ struct _CS
+ {
+ void (*_select) (void); ///< @ref \_WIZCHIP_ selected
+ void (*_deselect)(void); ///< @ref \_WIZCHIP_ deselected
+ }CS;
+ /**
+ * The set of interface IO callback func.
+ */
+ union _IF
+ {
+ /**
+ * For BUS interface IO
+ */
+ //M20156501 : Modify the function name for integrating with W5300
+ //struct
+ //{
+ // uint8_t (*_read_byte) (uint32_t AddrSel);
+ // void (*_write_byte) (uint32_t AddrSel, uint8_t wb);
+ //}BUS;
+ struct
+ {
+ iodata_t (*_read_data) (uint32_t AddrSel);
+ void (*_write_data) (uint32_t AddrSel, iodata_t wb);
+ }BUS;
+
+ /**
+ * For SPI interface IO
+ */
+ struct
+ {
+ uint8_t (*_read_byte) (void);
+ void (*_write_byte) (uint8_t wb);
+ void (*_read_burst) (uint8_t* pBuf, uint16_t len);
+ void (*_write_burst) (uint8_t* pBuf, uint16_t len);
+ }SPI;
+ // To be added
+ //
+ }IF;
+}_WIZCHIP;
+
+extern _WIZCHIP WIZCHIP;
+
+/**
+ * @ingroup DATA_TYPE
+ * WIZCHIP control type enumration used in @ref ctlwizchip().
+ */
+typedef enum
+{
+ CW_RESET_WIZCHIP, ///< Resets WIZCHIP by softly
+ CW_INIT_WIZCHIP, ///< Initializes to WIZCHIP with SOCKET buffer size 2 or 1 dimension array typed uint8_t.
+ CW_GET_INTERRUPT, ///< Get Interrupt status of WIZCHIP
+ CW_CLR_INTERRUPT, ///< Clears interrupt
+ CW_SET_INTRMASK, ///< Masks interrupt
+ CW_GET_INTRMASK, ///< Get interrupt mask
+ CW_SET_INTRTIME, ///< Set interval time between the current and next interrupt.
+ CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt.
+ CW_GET_ID, ///< Gets WIZCHIP name.
+
+//D20150601 : For no modification your application code
+//#if _WIZCHIP_ == W5500
+ CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5500
+ CW_SET_PHYCONF, ///< When PHY configured by internal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000
+ CW_GET_PHYCONF, ///< Get PHY operation mode in internal register. Valid Only W5500
+ CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5500
+ CW_SET_PHYPOWMODE, ///< Set PHY power mode as normal and down when PHYSTATUS.OPMD == 1. Valid Only W5500
+//#endif
+//D20150601 : For no modification your application code
+//#if _WIZCHIP_ == W5200 || _WIZCHIP_ == W5500
+ CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal, Valid Only W5100, W5200
+ CW_GET_PHYLINK ///< Get PHY Link status, Valid Only W5100, W5200
+//#endif
+}ctlwizchip_type;
+
+/**
+ * @ingroup DATA_TYPE
+ * Network control type enumration used in @ref ctlnetwork().
+ */
+typedef enum
+{
+ CN_SET_NETINFO, ///< Set Network with @ref wiz_NetInfo
+ CN_GET_NETINFO, ///< Get Network with @ref wiz_NetInfo
+ CN_SET_NETMODE, ///< Set network mode as WOL, PPPoE, Ping Block, and Force ARP mode
+ CN_GET_NETMODE, ///< Get network mode as WOL, PPPoE, Ping Block, and Force ARP mode
+ CN_SET_TIMEOUT, ///< Set network timeout as retry count and time.
+ CN_GET_TIMEOUT, ///< Get network timeout as retry count and time.
+}ctlnetwork_type;
+
+/**
+ * @ingroup DATA_TYPE
+ * Interrupt kind when CW_SET_INTRRUPT, CW_GET_INTERRUPT, CW_SET_INTRMASK
+ * and CW_GET_INTRMASK is used in @ref ctlnetwork().
+ * It can be used with OR operation.
+ */
+typedef enum
+{
+#if _WIZCHIP_ == W5500
+ IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500.
+#elif _WIZCHIP_ == W5300
+ IK_FMTU = (1 << 4), ///< Received a ICMP message (Fragment MTU)
+#endif
+
+ IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected
+
+#if _WIZCHIP_ != W5200
+ IK_DEST_UNREACH = (1 << 6), ///< Destination IP & Port Unreachable, No use in W5200
+#endif
+
+ IK_IP_CONFLICT = (1 << 7), ///< IP conflict occurred
+
+ IK_SOCK_0 = (1 << 8), ///< Socket 0 interrupt
+ IK_SOCK_1 = (1 << 9), ///< Socket 1 interrupt
+ IK_SOCK_2 = (1 << 10), ///< Socket 2 interrupt
+ IK_SOCK_3 = (1 << 11), ///< Socket 3 interrupt
+#if _WIZCHIP_ > W5100S
+ IK_SOCK_4 = (1 << 12), ///< Socket 4 interrupt, No use in 5100
+ IK_SOCK_5 = (1 << 13), ///< Socket 5 interrupt, No use in 5100
+ IK_SOCK_6 = (1 << 14), ///< Socket 6 interrupt, No use in 5100
+ IK_SOCK_7 = (1 << 15), ///< Socket 7 interrupt, No use in 5100
+#endif
+
+#if _WIZCHIP_ > W5100S
+ IK_SOCK_ALL = (0xFF << 8) ///< All Socket interrupt
+#else
+ IK_SOCK_ALL = (0x0F << 8) ///< All Socket interrupt
+#endif
+}intr_kind;
+
+#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin
+#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register
+#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting.
+#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation
+#define PHY_SPEED_10 0 ///< Link Speed 10
+#define PHY_SPEED_100 1 ///< Link Speed 100
+#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex
+#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex
+#define PHY_LINK_OFF 0 ///< Link Off
+#define PHY_LINK_ON 1 ///< Link On
+#define PHY_POWER_NORM 0 ///< PHY power normal mode
+#define PHY_POWER_DOWN 1 ///< PHY power down mode
+
+
+#if _WIZCHIP_ == W5100S || _WIZCHIP_ == W5500
+/**
+ * @ingroup DATA_TYPE
+ * It configures PHY configuration when CW_SET PHYCONF or CW_GET_PHYCONF in W5500,
+ * and it indicates the real PHY status configured by HW or SW in all WIZCHIP. \n
+ * Valid only in W5500.
+ */
+typedef struct wiz_PhyConf_t
+{
+ uint8_t by; ///< set by @ref PHY_CONFBY_HW or @ref PHY_CONFBY_SW
+ uint8_t mode; ///< set by @ref PHY_MODE_MANUAL or @ref PHY_MODE_AUTONEGO
+ uint8_t speed; ///< set by @ref PHY_SPEED_10 or @ref PHY_SPEED_100
+ uint8_t duplex; ///< set by @ref PHY_DUPLEX_HALF @ref PHY_DUPLEX_FULL
+ //uint8_t power; ///< set by @ref PHY_POWER_NORM or @ref PHY_POWER_DOWN
+ //uint8_t link; ///< Valid only in CW_GET_PHYSTATUS. set by @ref PHY_LINK_ON or PHY_DUPLEX_OFF
+ }wiz_PhyConf;
+#endif
+
+/**
+ * @ingroup DATA_TYPE
+ * It used in setting dhcp_mode of @ref wiz_NetInfo.
+ */
+typedef enum
+{
+ NETINFO_STATIC = 1, ///< Static IP configuration by manually.
+ NETINFO_DHCP ///< Dynamic IP configruation from a DHCP sever
+}dhcp_mode;
+
+/**
+ * @ingroup DATA_TYPE
+ * Network Information for WIZCHIP
+ */
+typedef struct wiz_NetInfo_t
+{
+ uint8_t mac[6]; ///< Source Mac Address
+ uint8_t ip[4]; ///< Source IP Address
+ uint8_t sn[4]; ///< Subnet Mask
+ uint8_t gw[4]; ///< Gateway IP Address
+ uint8_t dns[4]; ///< DNS server IP Address
+ dhcp_mode dhcp; ///< 1 - Static, 2 - DHCP
+}wiz_NetInfo;
+
+/**
+ * @ingroup DATA_TYPE
+ * Network mode
+ */
+typedef enum
+{
+#if _WIZCHIP_ == W5500
+ NM_FORCEARP = (1<<1), ///< Force to APP send whenever udp data is sent. Valid only in W5500
+#endif
+ NM_WAKEONLAN = (1<<5), ///< Wake On Lan
+ NM_PINGBLOCK = (1<<4), ///< Block ping-request
+ NM_PPPOE = (1<<3), ///< PPPoE mode
+}netmode_type;
+
+/**
+ * @ingroup DATA_TYPE
+ * Used in CN_SET_TIMEOUT or CN_GET_TIMEOUT of @ref ctlwizchip() for timeout configruation.
+ */
+typedef struct wiz_NetTimeout_t
+{
+ uint8_t retry_cnt; ///< retry count
+ uint16_t time_100us; ///< time unit 100us
+}wiz_NetTimeout;
+
+/**
+ *@brief Registers call back function for critical section of I/O functions such as
+ *\ref WIZCHIP_READ, @ref WIZCHIP_WRITE, @ref WIZCHIP_READ_BUF and @ref WIZCHIP_WRITE_BUF.
+ *@param cris_en : callback function for critical section enter.
+ *@param cris_ex : callback function for critical section exit.
+ *@todo Describe @ref WIZCHIP_CRITICAL_ENTER and @ref WIZCHIP_CRITICAL_EXIT marco or register your functions.
+ *@note If you do not describe or register, default functions(@ref wizchip_cris_enter & @ref wizchip_cris_exit) is called.
+ */
+void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void));
+
+
+/**
+ *@brief Registers call back function for WIZCHIP select & deselect.
+ *@param cs_sel : callback function for WIZCHIP select
+ *@param cs_desel : callback fucntion for WIZCHIP deselect
+ *@todo Describe @ref wizchip_cs_select and @ref wizchip_cs_deselect function or register your functions.
+ *@note If you do not describe or register, null function is called.
+ */
+void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void));
+
+/**
+ *@brief Registers call back function for bus interface.
+ *@param bus_rb : callback function to read byte data using system bus
+ *@param bus_wb : callback function to write byte data using system bus
+ *@todo Describe @ref wizchip_bus_readbyte and @ref wizchip_bus_writebyte function
+ *or register your functions.
+ *@note If you do not describe or register, null function is called.
+ */
+//M20150601 : For integrating with W5300
+//void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb));
+void reg_wizchip_bus_cbfunc(iodata_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, iodata_t wb));
+
+/**
+ *@brief Registers call back function for SPI interface.
+ *@param spi_rb : callback function to read byte using SPI
+ *@param spi_wb : callback function to write byte using SPI
+ *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function
+ *or register your functions.
+ *@note If you do not describe or register, null function is called.
+ */
+void reg_wizchip_spi_cbfunc(uint8_t (*spi_rb)(void), void (*spi_wb)(uint8_t wb));
+
+/**
+ *@brief Registers call back function for SPI interface.
+ *@param spi_rb : callback function to burst read using SPI
+ *@param spi_wb : callback function to burst write using SPI
+ *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function
+ *or register your functions.
+ *@note If you do not describe or register, null function is called.
+ */
+void reg_wizchip_spiburst_cbfunc(void (*spi_rb)(uint8_t* pBuf, uint16_t len), void (*spi_wb)(uint8_t* pBuf, uint16_t len));
+
+/**
+ * @ingroup extra_functions
+ * @brief Controls to the WIZCHIP.
+ * @details Resets WIZCHIP & internal PHY, Configures PHY mode, Monitor PHY(Link,Speed,Half/Full/Auto),
+ * controls interrupt & mask and so on.
+ * @param cwtype : Decides to the control type
+ * @param arg : arg type is dependent on cwtype.
+ * @return 0 : Success \n
+ * -1 : Fail because of invalid \ref ctlwizchip_type or unsupported \ref ctlwizchip_type in WIZCHIP
+ */
+int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg);
+
+/**
+ * @ingroup extra_functions
+ * @brief Controls to network.
+ * @details Controls to network environment, mode, timeout and so on.
+ * @param cntype : Input. Decides to the control type
+ * @param arg : Inout. arg type is dependent on cntype.
+ * @return -1 : Fail because of invalid \ref ctlnetwork_type or unsupported \ref ctlnetwork_type in WIZCHIP \n
+ * 0 : Success
+ */
+int8_t ctlnetwork(ctlnetwork_type cntype, void* arg);
+
+
+/*
+ * The following functions are implemented for internal use.
+ * but You can call these functions for code size reduction instead of ctlwizchip() and ctlnetwork().
+ */
+
+/**
+ * @ingroup extra_functions
+ * @brief Reset WIZCHIP by softly.
+ */
+void wizchip_sw_reset(void);
+
+/**
+ * @ingroup extra_functions
+ * @brief Initializes WIZCHIP with socket buffer size
+ * @param txsize Socket tx buffer sizes. If null, initialized the default size 2KB.
+ * @param rxsize Socket rx buffer sizes. If null, initialized the default size 2KB.
+ * @return 0 : succcess \n
+ * -1 : fail. Invalid buffer size
+ */
+int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize);
+
+/**
+ * @ingroup extra_functions
+ * @brief Clear Interrupt of WIZCHIP.
+ * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t.
+ */
+void wizchip_clrinterrupt(intr_kind intr);
+
+/**
+ * @ingroup extra_functions
+ * @brief Get Interrupt of WIZCHIP.
+ * @return @ref intr_kind value operated OR. It can type-cast to uint16_t.
+ */
+intr_kind wizchip_getinterrupt(void);
+
+/**
+ * @ingroup extra_functions
+ * @brief Mask or Unmask Interrupt of WIZCHIP.
+ * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t.
+ */
+void wizchip_setinterruptmask(intr_kind intr);
+
+/**
+ * @ingroup extra_functions
+ * @brief Get Interrupt mask of WIZCHIP.
+ * @return : The operated OR vaule of @ref intr_kind. It can type-cast to uint16_t.
+ */
+intr_kind wizchip_getinterruptmask(void);
+
+//todo
+#if _WIZCHIP_ > W5100
+ int8_t wizphy_getphylink(void); ///< get the link status of phy in WIZCHIP. No use in W5100
+ int8_t wizphy_getphypmode(void); ///< get the power mode of PHY in WIZCHIP. No use in W5100
+#endif
+
+#if _WIZCHIP_ == W5100S || _WIZCHIP_ == W5500
+ void wizphy_reset(void); ///< Reset phy. Vailid only in W5500
+/**
+ * @ingroup extra_functions
+ * @brief Set the phy information for WIZCHIP without power mode
+ * @param phyconf : @ref wiz_PhyConf
+ */
+ void wizphy_setphyconf(wiz_PhyConf* phyconf);
+ /**
+ * @ingroup extra_functions
+ * @brief Get phy configuration information.
+ * @param phyconf : @ref wiz_PhyConf
+ */
+ void wizphy_getphyconf(wiz_PhyConf* phyconf);
+ /**
+ * @ingroup extra_functions
+ * @brief Get phy status.
+ * @param phyconf : @ref wiz_PhyConf
+ */
+ void wizphy_getphystat(wiz_PhyConf* phyconf);
+ /**
+ * @ingroup extra_functions
+ * @brief set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200
+ * @param pmode Settig value of power down mode.
+ */
+ int8_t wizphy_setphypmode(uint8_t pmode);
+#endif
+
+/**
+* @ingroup extra_functions
+ * @brief Set the network information for WIZCHIP
+ * @param pnetinfo : @ref wizNetInfo
+ */
+void wizchip_setnetinfo(wiz_NetInfo* pnetinfo);
+
+/**
+ * @ingroup extra_functions
+ * @brief Get the network information for WIZCHIP
+ * @param pnetinfo : @ref wizNetInfo
+ */
+void wizchip_getnetinfo(wiz_NetInfo* pnetinfo);
+
+/**
+ * @ingroup extra_functions
+ * @brief Set the network mode such WOL, PPPoE, Ping Block, and etc.
+ * @param pnetinfo Value of network mode. Refer to @ref netmode_type.
+ */
+int8_t wizchip_setnetmode(netmode_type netmode);
+
+/**
+ * @ingroup extra_functions
+ * @brief Get the network mode such WOL, PPPoE, Ping Block, and etc.
+ * @return Value of network mode. Refer to @ref netmode_type.
+ */
+netmode_type wizchip_getnetmode(void);
+
+/**
+ * @ingroup extra_functions
+ * @brief Set retry time value(@ref _RTR_) and retry count(@ref _RCR_).
+ * @details @ref _RTR_ configures the retransmission timeout period and @ref _RCR_ configures the number of time of retransmission.
+ * @param nettime @ref _RTR_ value and @ref _RCR_ value. Refer to @ref wiz_NetTimeout.
+ */
+void wizchip_settimeout(wiz_NetTimeout* nettime);
+
+/**
+ * @ingroup extra_functions
+ * @brief Get retry time value(@ref _RTR_) and retry count(@ref _RCR_).
+ * @details @ref _RTR_ configures the retransmission timeout period and @ref _RCR_ configures the number of time of retransmission.
+ * @param nettime @ref _RTR_ value and @ref _RCR_ value. Refer to @ref wiz_NetTimeout.
+ */
+void wizchip_gettimeout(wiz_NetTimeout* nettime);
+#ifdef __cplusplus
+ }
+#endif
+
+#endif // _WIZCHIP_CONF_H_
diff --git a/NxFuncs/network/tcpclient.c b/NxFuncs/network/tcpclient.c
new file mode 100644
index 0000000..75ed6f6
--- /dev/null
+++ b/NxFuncs/network/tcpclient.c
@@ -0,0 +1,425 @@
+
+#include "tcpclient.h"
+
+#if (CLIENT_NUM > 0)
+
+#include "socket.h"
+#include "inout.h"
+#include "console.h"
+#include "delay.h"
+#include "trigger.h"
+
+//----------------------------------------------------------------------
+
+int g_clinetLinksta; // ״̬
+int g_clinetLinkCount; // ӶϿ
+
+
+//-------------------------------------------
+
+SocketCtrl g_clientSocket[CLIENT_NUM] =
+{
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+0, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+0, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*0, TCP_CLIENT_REMOTE_PORT_BEG},
+#if (CLIENT_NUM > 1)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+1, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+1, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*1, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 2)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+2, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+2, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*2, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 3)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+3, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+3, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*3, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 4)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+4, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+4, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*4, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 5)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+5, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+5, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*5, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 6)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+6, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+6, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*6, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+#if (CLIENT_NUM > 7)
+ {TCP_CLIENT, STA_INIT, TCP_CLIENT_SN_BEG+7, TCP_CLIENT_LOCAL_IP, TCP_CLIENT_LOCAL_PORT_BEG+7, TCP_CLIENT_REMOTE_IP_BEG+TCP_CLIENT_REMOTE_IP_ADD*7, TCP_CLIENT_REMOTE_PORT_BEG},
+#endif
+};
+
+
+//-----------------------------------------------------------------------------------------------------
+
+void InitTcpClient(void)
+{
+ int i;
+
+ g_clinetLinksta = LINK_INIT;
+ g_clinetLinkCount = 0;
+
+ for (i = 0; i < CLIENT_NUM; i++)
+ {
+ g_clientSocket[i].status = STA_CLOSED;
+ }
+
+}
+
+//-----------------------------------------------------------------------------------------------------
+
+void TcpClientRun(void)
+{
+ int i;
+ int rslt;
+ u8 sn, tmp8;
+ u16 port, ir;
+ int crsocket;
+ u16 sport;
+ u32 sip;
+
+ crsocket = 0;
+
+ // PHY״̬
+ rslt = ctlwizchip(CW_GET_PHYLINK, (void*)(&tmp8));
+
+#if (0)
+ {
+ u32 timer;
+ timer = GetMsSoftTimer();
+ printf("at%d, TcpClientRun\r\n", timer);
+ }
+#endif
+
+ if(rslt == -1)
+ {
+ g_clinetLinksta = LINK_INIT;
+ printf("Unknown PHY Link stauts.\r\n");
+ return;
+ }
+ else
+ {
+ if (tmp8 == PHY_LINK_ON)
+ {
+ if (g_clinetLinksta != LINK_UP)
+ {
+ crsocket = 1; // socket
+ g_clinetLinksta = LINK_UP;
+ printf("PHY Link UP.\r\n");
+ }
+ }
+ else if (tmp8 == PHY_LINK_OFF)
+ {
+ if (g_clinetLinksta == LINK_INIT || g_clinetLinksta == LINK_UP)
+ {
+ if (g_clinetLinksta == LINK_INIT)
+ {
+ crsocket = 2; // رsocket
+ g_clinetLinksta = LINK_DOWN;
+ }
+ else
+ {
+ g_clinetLinkCount = 0;
+ g_clinetLinksta = LINK_WAIT;
+ }
+ printf("2. PHY Link DOWN.\r\n");
+ }
+ else if (g_clinetLinksta == LINK_WAIT)
+ {
+ g_clinetLinkCount++;
+ if (g_clinetLinkCount > 10)
+ {
+ crsocket = 2; // رsocket
+ g_clinetLinksta = LINK_DOWN;
+ }
+ }
+ else
+ {
+
+ }
+ }
+ else
+ {
+ printf("waite PHY connect.\r\n");
+ return;
+ }
+ }
+
+ // ر
+ if (g_clinetLinksta == LINK_DOWN && crsocket == 2)
+ {
+ printf("link down or crsocket == 2\r\n");
+ for (i = 0; i < CLIENT_NUM; i++)
+ {
+ if (g_clientSocket[i].status != STA_CLOSED)
+ {
+ g_clientSocket[i].status = STA_CLOSED;
+ printf("close socket %d and disconnect.\r\n", g_clientSocket[i].socket);
+ disconnect(g_clientSocket[i].socket);
+ close(g_clientSocket[i].socket);
+ }
+ }
+ return;
+ }
+
+ // tcp ͻ
+ for (i = 0; i < CLIENT_NUM; i++)
+ {
+ sn = g_clientSocket[i].socket;
+ port = g_clientSocket[i].localPort;
+
+ tmp8 = getSn_SR(sn);
+ switch(tmp8)
+ {
+ case SOCK_ESTABLISHED: //
+ {
+ // printf("TCP client socket %d SOCK_ESTABLISHED\r\n", sn);
+
+ ir = getSn_IR(sn); // ȡжϼĴ
+ if ((ir & Sn_IR_CON) != 0)
+ {
+ g_clientSocket[i].status = STA_CONNECT;
+ getsockopt(sn, SO_DESTIP, &sip);
+ getsockopt(sn, SO_DESTPORT, &sport);
+ printf("TCP client socket %d is connected, destination ip=%d.%d.%d.%d, port=%d\r\n", sn,
+ GETIP1(sip), GETIP2(sip), GETIP3(sip), GETIP4(sip), sport);
+ setSn_IR(sn, Sn_IR_CON); // ж״̬
+ }
+ break;
+ }
+
+ case SOCK_CLOSE_WAIT: // Էرյǰ
+ {
+ printf("TCP client socket %d wait close\r\n", sn);
+ disconnect(sn);
+ g_clientSocket[i].status = STA_CLOSED;
+ break;
+ }
+
+ case SOCK_CLOSED: // ǹر״̬
+ {
+ // ȴµ
+
+ printf("TCP client socket %d is closed, create a new socket\r\n", sn);
+ rslt = socket(sn, Sn_MR_TCP, port, SF_IO_NONBLOCK); //
+ if (rslt == sn)
+ {
+ printf("Create TCP client success at socket %d\r\n", sn);
+ }
+ else
+ {
+ printf("Create TCP client failed at socket %d, code=%d\r\n", sn, rslt);
+ }
+ break;
+ }
+ case SOCK_INIT: // ʼ
+ {
+ sip = g_clientSocket[i].remoteIp;
+ sport = g_clientSocket[i].remotePort;
+
+ printf("TCP client socket %d connect to ip=%d.%d.%d.%d, port=%d\r\n", sn,
+ GETIP1(sip), GETIP2(sip), GETIP3(sip), GETIP4(sip), sport);
+
+ rslt = connect(sn, (u8*)(&sip), sport);
+ if (rslt == SOCK_OK)
+ {
+ g_clientSocket[i].status = STA_READY;
+ printf("TCP client socket %d connecting......\r\n", sn);
+ }
+ else
+ {
+ // printf("TCP client socket %d connect error, code=%d\r\n", sn, rslt);
+ }
+ break;
+ }
+ case SOCK_LISTEN:
+ {
+ printf("TCP client socket %d SOCK_LISTEN\r\n", sn);
+ break;
+ }
+ case SOCK_SYNSENT:
+ {
+ printf("TCP client socket %d SOCK_SYNSENT\r\n", sn);
+ break;
+ }
+ case SOCK_SYNRECV:
+ {
+ printf("TCP client socket %d SOCK_SYNRECV\r\n", sn);
+ break;
+ }
+ default:
+ {
+ // printf("default, TCP client socket %d status=0x%x\r\n", sn, tmp8);
+ break;
+ }
+ } // end of switch
+ }
+}
+
+
+/*
+
+void CreateTcpClient(void)
+{
+ int i;
+ int rslt;
+ u8 sn, tmp8;
+ u16 port;
+ for (i = 0; i < 8; i++)
+ {
+ if (g_clientSocket.status != STA_CLOSED)
+ {
+ printf("tcp clinet not closed\r\n");
+ return;
+ }
+
+ sn = g_clientSocket.socket;
+ port = g_clientSocket.port;
+
+ tmp8 = SF_IO_NONBLOCK;
+ rslt = socket(sn, Sn_MR_TCP, port, tmp8);
+ if (rslt == sn)
+ {
+ g_clientSocket.status = STA_READY;
+ printf("create tcp client success\r\n");
+ }
+ else
+ {
+ printf("create tcp client failed\r\n");
+ }
+ }
+}
+
+void ConnectTcpClient(void)
+{
+ int rslt;
+ u8 sn;
+ u16 port;
+ u32 ipaddr;
+ if (g_clientSocket.status != STA_READY)
+ {
+ printf("tcp clinet not ready\r\n");
+ return;
+ }
+
+ sn = g_clientSocket.socket;
+ ipaddr = PLC_SERVER_IP;
+ port = PLC_SERVER_PORT;
+
+ rslt = connect(sn, (u8*)(&ipaddr), port);
+ if (rslt == SOCK_OK)
+ {
+ g_clientSocket.status = STA_CONNECT;
+ printf("connect server success......\r\n");
+ }
+ else if (rslt == SOCKERR_SOCKNUM)
+ {
+ printf("Invalid socket number\r\n");
+ }
+ else if (rslt == SOCKERR_SOCKMODE)
+ {
+ printf("Invalid socket mode\r\n");
+ }
+ else if (rslt == SOCKERR_SOCKINIT)
+ {
+ printf("Socket is not initialized\r\n");
+ }
+ else if (rslt == SOCKERR_IPINVALID)
+ {
+ printf("Wrong server IP address\r\n");
+ }
+ else if (rslt == SOCKERR_PORTZERO)
+ {
+ printf("Server port zero\r\n");
+ }
+ else if (rslt == SOCKERR_TIMEOUT)
+ {
+ printf("Timeout occurred during request connection\r\n");
+ }
+ else // if (rslt == SOCK_BUSY)
+ {
+ printf("0. socket is busy\r\n");
+ }
+}
+*/
+
+void TestNetTrans(void)
+{
+ int i[8], sta[8], rslt;
+ int j;
+ u8 buff[MAX_TRANS_DATA];
+
+ memset(i, 0, sizeof(int)*8);
+ memset(sta, 0, sizeof(int)*8);
+ memset(buff, 0x5A, MAX_TRANS_DATA);
+
+ do
+ {
+ if (IsConsoleCancel() != 0)
+ {
+ printf("send cancel\r\n");
+ break;
+ }
+
+ for (j = 0; j < CLIENT_NUM; j++)
+ {
+ if (g_clientSocket[j].status == STA_CONNECT)
+ {
+ if (sta[j] == 0)
+ {
+ if (i[j]%10 == 0)
+ {
+ printf("socket %d send data from tcp client to server %d times\r\n", g_clientSocket[j].socket, i[j]);
+ }
+ if (i[j]%2 == 0)
+ {
+ SetLedOn();
+ }
+ else
+ {
+ SetLedOff();
+ }
+
+ sta[j] = 1;
+ }
+
+ if (sta[j] == 1)
+ {
+ rslt = EthernetSendData(&(g_clientSocket[j]), buff, MAX_TRANS_DATA);
+ if (rslt != MAX_TRANS_DATA)
+ {
+ continue;
+ }
+ // printf("send data %d times success\r\n", i);
+ sta[j] = 0;
+ i[j]++;
+ }
+ }
+ }
+ }while(1);
+
+}
+#endif
+
+SocketCtrl * GetTcpClientCtrlFromSocketId(int sIdx)
+{
+#if (CLIENT_NUM > 0)
+ if (sIdx < CLIENT_NUM)
+ {
+ return &(g_clientSocket[sIdx]);
+ }
+ else
+#endif
+ {
+ return NULL;
+ }
+}
+
+int IsClinetConnect(int sIdx)
+{
+#if (CLIENT_NUM > 0)
+ if (sIdx < CLIENT_NUM)
+ {
+ return g_clientSocket[sIdx].status;
+ }
+ else
+#endif
+ {
+ return -1;
+ }
+}
+
diff --git a/NxFuncs/network/tcpclient.h b/NxFuncs/network/tcpclient.h
new file mode 100644
index 0000000..b396a17
--- /dev/null
+++ b/NxFuncs/network/tcpclient.h
@@ -0,0 +1,34 @@
+
+#ifndef __TCPCLIENT_H__
+#define __TCPCLIENT_H__
+
+#include "ethernet.h"
+
+
+#if (CLIENT_NUM > 0)
+
+
+//-------------------------------------------------------------------
+
+void InitTcpClient(void);
+
+void TcpClientRun(void);
+
+/*
+void ConnectTcpClient(void);
+
+void CreateTcpClient(void);
+
+*/
+
+
+//----------------------------------------------------------------------
+#endif
+
+int IsClinetConnect(int sIdx);
+SocketCtrl * GetTcpClientCtrlFromSocketId(int sIdx);
+
+
+#endif
+
+
diff --git a/NxFuncs/network/tcpserver.c b/NxFuncs/network/tcpserver.c
new file mode 100644
index 0000000..a9503a8
--- /dev/null
+++ b/NxFuncs/network/tcpserver.c
@@ -0,0 +1,388 @@
+
+#include "tcpserver.h"
+
+#if (SERVER_NUM > 0)
+
+
+// TCP server
+#include "socket.h"
+#include "inout.h"
+
+//---------------------------------------------------------------
+
+int g_linksta; // ״̬
+int g_linkCount; // ӶϿ
+
+//-------------------------------------------
+
+SocketCtrl g_serverSocket[SERVER_NUM] =
+{
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+0, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*0, TCP_SERVER_PORT_BEG+0, 0, 0},
+#if (SERVER_NUM > 1)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+1, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*1, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 2)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+2, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*2, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 3)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+3, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*3, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 4)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+4, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*4, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 5)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+5, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*5, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 6)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+6, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*6, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+#if (SERVER_NUM > 7)
+ {TCP_SERVER, STA_INIT, TCP_SERVER_SN_BEG+7, TCP_SERVER_LOCAL_IP_BEG+TCP_SERVER_LOCAL_IP_ADD*7, TCP_SERVER_PORT_BEG+0, 0, 0},
+#endif
+};
+
+void InitTcpServer(void)
+{
+ int i;
+ for (i = 0; i < SERVER_NUM; i++)
+ {
+ g_serverSocket[i].status = STA_CLOSED;
+ }
+
+ g_linksta = LINK_INIT;
+ g_linkCount = 0;
+}
+
+void SetTcpKeepAlive(void)
+{
+ int i;
+ uint8_t alivetime = 1;
+ for (i = 0; i < SERVER_NUM; i++)
+ {
+ setsockopt(g_serverSocket[i].socket, SO_KEEPALIVEAUTO, &alivetime);
+ printf("enable socket %d auto keep alive\r\n", g_serverSocket[i].socket);
+ }
+}
+
+void TcpServerRun(void)
+{
+ int i;
+ int rslt;
+ int crsocket;
+ u8 sn, tmp8;
+ u16 port, ir;
+
+ crsocket = 0;
+
+ // PHY״̬
+ rslt = ctlwizchip(CW_GET_PHYLINK, (void*)(&tmp8));
+
+ if (1) // ȡȶ
+ {
+ int tprslt, retry;
+ u8 temp;
+ retry = 10;
+ do
+ {
+ tprslt = ctlwizchip(CW_GET_PHYLINK, (void*)(&temp));
+ if (rslt != tprslt)
+ {
+ printf("1. net link rslt = %d\r\n", tprslt);
+ break;
+ }
+ else
+ {
+ if (temp != tmp8)
+ {
+ printf("1. net link sta = 0x%x, old=0x%x\r\n", temp, tmp8);
+ break;
+ }
+ }
+ retry--;
+ }while(retry > 0);
+ if (retry != 0)
+ {
+ return;
+ }
+ }
+
+ if (rslt == -1)
+ {
+ g_linksta = LINK_INIT;
+ printf("Unknown PHY Link stauts.\r\n");
+ return;
+ }
+ else
+ {
+ if (tmp8 == PHY_LINK_ON)
+ {
+ if (g_linksta != LINK_UP)
+ {
+ crsocket = 1; // socket
+ g_linksta = LINK_UP;
+ printf("PHY Link UP.\r\n");
+ g_linkCount = 0;
+ }
+ }
+ else if (tmp8 == PHY_LINK_OFF)
+ {
+ if (g_linksta == LINK_INIT || g_linksta == LINK_UP)
+ {
+ if (g_linksta == LINK_INIT)
+ {
+ crsocket = 2; // رsocket
+ g_linksta = LINK_DOWN;
+ printf("1. PHY Link DOWN.\r\n");
+ }
+ else
+ {
+ g_linkCount = 0;
+ g_linksta = LINK_WAIT;
+ printf("1. PHY Link WAIT.\r\n");
+ }
+ }
+ else if (g_linksta == LINK_WAIT)
+ {
+ printf("2. PHY Link WAIT.\r\n");
+ g_linkCount++;
+ if (g_linkCount > 10) // Ͽʱ
+ {
+ crsocket = 2; // رsocket
+ g_linksta = LINK_DOWN;
+ printf("1. PHY Link DOWN.\r\n");
+ }
+ }
+ else if (g_linksta == LINK_DOWN)
+ {
+
+ }
+ else
+ {
+ printf("other Link sta.\r\n");
+ }
+ }
+ else
+ {
+ printf("waite PHY connect.\r\n");
+ return;
+ }
+ }
+
+ // ر
+ if (g_linksta == LINK_DOWN && crsocket == 2)
+ {
+ for (i = 0; i < SERVER_NUM; i++)
+ {
+ if (g_serverSocket[i].status != STA_CLOSED)
+ {
+ g_serverSocket[i].status = STA_CLOSED;
+ printf("Close TCP server socket %d and disconnect.\r\n", g_serverSocket[i].socket);
+ disconnect(g_serverSocket[i].socket);
+ close(g_serverSocket[i].socket);
+ }
+ }
+ return;
+ }
+
+ // tcp
+ for (i = 0; i < SERVER_NUM; i++)
+ {
+ sn = g_serverSocket[i].socket;
+ port = g_serverSocket[i].localPort;
+ tmp8 = getSn_SR(sn);
+
+ if (1) // ȡȶ
+ {
+ int retry;
+ u8 temp;
+ retry = 10;
+ do
+ {
+ temp = getSn_SR(sn);
+
+ if (temp != tmp8)
+ {
+ printf("1. socket %d sr = 0x%x, old=0x%x\r\n", sn, temp, tmp8);
+ break;
+ }
+ retry--;
+ }while(retry > 0);
+ if (retry != 0)
+ {
+ return;
+ }
+ }
+
+ switch(tmp8)
+ {
+ case SOCK_ESTABLISHED: //
+ {
+ ir = getSn_IR(sn); // ȡжϼĴ
+ if ((ir & Sn_IR_CON) != 0)
+ {
+ u32 ip;
+ u16 port;
+ g_serverSocket[i].status = STA_CONNECT;
+ getsockopt(sn, SO_DESTIP, &ip);
+ getsockopt(sn, SO_DESTPORT, &port);
+
+ printf("TCP server is connected to socket %d, destination ip=%d.%d.%d.%d, port=%d\r\n", sn,
+ GETIP1(ip), GETIP2(ip), GETIP3(ip), GETIP4(ip), port);
+ setSn_IR(sn, Sn_IR_CON); // ж״̬
+ }
+
+ if((ir & Sn_IR_CON) != 0) //
+ {
+ }
+
+ if ((ir & Sn_IR_DISCON) != 0) // Ͽ
+ {
+ }
+
+ if ((ir & Sn_IR_RECV) != 0) // յ
+ {
+ }
+
+ if ((ir & Sn_IR_TIMEOUT) != 0) // ʱ
+ {
+ }
+
+ if ((ir & Sn_IR_SENDOK) != 0) //
+ {
+ }
+ break;
+ }
+
+ case SOCK_CLOSE_WAIT: // Էرյǰ
+ {
+ rslt = disconnect(sn);
+ close(sn);
+
+ printf("TCP server socket %d wait close, rslt=%d\r\n", sn, rslt);
+
+ // if (rslt == SOCK_OK)
+ {
+ g_serverSocket[i].status = STA_CLOSED;
+ }
+ break;
+ }
+
+ case SOCK_CLOSED: // ǹر״̬
+ {
+ printf("TCP server socket %d is closed, create a new socket\r\n", sn);
+ rslt = socket(sn, Sn_MR_TCP, port, SF_IO_NONBLOCK|0); // SF_TCP_NODELAY
+ if(rslt == sn)
+ {
+ printf("TCP server socket %d create success\r\n", sn);
+ }
+ else
+ {
+ printf("Create TCP server socket %d failed, code=%d\r\n", sn, rslt);
+ if (rslt == SOCKERR_SOCKINIT)
+ {
+ printf("Re Init Network\r\n");
+ InitNetConfig(); // оƬ
+ }
+ }
+ break;
+ }
+
+ case SOCK_INIT: // ʼ
+ {
+ rslt = listen(sn);
+ if (rslt == SOCK_OK)
+ {
+ g_serverSocket[i].status = STA_READY;
+ printf("TCP server socket %d Listening......\r\n\tserver ip= %d.%d.%d.%d, port=%d\r\n", \
+ sn, g_netInfo.ip[0],g_netInfo.ip[1],g_netInfo.ip[2],g_netInfo.ip[3], port);
+ }
+ else
+ {
+ printf("TCP server socket %d Listen error, code=%d\r\n", sn, rslt);
+ }
+ break;
+ }
+ case SOCK_LISTEN:
+ {
+ break;
+ }
+ default:
+ {
+/*
+ SOCK_SYNSENT 0x15
+ SOCK_SYNRECV 0x16
+ SOCK_ESTABLISHED 0x17
+ SOCK_FIN_WAIT 0x18
+ SOCK_CLOSING 0x1A
+ SOCK_TIME_WAIT 0x1B
+ SOCK_CLOSE_WAIT 0x1C
+ SOCK_LAST_ACK 0x1D
+ SOCK_UDP 0x22
+ SOCK_MACRAW 0x42
+ */
+ if (tmp8 != 0)
+ {
+ printf("TCP server default, getSn_SR=0x%x\r\n", tmp8);
+ }
+ break;
+ }
+ } // end of switch
+ }
+}
+
+SocketCtrl * GetTcpServerCtrlFromSocketId(int sIdx)
+{
+ if (sIdx < SERVER_NUM)
+ {
+ return &(g_serverSocket[sIdx]);
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+#if (0)
+
+void TcpServerGetData(void)
+{
+ int i;
+ int len, rslt, expt;
+ u8 buff[MAX_TRANS_DATA];
+
+ for (i = 0; i < SERVER_NUM; i++)
+ {
+ len = EthernetGetRsLen(&(g_serverSocket[i]));
+ if (len != 0)
+ {
+ printf("receive data from socket%d, len=%d\r\n", g_serverSocket[i].socket, len);
+ }
+
+ while (len != 0)
+ {
+ if (len > MAX_TRANS_DATA)
+ {
+ expt = MAX_TRANS_DATA;
+ }
+ else
+ {
+ expt = len;
+ }
+ rslt = EthernetGetData(&(g_serverSocket[i]), buff, expt);
+
+ if (rslt == expt)
+ {
+ len -= expt;
+ }
+ else
+ {
+ printf("receive data error\r\n");
+ }
+ }
+ }
+
+}
+
+#endif
+
+#endif
diff --git a/NxFuncs/network/tcpserver.h b/NxFuncs/network/tcpserver.h
new file mode 100644
index 0000000..e3cd4bb
--- /dev/null
+++ b/NxFuncs/network/tcpserver.h
@@ -0,0 +1,21 @@
+
+#ifndef __TCPSERVER_H__
+#define __TCPSERVER_H__
+
+#include "ethernet.h"
+
+#if (SERVER_NUM > 0)
+
+void InitTcpServer(void);
+
+void SetTcpKeepAlive(void);
+
+SocketCtrl * GetTcpServerCtrlFromSocketId(int sIdx);
+
+// tcp
+void TcpServerRun(void);
+
+#endif
+
+
+#endif
diff --git a/NxFuncs/network/udptrans.c b/NxFuncs/network/udptrans.c
new file mode 100644
index 0000000..81a006d
--- /dev/null
+++ b/NxFuncs/network/udptrans.c
@@ -0,0 +1,98 @@
+
+#include "udptrans.h"
+
+typedef struct
+{
+ int socketSn;
+ u32 localIP;
+ u32 localPort;
+ u32 remoteIP;
+ u16 remotePort;
+
+}UdpCtrl;
+
+UdpCtrl g_udpCtrl;
+
+//-------------------------------------------
+
+#if (UDP_NUM > 0)
+
+//-------------------------------------------
+
+SocketCtrl g_udpSocket[UDP_NUM] =
+{
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+0, UDP_LOCAL_PORT_BEG+0},
+#if (UDP_NUM > 1)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+1, UDP_LOCAL_PORT_BEG+1},
+#endif
+#if (UDP_NUM > 2)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+2, UDP_LOCAL_PORT_BEG+2},
+#endif
+#if (UDP_NUM > 3)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+3, UDP_LOCAL_PORT_BEG+3},
+#endif
+#if (UDP_NUM > 4)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+4, UDP_LOCAL_PORT_BEG+4},
+#endif
+#if (UDP_NUM > 5)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+5, UDP_LOCAL_PORT_BEG+5},
+#endif
+#if (UDP_NUM > 6)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+6, UDP_LOCAL_PORT_BEG+6},
+#endif
+#if (UDP_NUM > 7)
+ {UDP_COMM, STA_INIT, UDP_SN_BEG+7, UDP_LOCAL_PORT_BEG+7},
+#endif
+};
+
+#endif
+
+
+
+void InitUdpTrans(void)
+{
+ g_udpCtrl.socketSn = UDP_SN_BEG;
+ g_udpCtrl.localIP = UDP_LOCAL_IP;
+ g_udpCtrl.localPort = UDP_LOCAL_PORT_BEG;
+
+ g_udpCtrl.remoteIP = UDP_REMOTE_IP;
+ g_udpCtrl.remotePort = UDP_REMOTE_PORT;
+}
+
+int UdpTransData(u8 * pBuff, int len)
+{
+ int rslt;
+
+ rslt = sendto(g_udpCtrl.socketSn, pBuff, len, (u8*)(&g_udpCtrl.remoteIP), g_udpCtrl.remotePort);
+ return rslt;
+}
+
+int UdpRecvData(u8 * pBuff, int len)
+{
+ int rslt;
+ u32 ip;
+ u16 port;
+
+ rslt = recvfrom(g_udpCtrl.socketSn, pBuff, len, (u8*)(&ip), &port);
+/*
+ // ¶ԷIP PORT
+ g_udpCtrl.remoteIP;
+ g_udpCtrl.remotePort;
+*/
+ return rslt;
+}
+
+SocketCtrl * GetUdpCtrlFromSocketId(int sIdx)
+{
+#if (UDP_NUM > 0)
+ if (sIdx < UDP_NUM)
+ {
+ return &(g_udpSocket[sIdx]);
+ }
+ else
+#endif
+ {
+ return NULL;
+ }
+}
+
diff --git a/NxFuncs/network/udptrans.h b/NxFuncs/network/udptrans.h
new file mode 100644
index 0000000..1393feb
--- /dev/null
+++ b/NxFuncs/network/udptrans.h
@@ -0,0 +1,16 @@
+
+#ifndef __UDPTRANS_H__
+#define __UDPTRANS_H__
+
+#include "ethernet.h"
+
+
+void InitUdpTrans(void);
+
+int UdpTransData(u8 * pBuff, int len);
+
+int UdpRecvData(u8 * pBuff, int len);
+
+SocketCtrl * GetUdpCtrlFromSocketId(int sIdx);
+
+#endif
diff --git a/NxFuncs/norflash/norflash.c b/NxFuncs/norflash/norflash.c
new file mode 100644
index 0000000..e3d893f
--- /dev/null
+++ b/NxFuncs/norflash/norflash.c
@@ -0,0 +1,914 @@
+
+#include "norflash.h"
+
+#include "trigger.h"
+#include "shell.h"
+#include "delay.h"
+
+//--------------------------------------------------------------------------------------------
+
+//
+//----------------------------------------------
+
+// serial Norflash (/˫·/·SPIָ)ָ
+
+// // ʵ
+#define SNF_WT_ENABLE 0x06 // * // дʹ
+#define SNF_VSR_WR_ENABLE 0x50 // // ʧ洢SRдʹ
+#define SNF_WT_DISABLE 0x04 // * // д
+
+#define SNF_RD_STREG1 0x05 // * // ״̬Ĵ1(S7--S0)
+#define SNF_RD_STREG2 0x35 // * // ״̬Ĵ2(S15--S8)
+#define SNF_WT_STREG12 0x01 // * // д״̬Ĵ12(S7--S0 S15--S8)
+
+#define SNF_READ_DATA 0x03 // * // (3ֽڵַ+1ֽ)
+#define SNF_FAST_READ 0x0B // * // [ٶָ] (3ֽڵַ+1ֽ+1ֽ)
+
+#define SNF_PAGE_PROGRAM 0x02 // * // ҳд[д128(256ֽ),ҲԿҳ] 3ֽڵĵַ+2ֽݸ
+#define SNF_4K_ERASE 0x20 // * // (4KB) (3ֽڵַ)
+#define SNF_32K_ERASE 0x52 // * // (32KB) (3ֽڵַ)
+#define SNF_64K_ERASE 0xD8 // * // (64KB) (3ֽڵַ)
+
+
+#define SNF_CHIP_ERASE 0xC7 // * // Ƭ 0x60
+
+
+#define SNF_EP_SUSPEND 0x75 // // д
+#define SNF_EP_RESUME 0x7A // // дָ(ӹУ
+#define SNF_POWER_DOWN 0xB9 // //
+
+#define SNF_WKUP_DEVICE_ID 0xAB // // ϵͶȡ豸ID (3ֽ+1ֽ豸ID)
+#define SNF_MANU_DEVICE_ID 0x90 // * // ȡID豸ID (2ֽ+00H+1ֽID+1ֽ豸ID)
+#define SNF_JEDEC_ID 0x9F // * // оƬ JEDEC ID ̬Эᣩ(1ֽID+2ֽ豸ID(洢+洢))
+#define SNF_UNIQUE_ID 0x4B // * // ID (4ֽ+8ֽUID)
+#define SNF_RD_SFDP 0x5A // // SFDPĴ(3ֽڵַ+1ֽ+1ֽ)
+
+#define SNF_ERASE_SECURITY 0x44 // // Ĵ(3ֽڵַ) 鱣ܼĴַ 0x0010xx 0x0020xx 0x0030xx
+#define SNF_PROGRAM_SECURITY 0x42 // // Ĵ(3ֽڵַ+1ֽ)
+#define SNF_READ_SECURITY 0x48 // // ȡ Ĵ(3ֽڵַ+1ֽ)
+
+#define SNF_RESET_DEVICE 0x66 // // λ
+#define SNF_ENABLE_RESET 0x99 // // λоƬ
+
+/*
+#define SNF_BLOCK_LOCK 0x7E // // ȫ
+#define SNF_BLOCK_UNLOCK 0x98 // // ȫ
+#define SNF_ENTER_QPI 0x38 // // QPIģʽ
+
+#define SNF_INDV_BLOCK_LOCK 0x36 // //
+#define SNF_INDV_BLOCK_UNLOCK 0x39 // //
+#define SNF_READ_BLOCK_LOCK 0x3D // // ȡ
+*/
+
+//---------------------------------------------------
+
+#define DUMMY_BYTE 0xFF
+
+//--------------------------------------------------------------------------------------------
+
+int SNFWaitNotBusyMs(u32 timeout);
+int SNFWaitNotBusy10Us(u32 timeout);
+
+u8 SNFReadStatusReg1(void);
+u8 SNFReadStatusReg2(void);
+void SNFWriteStatusReg1And2(u8 reg1, u8 reg2);
+
+void ShowSNFInfo(void);
+void SNFlashTest(char * para1, char * para2); // NorFlash
+
+//--------------------------------------------------------------------------------------------
+
+typedef struct
+{
+ int inited;
+ // SPI д
+ void (*spicson)(void);
+ void (*spicsoff)(void);
+ u8 (*spird)(void);
+ void (*spiwr)(u8 wb);
+
+}SNFCtrl;
+
+SNFCtrl g_snfCtrl;
+
+//--------------------------------------------------------------------------------------------
+
+// NorFlash ʼ
+int SNFlashInit(void (*spicson)(void), void (*spicsoff)(void), u8 (*spird)(void), void (*spiwr)(u8 wb))
+{
+ memset(&g_snfCtrl, 0, sizeof(SNFCtrl));
+
+ g_snfCtrl.spicson = spicson;
+ g_snfCtrl.spicsoff = spicsoff;
+ g_snfCtrl.spird = spird;
+ g_snfCtrl.spiwr = spiwr;
+
+ if (g_snfCtrl.spicson == NULL ||
+ g_snfCtrl.spicsoff == NULL ||
+ g_snfCtrl.spird == NULL ||
+ g_snfCtrl.spiwr == NULL ||
+ 0 )
+ {
+ printf("SNFlashInit para error\r\n");
+ return -1;
+ }
+
+ g_snfCtrl.inited = 1;
+
+ SNFWirteEnable();
+
+ SNFWriteStatusReg1And2(0, 0);
+
+ SNFWaitNotBusyMs(100);
+
+ SNFWirteDisable();
+
+#if (0)
+ ShowSNFInfo();
+ AddShellCmd("NORFLASH", "test nor flash", SNFlashTest);
+#endif
+
+ return 0;
+}
+
+//---------------------------------
+
+// дʹܿ
+// ״̬ĴеWEL λ Ϊ1
+// ִ д״̬Ĵָ֮ǰWELλ1
+void SNFWirteEnable(void)
+{
+ if (g_snfCtrl.inited == 0)
+ {
+ return;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_WT_ENABLE);
+
+ g_snfCtrl.spicsoff();
+}
+
+//---------------------------------
+
+// дʹܹأɹرշʧĴдʹܣ
+// ״̬ĴеWEL λ Ϊ0
+// ִ д״̬Ĵָ֮ǰWELλ1
+void SNFWirteDisable(void)
+{
+ if (g_snfCtrl.inited == 0)
+ {
+ return;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_WT_DISABLE);
+
+ g_snfCtrl.spicsoff();
+}
+
+//---------------------------------
+
+// ״̬Ĵ1
+// ʱȡݿȡ
+// SRP0 SEC TB PB2 PB1 PB0 WEL BUSY
+
+u8 SNFReadStatusReg1(void)
+{
+ u8 dat;
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_RD_STREG1);
+
+ dat = g_snfCtrl.spird(); //
+
+ g_snfCtrl.spicsoff();
+
+ return dat;
+}
+
+//---------------------------------
+
+// ״̬Ĵ2
+// ʱȡݿȡ
+// SUS CMP LB3 LB2 LB1 (R) QE SRP1
+u8 SNFReadStatusReg2(void)
+{
+ u8 dat;
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_RD_STREG2);
+
+ dat = g_snfCtrl.spird(); //
+
+ g_snfCtrl.spicsoff();
+
+ return dat;
+}
+
+//---------------------------------
+
+// д״̬Ĵ12
+void SNFWriteStatusReg1And2(u8 reg1, u8 reg2)
+{
+ if (g_snfCtrl.inited == 0)
+ {
+ return;
+ }
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_WT_STREG12);
+
+ g_snfCtrl.spiwr(reg1);
+
+ g_snfCtrl.spiwr(reg2);
+
+ g_snfCtrl.spicsoff();
+}
+
+//---------------------------------
+// : жNorǷڿ״̬
+// ֵ: 0,
+// 1, æ
+
+int SNFIsdStatusBusy(void)
+{
+ u8 sta1;
+ sta1 = SNFReadStatusReg1();
+ sta1 &= 0x01; // WIP flag
+
+ return sta1;
+}
+
+//---------------------------------
+// (50Mµٶȣ
+// 洢ڿȡ
+int SNFlashRdData(u32 addr, u8 * pBuf, int len)
+{
+ int i;
+ if (pBuf == NULL ||
+ len <= 0 ||
+ g_snfCtrl.inited == 0 ||
+ 0 )
+ {
+ return -1;
+ }
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_READ_DATA);
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ for (i = 0; i < len; i++)
+ {
+ *pBuf++ = g_snfCtrl.spird();
+ }
+
+ g_snfCtrl.spicsoff();
+
+ return 0;
+}
+
+//---------------------------------
+// ٶȡɴﵽ104M
+// 洢ڿȡ
+int SNFFastReadData(u32 addr, u8 * pBuf, int len)
+{
+ int i;
+ if (pBuf == NULL ||
+ len <= 0 ||
+ g_snfCtrl.inited == 0 ||
+ 0 )
+ {
+ return -1;
+ }
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_FAST_READ);
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spiwr(DUMMY_BYTE);
+
+ for (i = 0; i < len; i++)
+ {
+ *pBuf++ = g_snfCtrl.spird();
+ }
+
+ g_snfCtrl.spicsoff();
+
+ return 0;
+}
+
+//---------------------------------
+// жǷΪ
+int IsSNFlashEmpty(u32 addr, int len)
+{
+ u32 i;
+ int rslt = 0;
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_READ_DATA);
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ for (i = 0; i < len; i++)
+ {
+ if (g_snfCtrl.spird() != 0xff)
+ {
+ rslt = 1;
+ break;
+ }
+ }
+
+ g_snfCtrl.spicsoff();
+
+ return rslt;
+}
+
+//---------------------------------
+// ҳд[д256ֽ]
+// ݳһҳַѭصһҳʼд
+int SNFPageProgram(u32 addr, u8 * pBuf, int len)
+{
+ int i;
+ if (pBuf == NULL ||
+ len <= 0 ||
+ g_snfCtrl.inited == 0 ||
+ 0 )
+ {
+ return -1;
+ }
+
+ SNFWirteEnable();
+ SNFWaitNotBusy10Us(100);
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_PAGE_PROGRAM);
+
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ for (i = 0; i < len; i++)
+ {
+ g_snfCtrl.spiwr(*pBuf++);
+ }
+
+ g_snfCtrl.spicsoff();
+
+ return SNFWaitNotBusy10Us(300);
+}
+
+//---------------------------------
+// (4KB)
+int SNFlash4kErase(u32 addr, int wait)
+{
+ int rslt = 1;
+ if (g_snfCtrl.inited == 0)
+ {
+ return rslt;
+ }
+
+ SNFWirteEnable();
+ SNFWaitNotBusy10Us(100);
+
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_4K_ERASE);
+
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spicsoff();
+
+ if (wait != 0)
+ {
+ rslt = SNFWaitNotBusyMs(300);
+ }
+
+ return rslt;
+}
+
+//---------------------------------
+// (32KB)
+int SNFlash32kErase(u32 addr, int wait)
+{
+ int rslt = 1;
+ if (g_snfCtrl.inited == 0)
+ {
+ return rslt;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_32K_ERASE);
+
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spicsoff();
+
+ if (wait != 0)
+ {
+ rslt = SNFWaitNotBusyMs(800);
+ }
+
+ return rslt;
+}
+
+//---------------------------------
+// (64KB)
+int SNFlash64kErase(u32 addr, int wait)
+{
+ int rslt = 1;
+ if (g_snfCtrl.inited == 0)
+ {
+ return rslt;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_64K_ERASE);
+
+ g_snfCtrl.spiwr(LOBYTE(HIWORD(addr)));
+
+ g_snfCtrl.spiwr(HIBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spiwr(LOBYTE(LOWORD(addr)));
+
+ g_snfCtrl.spicsoff();
+
+ if (wait != 0)
+ {
+ rslt = SNFWaitNotBusyMs(1000);
+ }
+
+ return rslt;
+}
+
+//---------------------------------
+// Ƭ
+int SNFlashChipErase(u32 addr, int wait)
+{
+ int rslt = 1;
+ if (g_snfCtrl.inited == 0)
+ {
+ return rslt;
+ }
+ g_snfCtrl.spicson();
+
+ g_snfCtrl.spiwr(SNF_CHIP_ERASE);
+
+ g_snfCtrl.spicsoff();
+
+ if (wait != 0)
+ {
+ rslt = SNFWaitNotBusyMs(6000);
+ }
+
+ return rslt;
+}
+
+//---------------------------------
+// ȡ id 豸 ID
+// manufacturer id + device id
+
+u32 SNFGetManufacDeviceID(void)
+{
+ u32 mdid;
+ u8 mid,did;
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+ g_snfCtrl.spicson();
+ g_snfCtrl.spiwr(SNF_MANU_DEVICE_ID);
+ g_snfCtrl.spiwr(0);
+ g_snfCtrl.spiwr(0);
+ g_snfCtrl.spiwr(0);
+
+ mid = g_snfCtrl.spird();
+ did = g_snfCtrl.spird();
+
+ g_snfCtrl.spicsoff();
+
+ mdid = MAKEDWORDF(did, mid, 0, 0);
+
+// printf("Nor flash manufacturer id and device id = 0x%x\r\n", mdid);
+
+ return mdid;
+}
+
+//---------------------------------
+// ȡ JEDEC ID
+// manufacturer id + memory type + capacity
+
+u32 SNFGetJedecID(void)
+{
+ u32 jid;
+ u8 id1,id2,id3;
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+ g_snfCtrl.spicson();
+ g_snfCtrl.spiwr(SNF_JEDEC_ID);
+ id3 = g_snfCtrl.spird();
+ id2 = g_snfCtrl.spird();
+ id1 = g_snfCtrl.spird();
+ g_snfCtrl.spicsoff();
+
+ jid = MAKEDWORDF(id1, id2, id3, 0);
+
+// printf("Nor flash jedec id = 0x%x\r\n", jid);
+
+ return jid;
+}
+
+//---------------------------------
+// ȡ Unique ID
+// 8ֽڵΨһк
+
+u64 SNFGetUniqueID(void)
+{
+ int i;
+ u8 id;
+ u64 uid;
+ u8 * pId = (u8 *)(&uid);
+
+ if (g_snfCtrl.inited == 0)
+ {
+ return 0;
+ }
+ g_snfCtrl.spicson();
+ g_snfCtrl.spiwr(SNF_UNIQUE_ID);
+ g_snfCtrl.spiwr(DUMMY_BYTE);
+ g_snfCtrl.spiwr(DUMMY_BYTE);
+ g_snfCtrl.spiwr(DUMMY_BYTE);
+ g_snfCtrl.spiwr(DUMMY_BYTE);
+
+ printf("Nor flash Unique id = ");
+
+ for (i = 0; i < 8; i++)
+ {
+ id = g_snfCtrl.spird();
+ *pId++ = id;
+ printf("0x%x, ", id);
+ }
+ printf("\r\n");
+
+ g_snfCtrl.spicsoff();
+
+ return uid;
+}
+
+//---------------------------------
+// д
+int SNFlashWrData(u32 addr, u8 *data, int len)
+{
+ int rslt;
+ u32 pglen;
+
+ pglen = addr % SNF_BYTES_PER_PAGE;
+ if (pglen == 0)
+ {
+ pglen = SNF_BYTES_PER_PAGE;
+ }
+
+ do
+ {
+ rslt = SNFPageProgram(addr, data, pglen);
+ if (rslt != 0)
+ {
+ break;
+ }
+ addr += pglen;
+ data += pglen;
+ len -= pglen;
+ if (len >= SNF_BYTES_PER_PAGE)
+ {
+ pglen = SNF_BYTES_PER_PAGE;
+ }
+ else if (len > 0)
+ {
+ pglen = len;
+ }
+ else
+ {
+ break;
+ }
+ }while(1);
+
+ return rslt;
+}
+
+//---------------------------------
+/*
+ * ---------------------- eaddr:ַ(ʼַ) -----
+ * | | |
+ * | | |
+ * | ҳ1 | |
+ * ---------------------- |
+ * | | |
+ * | | elen:ַдɵֽ
+ * | ҳ2 | |
+ * ---------------------- ---- addr:дʼַ |
+ * | | | |
+ * | | len:д볤 |
+ * | ҳ3 | | |
+ * ---------------------- ----- ----
+ * | |
+ * | |
+ * | ҳ4 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ5 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ6 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ7 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ8 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ9 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ10 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ11 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ12 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ13 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ14 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ15 |
+ * ----------------------
+ * | |
+ * | |
+ * | ҳ16 |
+ * ----------------------
+ */
+// дݣԶ
+int SNFlashWrDataWithErase(u32 addr, u8 *data, int len)
+{
+ int i, erflag, rslt; // erflag:־ = 1,
+ u8 rdata[SNF_BYTES_PER_SEC]; // 洢
+ u32 eaddr; // ַ
+ u32 elen, wlen; // elen:ַдɵֽ wlen:д볤
+
+ eaddr = (addr/SNF_BYTES_PER_SEC) * SNF_BYTES_PER_SEC; // ȡַ
+ rslt = 0;
+
+ printf("nwe, fad=0x%x, sad=0x%x len=%d, \r\n", addr, eaddr, len);
+
+ while(addr < SNF_TOTAL_BYTES && len > 0)
+ {
+ erflag = 0;
+ SNFlashRdData(eaddr, rdata, SNF_BYTES_PER_SEC); // ȡһ
+
+ elen = SNF_BYTES_PER_SEC;
+ if ((addr-eaddr)+len < elen)
+ {
+ elen = len+(addr-eaddr); // ַдɵֽ
+ }
+
+ wlen = elen-(addr-eaddr);
+
+ // жǷҪ
+ for (i = (addr-eaddr); i < elen; i++) // д(0--1)
+ {
+ if ((rdata[i] & data[i]) != data[i]) // ֮ҪдͬԲ
+ {
+ erflag = 1; // ־
+ break;
+ }
+ }
+
+ // printf("elen=%d, wlen=%d, bufbeg=%d\r\n", elen, wlen, addr-eaddr);
+
+ if (erflag != 0)
+ {
+ SNFlash4kErase(eaddr, 1); // һ
+
+ memcpy(&(rdata[(addr-eaddr)]), data, wlen); // д뻺
+ rslt = SNFlashWrData(eaddr, rdata, SNF_BYTES_PER_SEC); // дflash
+
+ printf("Erase 4K and wr\r\n");
+ }
+ else
+ {
+ // printf("wr to fls\r\n");
+ rslt = SNFlashWrData(addr, data, wlen); // дflash
+ }
+
+ if (rslt != 0)
+ {
+ break;
+ }
+
+ len -= wlen;
+ data += wlen;
+ addr += wlen; // ַ
+ eaddr += SNF_BYTES_PER_SEC;
+ }
+
+ return rslt;
+}
+
+
+//---------------------------------
+
+// : ȴNor
+// ֵ: 0,
+// -1, ʱ
+int SNFWaitNotBusyMs(u32 timeout)
+{
+ u32 i;
+ int rst = -1;
+
+ for (i = 0; i < timeout; i++)
+ {
+ if (SNFIsdStatusBusy() == 0)
+ {
+ rst = 0;
+ break;
+ }
+ DelayMs(1); // ˴滻Ϊʱ
+ }
+
+ return rst;
+}
+
+//---------------------------------
+// : ȴNor
+// ֵ:0
+// -1:ʱ
+int SNFWaitNotBusy10Us(u32 timeout)
+{
+ u32 i;
+ int rst = -1;
+
+ for (i = 0; i < timeout; i++)
+ {
+ if (SNFIsdStatusBusy() == 0)
+ {
+ rst = 0;
+ break;
+ }
+ DelayUs(10); // ˴滻Ϊʱ
+ }
+
+ return rst;
+}
+
+//---------------------------------
+
+void ShowSNFInfo(void)
+{
+ u32 id;
+
+ printf("--------------nor flash info--------------\r\n");
+
+ id = SNFGetManufacDeviceID(); // ȡ id 豸 ID
+ printf("manufacturer id = 0x%x\r\n", HIBYTE(LOWORD(id)));
+ printf("device id = 0x%x\r\n", LOBYTE(LOWORD(id)));
+
+ id = SNFGetJedecID(); // ȡ jedec id
+
+ printf("manufacturer id = 0x%x\r\n", LOBYTE(HIWORD(id)));
+ printf("memory type = 0x%x\r\n", HIBYTE(LOWORD(id)));
+ printf("capacity = 0x%x\r\n", LOBYTE(LOWORD(id)));
+
+ SNFGetUniqueID(); // 8ֽڵΨһк
+
+ printf("------------------------------------------\r\n");
+}
+
+// NorFlash
+void SNFlashTest(char * para1, char * para2)
+{
+ int p1, p2;
+
+ p1 = p2 = 0;
+ if (para1 != NULL && strcmp(para1, "") != 0)
+ {
+ p1 = atoi(para1);
+ }
+ if (para2 != NULL && strcmp(para2, "") != 0)
+ {
+ p2 = atoi(para2);
+ }
+ if (p1 == p2)
+ {
+ }
+ //--------------------------------
+ {
+ u8 buff[1024];
+ int i;
+
+ if (p1 == 0)
+ {// ӵַp2ʼȡ1Kֽ
+ memset(buff, 0, 1024);
+ DatFlashRdData(p2, buff, 1024);
+ printf("DatFlashRdData addr=0x%x,\r\n", p2);
+ for (i = 0; i < 1024; i++)
+ {
+ if ((i%16) == 0)
+ {
+ printf("\r\n%d:\t", i+1);
+ DelayMs(10);
+ }
+ printf("%02x ", buff[i]);
+ }
+ printf("\r\n");
+ }
+ else if (p1 == 1)
+ {// ӵַp2ʼд1Kֽ
+ printf("DatFlashWrDataWithErase addr=0x%x,\r\n", p2);
+
+ for (i = 0; i < 1024; i++)
+ {
+ buff[i] = p2 + i;
+ }
+ DatFlashWrDataWithErase(p2, buff, 1024);
+ printf("done \r\n");
+ }
+ else if (p1 == 3)
+ {// ӵַ0x190000ʼȡ
+ int circle = p2;
+ int count = 0;
+ do
+ {
+ memset(buff, 0, 1024);
+ DatFlashRdData(0x190000+count*0x400, buff, 1024);
+ printf("DatFlashRdData addr=0x%x,\r\n", 0x190000+count*0x400);
+ for (i = 0; i < 1024; i++)
+ {
+ if ((i%16) == 0)
+ {
+ printf("\r\n%d:\t", count*1024+i+1);
+ DelayMs(10);
+ }
+ printf("%02x ", buff[i]);
+ }
+ printf("\r\n");
+ circle--;
+ count++;
+ if (circle <= 0)
+ {
+ break;
+ }
+ }while(1);
+ }
+ }
+}
+
diff --git a/NxFuncs/norflash/norflash.h b/NxFuncs/norflash/norflash.h
new file mode 100644
index 0000000..3e38cb6
--- /dev/null
+++ b/NxFuncs/norflash/norflash.h
@@ -0,0 +1,187 @@
+
+#ifndef __NORFLASH_H__
+#define __NORFLASH_H__
+
+#include "config.h"
+
+//-------------------------------------------------------------------------------
+
+// Norflash ķʽӿ
+// SPIӿ
+
+//----------------------------------------------
+// ֧ W25Q80, W25Q16, W25Q32, W25Q64, W25Q128, W25Q256
+#define W25Q80 8 // 8M Bit 1MB = 1024K = 1024 * 1024 B
+#define W25Q16 16 // 16M Bit 2MB = 2048K = 2 * 1024 * 1024 B
+#define W25Q32 32
+#define W25Q64 64
+#define W25Q128 128 // 128M Bit 16MB
+#define W25Q256 256 // 256M Bit 32MB
+
+// оƬѡ
+#ifndef SERNORFLASHTYPE
+#define SERNORFLASHTYPE W25Q16
+#endif
+
+
+//----------------------------------------------
+
+#define RWSPI 1
+#define RWQPI 2
+
+#ifndef RWMODE
+#define RWMODE RWSPI
+#endif
+
+//----------------------------------------------
+#define RWADDR3 1
+#define RWADDR4 2
+
+#ifndef RWADDRMODE
+#define RWADDRMODE RWADDR3
+#endif
+
+//-------------------------------------------------------------------------------
+
+// Norflash Сֽ
+#define SNF_TOTAL_BYTES (SERNORFLASHTYPE*1024*(1024/8)) // ֽ
+
+#define SNF_BYTES_PER_PAGE 0x100 // ÿҳֽڸ(256)ҳDZдСλҳָ1/4 K
+#define SNF_PAGES_PER_SEC 0x10 // ÿҳ(16)DzСλָ
+#define SNF_BYTES_PER_SEC (SNF_BYTES_PER_PAGE*SNF_PAGES_PER_SEC) // ÿֽڸ(4096) 4K
+
+//-------------------------------------------------------------------------------
+
+// Norflash ʹû֣ͬĻֲͬ
+
+
+// FLASH , Сȱ֤λַ
+
+// |-----------------|-----------------|-------------| // W25Q256 W25Q16 W25Q80
+// | name | begin addr | size |
+// |-----------------|-----------------|-------------|
+// | file area | 0x00 | 0x01000000 | // 16MB
+// |-----------------|-----------------|-------------|
+// | rev area | 0x01000000 | 0x00E00000 | // 14MB
+// |-----------------|-----------------|-------------|
+// | run hour area | 0x01E00000 | 0x00100000 | // 1MB 1MB
+// |-----------------|-----------------|-------------|
+// | para area | 0x01F00000 | 0x00010000 | // 512KB 64KB 64KB
+// |-----------------|-----------------|-------------|
+// | rev area 2 | 0x01F10000 | 0x00070000 | // 512KB 448KB 448KB
+// |-----------------|-----------------|-------------|
+// | update area | 0x01F80000 | 0x00080000 | // 512KB 512KB 512KB
+// |-----------------|-----------------|-------------|
+
+#if (SERNORFLASHTYPE == W25Q256)
+
+#define SNF_DAT_FILE_BEGIN 0x00000000
+#define SNF_DAT_FILE_SIZE 0x01000000 // ļ16MֽڣΪ洢ļչ
+
+#define SNF_RUNHOUR_BEGIN 0x01E00000
+#define SNF_RUNHOUR_SIZE 0x00100000 // ʱ, 1Mֽ
+
+#define SNF_PARAS_BEGIN 0x01F00000
+#define SNF_PARAS_SIZE 0x00010000 // ݴ洢, 64KBֽ
+
+#define SNF_UPDATE_BEGIN 0x01F80000
+#define SNF_UPDATE_SIZE 0x00080000 // ݴ洢, 512KBֽ
+
+#elif (SERNORFLASHTYPE == W25Q16)
+
+#define SNF_PARAS_BEGIN 0x00100000
+#define SNF_PARAS_SIZE 0x00010000 // ݴ洢, 64KBֽ
+
+#define SNF_UPDATE_BEGIN 0x00180000
+#define SNF_UPDATE_SIZE 0x00080000 // ݴ洢, 512KBֽ
+
+#elif (SERNORFLASHTYPE == W25Q80)
+
+#define SNF_PARAS_BEGIN 0x00000000
+#define SNF_PARAS_SIZE 0x00010000 // ݴ洢, 64KBֽ
+
+#define SNF_UPDATE_BEGIN 0x00080000
+#define SNF_UPDATE_SIZE 0x00080000 // ݴ洢, 512KBֽ
+
+#endif
+
+//--------------------------------
+
+//--------------------------------
+
+//--------------------------------
+
+//--------------------------------
+
+
+
+//-------------------------------------------------------------------------------
+// ʼעд
+int SNFlashInit(void (*spicson)(void), void (*spicsoff)(void), u8 (*spird)(void), void (*spiwr)(u8 wb));
+
+// дʹܿ
+void SNFWirteEnable(void);
+
+// дʹܹ
+void SNFWirteDisable(void);
+
+// жNorǷڿ״̬
+int SNFIsdStatusBusy(void);
+
+//
+int SNFlashRdData(u32 addr, u8 * pBuf, int len);
+
+// ٶȡɴﵽ104M
+int SNFFastReadData(u32 addr, u8 * pBuf, int len);
+
+// ҳд[д256ֽ]
+int SNFPageProgram(u32 addr, u8 * pBuf, int len);
+
+// (4KB)
+int SNFlash4kErase(u32 addr, int wait);
+
+// (32KB)
+int SNFlash32kErase(u32 addr, int wait);
+
+// (64KB)
+int SNFlash64kErase(u32 addr, int wait);
+
+// Ƭ
+int SNFlashChipErase(u32 addr, int wait);
+
+// ȡ id 豸 ID
+u32 SNFGetManufacDeviceID(void);
+
+// ȡ JEDEC ID
+u32 SNFGetJedecID(void);
+
+// ȡ Unique ID 8ֽڵΨһк
+u64 SNFGetUniqueID(void);
+
+// д
+int SNFlashWrData(u32 addr, u8 *data, int len);
+
+// дݣԶ
+int SNFlashWrDataWithErase(u32 addr, u8 *data, int len);
+
+// жǷΪ
+int IsSNFlashEmpty(u32 addr, int len);
+
+
+//-------------------------------------------------------------------------------
+
+#define DatFlashInit SNFlashInit
+
+//#define DatFlashRdData SNFlashRdData
+#define DatFlashRdData(saddr, taddr, blen) SNFlashRdData(saddr, (u8*)(taddr), blen)
+#define DatFlashWrData SNFlashWrData
+#define DatFlashWrDataWithErase SNFlashWrDataWithErase
+
+#define IsDatFlashEmpty IsSNFlashEmpty
+
+#define DatFlash4kErase SNFlash4kErase
+
+
+//-------------------------------------------------------------------------------
+
+#endif
diff --git a/NxFuncs/norparas/norparas.c b/NxFuncs/norparas/norparas.c
new file mode 100644
index 0000000..64f3648
--- /dev/null
+++ b/NxFuncs/norparas/norparas.c
@@ -0,0 +1,711 @@
+
+#define _IN_NORPARAS_C
+#include "norparas.h"
+
+
+#if (MAX_PARA_BLOCK > 0)
+#include "norflash.h"
+#include "inout.h"
+#include "shell.h"
+#include "delay.h"
+
+//----------------------------------------------------
+
+#define NORPARA_BEG_ADDR (SNF_PARAS_BEGIN) // ʼַ,ÿռһ,16
+
+#define NP_BLOCK_BYTES SNF_BYTES_PER_PAGE // ÿҳС(һҳ)
+#define NP_SAVE_BYTES_PER_BLOCK SNF_BYTES_PER_SEC // ÿС(һ)
+#define NP_SAVE_BLOCKS_PER_SEC 16 // ÿҳ,һҳ洢ҳЧ־,ʵʹ15ҳڴ洢
+
+
+#define GET_NORPARA_BLOCK_ADDR(bidx) (NORPARA_BEG_ADDR+(bidx)*NP_SAVE_BYTES_PER_BLOCK) // ȡʼַ
+
+//----------------------------------------------------
+
+typedef struct
+{
+ int paraEn; // Ч־
+ NorParaBlock norParaBlock; //
+ s32 * pParaList; // б(,СֵĬֵ)
+ char * pParasName; // б
+
+ // 洢
+ u32 pageFlag[NP_SAVE_BLOCKS_PER_SEC]; // ҳ־
+
+}NorParaBlockCtrl;
+
+NorParaBlockCtrl g_norParaBlockList[MAX_PARA_BLOCK];
+
+//----------------------------------------------------
+
+const char * SHOWP_STR =
+ "\t" " ʾز " "\r\n"
+ "\t" " p1 p2" "\r\n"
+ "\t" " 0 0 ʾȫ " "\r\n"
+ "\t" " b001 0 ʾb " "\r\n"
+ "\t" " b002 0 bĬϲ " "\r\n"
+ "\t" " b003 0 b¼ز " "\r\n"
+;
+
+void ShowPara(char * para1, char * para2);
+
+const char * SETP_STR =
+ "\t" "ò " "\r\n"
+ "\t" " p1 p2" "\r\n"
+ "\t" " b00x val òb, ID x, ֵ val " "\r\n"
+ "\t" " 10b000 0 b " "\r\n"
+;
+
+void SetPara(char * para1, char * para2);
+//----------------------------------------------------
+
+void InitNorParas(void)
+{
+ static int g_inited = 0;
+
+ if (g_inited == 0)
+ {
+ g_inited = 1;
+ InitNorSpi(); // ʼ nor flash SPI
+ SNFlashInit(SetNorSpiNssOn, SetNorSpiNssOff, NorSpiReadByte, NorSpiWriteByte); // ʼnor flash עд
+
+ // ʼ
+ for(int i = 0; i < MAX_PARA_BLOCK; i++)
+ {
+ memset(&g_norParaBlockList[i], 0, sizeof(NorParaBlockCtrl));
+ LoadNorParas(i);
+ }
+ AddShellCmd("SHOWPARA", SHOWP_STR, ShowPara);
+ AddShellCmd("SETPARA", SETP_STR, SetPara);
+ }
+}
+
+// ȡЧ־
+int GetNorParaEn(int bIdx)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+
+ return g_norParaBlockList[bIdx].paraEn;
+}
+
+// زҳЧ־
+int LoadParaPageFlag(int bIdx)
+{
+ NorParaBlockCtrl * pCtrl;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+ pCtrl = &g_norParaBlockList[bIdx];
+
+ return DatFlashRdData(GET_NORPARA_BLOCK_ADDR(bIdx), (u8 *)(&pCtrl->pageFlag[0]), NP_SAVE_BLOCKS_PER_SEC*sizeof(u32));
+}
+
+// ҳЧ־
+int SaveParaPageFlag(int bIdx)
+{
+ NorParaBlockCtrl * pCtrl;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+ pCtrl = &g_norParaBlockList[bIdx];
+
+ return DatFlashWrData(GET_NORPARA_BLOCK_ADDR(bIdx), (u8 *)(&pCtrl->pageFlag[0]), NP_SAVE_BLOCKS_PER_SEC*sizeof(u32));
+}
+
+// òҳЧ־
+int SetParaPageFlagValue(int bIdx, int pIdx, int enFlag)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK || pIdx < 0 || pIdx >= NP_SAVE_BLOCKS_PER_SEC)
+ {
+ return -1;
+ }
+
+ if (enFlag == 0)
+ {
+ g_norParaBlockList[bIdx].pageFlag[pIdx] = 0; // ʧЧ,0xffffffffδʹҳ
+ }
+ else
+ {
+ g_norParaBlockList[bIdx].pageFlag[pIdx] = PARA_VALID+pIdx; // Ч
+ }
+
+ return 0;
+}
+
+// Ӳҳ־õǰЧҳ
+int GetSaveIdxFromPageFlag(int bIdx)
+{
+ int i;
+ NorParaBlockCtrl * pCtrl;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+
+ pCtrl = &g_norParaBlockList[bIdx];
+
+ for(i = 1; i < NP_SAVE_BLOCKS_PER_SEC; i++)
+ {
+ if (pCtrl->pageFlag[i] == PARA_VALID+i)
+ {
+ return i;
+ }
+ }
+
+ return -2;
+}
+
+// õһδʹҳ
+int GetNextSaveIdxFromPageFlag(int bIdx)
+{
+ int i;
+ NorParaBlockCtrl * pCtrl;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+
+ pCtrl = &g_norParaBlockList[bIdx];
+
+ for (i = 1; i < NP_SAVE_BLOCKS_PER_SEC; i++)
+ {
+ if (pCtrl->pageFlag[i] == 0xffffffff)
+ {
+ return i;
+ }
+ }
+
+ return -2;
+}
+
+// ȡ
+// bIdx:ID
+// return: -1:ش,вҳ,δҵЧ
+// 0:ȷֵ
+int LoadNorParas(int bIdx)
+{
+ u32 addr; //
+ NorParaBlockCtrl * pCtrl;
+ int idx, rslt;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+
+ pCtrl = &g_norParaBlockList[bIdx];
+
+ memset(pCtrl, 0, sizeof(NorParaBlockCtrl));
+
+ // 洢Ч־
+ rslt = LoadParaPageFlag(bIdx);
+ if (rslt < 0)
+ {
+ return -1;
+ }
+
+ idx = GetSaveIdxFromPageFlag(bIdx); // õǰЧҳid
+
+ if (idx < 0)
+ {
+ printf("load nor para error, code=%d\r\n", idx);
+ return -1;
+ }
+
+ printf("load nor para block %d, page is %d\r\n", bIdx, idx);
+
+ addr = GET_NORPARA_BLOCK_ADDR(bIdx) + (idx * NP_BLOCK_BYTES);
+ DatFlashRdData(addr, (u8*)&pCtrl->norParaBlock, sizeof(NorParaBlock));
+
+ g_norParaBlockList[bIdx].paraEn = PARA_VALID; // Ч
+
+ return 0;
+}
+
+//
+//bIdx IJID
+int SaveNorParas(int bIdx)
+{
+ u32 addr;
+ int cidx, nidx;
+
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return -1;
+ }
+
+ cidx = GetSaveIdxFromPageFlag(bIdx);
+ nidx = GetNextSaveIdxFromPageFlag(bIdx);
+ if (cidx < 0)
+ {
+ cidx = 0;
+ }
+
+ if (nidx < 0) //
+ {
+ printf("overflow, erase 4k\r\n");
+ DatFlash4kErase(GET_NORPARA_BLOCK_ADDR(bIdx), 1); //
+ LoadParaPageFlag(bIdx);
+ cidx = 0;
+ nidx = GetNextSaveIdxFromPageFlag(bIdx);
+ }
+
+ if (nidx < 0) //
+ {
+ printf("SaveNorParas error\r\n");
+ return -2;
+ }
+
+ // 洢֮ҳ
+ addr = GET_NORPARA_BLOCK_ADDR(bIdx) + ((nidx) * NP_BLOCK_BYTES);
+ DatFlashWrDataWithErase(addr, (u8 *)&g_norParaBlockList[bIdx].norParaBlock, sizeof(NorParaBlock));
+
+ SetParaPageFlagValue(bIdx, nidx, 1); // ²洢ҳЧ
+
+ SetParaPageFlagValue(bIdx, cidx, 0); // ɵIJ洢ҳ
+
+ SaveParaPageFlag(bIdx); // ҳ־
+
+ g_norParaBlockList[bIdx].paraEn = PARA_VALID; // Ч
+
+ printf("save nor para successful, page is %d \r\n", nidx);
+
+ return 0;
+}
+
+
+// ȡز
+NorParaBlock * GetNorParaBlock(int bIdx)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK)
+ {
+ return NULL;
+ }
+
+ return &g_norParaBlockList[bIdx].norParaBlock;
+}
+
+// ò
+void SetNorParaNameString(int bIdx, void * pName)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK )
+ {
+ return;
+ }
+
+ g_norParaBlockList[bIdx].pParasName = pName;
+}
+
+// òб(,СֵĬֵ)
+void SetNorParaList(int bIdx, void * pPara)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK )
+ {
+ return;
+ }
+
+ g_norParaBlockList[bIdx].pParaList = pPara;
+}
+
+// Ĭϲ
+void LoadNorDefPara(int bIdx)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK || g_norParaBlockList[bIdx].pParaList == NULL)
+ {
+ return;
+ }
+
+ for(int i = 0; i < PARA_NUM_PER_BLK; i++)
+ {
+ int offset = i * 4 + 3;
+ g_norParaBlockList[bIdx].norParaBlock.buff[i] = * ( g_norParaBlockList[bIdx].pParaList + offset );
+ }
+}
+
+
+// Χ(ڵȫ)
+void CheckParaRange(int bIdx)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK || g_norParaBlockList[bIdx].pParaList == NULL)
+ {
+ return;
+ }
+
+ for(int i = 0; i < PARA_NUM_PER_BLK; i++)
+ {
+ int paratype, minOffset, maxOffset; // ,Сֵָƫ
+ paratype = (i * 4);
+ minOffset = (i * 4 + 1);
+ maxOffset = (i * 4 + 2);
+ if ((*(g_norParaBlockList[bIdx].pParaList + paratype)) == PTYPE_S)
+ {
+ if (g_norParaBlockList[bIdx].norParaBlock.buff[i] < (*(g_norParaBlockList[bIdx].pParaList + minOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[i] = (*( g_norParaBlockList[bIdx].pParaList + minOffset));
+ printf("less than min, equal min, block %d, id is %d\r\n", bIdx, i+1);
+ }
+ else if (g_norParaBlockList[bIdx].norParaBlock.buff[i] > (*( g_norParaBlockList[bIdx].pParaList + maxOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[i] = (*( g_norParaBlockList[bIdx].pParaList + maxOffset));
+ printf("more than max, equal max, block %d, id is %d\r\n", bIdx, i+1);
+ }
+ }
+ else if ((*(g_norParaBlockList[bIdx].pParaList + paratype)) == PTYPE_U)
+ {
+ if ((u32)g_norParaBlockList[bIdx].norParaBlock.buff[i] < (u32)(*(g_norParaBlockList[bIdx].pParaList + minOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[i] = (*( g_norParaBlockList[bIdx].pParaList + minOffset));
+ printf("less than min, equal min, block %d, id is %d\r\n", bIdx, i+1);
+ }
+ else if ((u32)g_norParaBlockList[bIdx].norParaBlock.buff[i] > (u32)(*( g_norParaBlockList[bIdx].pParaList + maxOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[i] = (*( g_norParaBlockList[bIdx].pParaList + maxOffset));
+ printf("more than max, equal max, block %d, id is %d\r\n", bIdx, i+1);
+ }
+ }
+ }
+}
+
+
+// Χ(ڵij)
+void CheckAParaRange(int bIdx, int id)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK || g_norParaBlockList[bIdx].pParaList == NULL)
+ {
+ return;
+ }
+
+ if (id >= 0 && id < PARA_NUM_PER_BLK)
+ {
+ int paratype, minOffset, maxOffset; // ,Сֵָƫ
+ paratype = (id * 4);
+ minOffset = (id * 4 + 1);
+ maxOffset = (id * 4 + 2);
+ if ((*(g_norParaBlockList[bIdx].pParaList + paratype)) == PTYPE_S)
+ {
+ if (g_norParaBlockList[bIdx].norParaBlock.buff[id] < (*( g_norParaBlockList[bIdx].pParaList + minOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[id] = (*( g_norParaBlockList[bIdx].pParaList + minOffset));
+ printf("less than min, equal min\r\n");
+ }
+ else if (g_norParaBlockList[bIdx].norParaBlock.buff[id] > (*( g_norParaBlockList[bIdx].pParaList + maxOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[id] = (*( g_norParaBlockList[bIdx].pParaList + maxOffset));
+ printf("more than max, equal max\r\n");
+ }
+ }
+ else if ((*(g_norParaBlockList[bIdx].pParaList + paratype)) == PTYPE_U)
+ {
+ if ((u32)g_norParaBlockList[bIdx].norParaBlock.buff[id] < (u32)(*( g_norParaBlockList[bIdx].pParaList + minOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[id] = (*( g_norParaBlockList[bIdx].pParaList + minOffset));
+ printf("less than min, equal min\r\n");
+ }
+ else if ((u32)g_norParaBlockList[bIdx].norParaBlock.buff[id] > (u32)(*( g_norParaBlockList[bIdx].pParaList + maxOffset)) )
+ {
+ g_norParaBlockList[bIdx].norParaBlock.buff[id] = (*( g_norParaBlockList[bIdx].pParaList + maxOffset));
+ printf("more than max, equal max\r\n");
+ }
+ }
+ }
+}
+
+
+// ȡһ
+s32 GetANorPara(int bIdx, int id)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK )
+ {
+ return -1;
+ }
+
+ if (GetNorParaEn(bIdx) == PARA_VALID)
+ {
+ int idx = id - 1;
+
+ if (idx >= 0 && idx < PARA_NUM_PER_BLK)
+ {
+ return g_norParaBlockList[bIdx].norParaBlock.buff[idx];
+ }
+ }
+ return 0;
+}
+
+// һ
+// úṩ湦,ɺֶ
+// ע:norflashƵд
+void SetANorPara(int bIdx, int id, s32 val)
+{
+ if (bIdx < 0 || bIdx >= MAX_PARA_BLOCK )
+ {
+ return;
+ }
+
+ char * pInfo = NULL;
+ int idx = id - 1;
+
+ if (idx >= 0 && idx < PARA_NUM_PER_BLK)
+ {
+ if ((*(g_norParaBlockList[bIdx].pParaList + idx*4)) == PTYPE_S)
+ {
+ s32 old;
+
+ pInfo = (g_norParaBlockList[bIdx].pParasName+(idx)*PARA_STR_LEN);
+
+ printf("set para block %d\r\n", bIdx+1);
+
+ old = g_norParaBlockList[bIdx].norParaBlock.buff[idx];
+ g_norParaBlockList[bIdx].norParaBlock.buff[idx] = val;
+
+ CheckAParaRange(bIdx, idx);
+
+ if (pInfo == NULL)
+ {
+ pInfo = "";
+ }
+
+ printf("%d. (%s) = %d, oldvalue=%d\r\n", (id), pInfo, val, old);
+ }
+ else
+ {
+ u32 old;
+
+ pInfo = (g_norParaBlockList[bIdx].pParasName+(idx)*PARA_STR_LEN);
+
+ printf("set para block %d\r\n", bIdx+1);
+
+ old = (u32)g_norParaBlockList[bIdx].norParaBlock.buff[idx];
+ g_norParaBlockList[bIdx].norParaBlock.buff[idx] = val;
+
+ CheckAParaRange(bIdx, idx);
+
+ if (pInfo == NULL)
+ {
+ pInfo = "";
+ }
+
+ printf("%d. (%s) = %d, oldvalue=%d\r\n", (id), pInfo, (u32)val, old);
+ }
+ }
+}
+
+
+/*
+ * p1 p2
+ * 1001 val // ò1,ID 1,ֵval
+ * 1002 val // ò1,ID 2,ֵval
+ ......
+ * 2001 val // ò2,ID 1,ֵval
+ * 2002 val // ò2,ID 2,ֵval //ṩ湦
+ ......
+ * 101000 // 1
+ * 102000 // 2
+ */
+
+void SetPara(char * para1, char * para2)
+{
+ int p1, p2, p3;
+
+ if (para1 == NULL || para2 == NULL)
+ {
+ return;
+ }
+
+ printf("para1=%s, para2=%s\r\n", para1, para2);
+
+ p1 = 0;
+ p2 = 0;
+ if (strcmp(para1, "") != 0)
+ {
+ p1 = atoi(para1);
+ }
+ if (strcmp(para2, "") != 0)
+ {
+ p2 = atoi(para2);
+ }
+ if (p1 == p2)
+ {
+ }
+
+ p3 = p1 / 1000; // id
+ p1 = p1 % 1000; // id
+ // p2:ֵ
+
+ if (p3 > 0 && p3 <= MAX_PARA_BLOCK)
+ {
+ SetANorPara(p3-1, p1, p2);
+ }
+ else if (p3 > 100 && p3 <= 116)
+ {
+ p3 -= 101;
+ printf("save block %d\r\n", p3+1);
+ SaveNorParas(p3);
+ }
+}
+
+/*
+ * p1 p2
+ * // ʾȫ
+ * 1001 // ʾ1
+ * 2001 // ʾ2
+ * 1002 // 1Ĭϲ
+ * 2002 // 2Ĭϲ
+ * 1003 // 1¼ز
+ * 2003 // 2¼ز
+ */
+void ShowPara(char * para1, char * para2)
+{
+ int p1, p2, p3;
+
+ if (para1 == NULL || para2 == NULL)
+ {
+ return;
+ }
+
+ printf("para1=%s, para2=%s\r\n", para1, para2);
+
+ p1 = 0;
+ p2 = 0;
+ if (strcmp(para1, "") != 0)
+ {
+ p1 = atoi(para1);
+ }
+ if (strcmp(para2, "") != 0)
+ {
+ p2 = atoi(para2);
+ }
+ if (p1 == p2)
+ {
+ }
+ p3 = p1 / 1000; // id
+ p1 = p1 % 1000; //
+ // p2: ID
+
+ if (p3 <= MAX_PARA_BLOCK)
+ {
+ switch(p1)
+ {
+ case 0:
+ {
+ // ʾȫ
+ for (int j = 0; j < MAX_PARA_BLOCK; j++)
+ {
+ printf("\r\npara block %d:\r\n", j+1);
+
+ if (g_norParaBlockList[j].pParasName == NULL)
+ {
+ continue;
+ }
+
+ for(int i = 0; i < PARA_NUM_PER_BLK; i++)
+ {
+ char * pStr;
+ pStr = g_norParaBlockList[j].pParasName + (i*PARA_STR_LEN);
+ if (pStr == NULL)
+ {
+ pStr = "";
+ }
+
+ if ( strcmp(pStr, "") != 0 )
+ {
+ if ((*(g_norParaBlockList[j].pParaList+i*4)) == PTYPE_S)
+ {
+ printf("%d. (%s) val=%d, min=%d, max=%d, def=%d\r\n", i+1, pStr,
+ GetANorPara(j, i+1),
+ *(g_norParaBlockList[j].pParaList+ i*4+1),
+ *(g_norParaBlockList[j].pParaList+ i*4+2),
+ *(g_norParaBlockList[j].pParaList+ i*4+3) );
+ }
+ else
+ {
+ printf("%d. (%s) val=%d, min=%d, max=%d, def=%d\r\n", i+1, pStr,
+ (u32)GetANorPara(j, i+1),
+ (u32)(*(g_norParaBlockList[j].pParaList+ i*4+1)),
+ (u32)(*(g_norParaBlockList[j].pParaList+ i*4+2)),
+ (u32)(*(g_norParaBlockList[j].pParaList+ i*4+3)) );
+ }
+ }
+ DelayMs(1);
+ }
+ }
+ break;
+ }
+ case 1:
+ {
+ // ʾij
+ printf("\r\npara block %d:\r\n", p3);
+
+ if (g_norParaBlockList[p3-1].pParasName != NULL)
+ {
+ for(int i = 0; i < PARA_NUM_PER_BLK; i++)
+ {
+ char * pStr;
+ pStr = g_norParaBlockList[p3-1].pParasName + (i*PARA_STR_LEN);
+ if (pStr == NULL)
+ {
+ pStr = "";
+ }
+
+ if ( strcmp(pStr, "") != 0 )
+ {
+ if ((*(g_norParaBlockList[j].pParaList+i*4)) == PTYPE_S)
+ {
+ printf("%d. (%s) val=%d, min=%d, max=%d, def=%d\r\n", i+1, pStr,
+ GetANorPara(p3-1, i+1),
+ *(g_norParaBlockList[p3-1].pParaList+ i*4+1),
+ *(g_norParaBlockList[p3-1].pParaList+ i*4+2),
+ *(g_norParaBlockList[p3-1].pParaList+ i*4+3) );
+ }
+ else
+ {
+ printf("%d. (%s) val=%d, min=%d, max=%d, def=%d\r\n", i+1, pStr,
+ (u32)GetANorPara(p3-1, i+1),
+ (u32)(*(g_norParaBlockList[p3-1].pParaList+ i*4+1)),
+ (u32)(*(g_norParaBlockList[p3-1].pParaList+ i*4+2)),
+ (u32)(*(g_norParaBlockList[p3-1].pParaList+ i*4+3)) );
+ }
+ }
+ DelayMs(1);
+ }
+ }
+ break;
+ }
+ case 2:
+ {
+ int bidx = p3 - 1;
+ // Ĭϲ
+ if (bidx >= 0)
+ {
+ printf("load def para block %d:\r\n", p3);
+ LoadNorDefPara(bidx);
+ }
+ break;
+ }
+ case 3:
+ {
+ int bidx = p3 - 1;
+ if (bidx >= 0)
+ {
+ printf("load para block %d:\r\n", p3);
+ // ¼ز
+ LoadNorParas(bidx);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+}
+
+#endif
+
diff --git a/NxFuncs/norparas/norparas.h b/NxFuncs/norparas/norparas.h
new file mode 100644
index 0000000..8718657
--- /dev/null
+++ b/NxFuncs/norparas/norparas.h
@@ -0,0 +1,65 @@
+
+#ifndef __NORPARAS_H__
+#define __NORPARAS_H__
+
+#include "config.h"
+
+// Ķд
+
+// norflashĴ
+
+#ifndef MAX_PARA_BLOCK // ֲ֧
+#define MAX_PARA_BLOCK (0)
+#endif
+
+#if (MAX_PARA_BLOCK > 16) // ֧16
+#undef MAX_PARA_BLOCK
+#define MAX_PARA_BLOCK 16
+#endif
+
+
+
+#define PARA_NUM_PER_BLK (64) // 64,ÿռ4ֽ,256ֽ(һҳ)
+
+#define PARA_STR_LEN (30) // Ƴ
+
+#define PARA_VALID 0x55AA // Ч־,Զ
+
+//------------------------------------------------------------------------------
+
+typedef struct
+{
+ s32 buff[PARA_NUM_PER_BLK];
+}NorParaBlock;
+
+//
+#define PTYPE_S 0 // з
+#define PTYPE_U 1 //
+#define PTYPE_B 2 // λͼ
+
+//------------------------------------------------------------------------------
+
+
+void InitNorParas(void); // ʼ
+
+int GetNorParaEn(int bIdx); // ȡЧ־
+
+int LoadNorParas(int bIdx); // ȡ bIdx:ID
+
+int SaveNorParas(int bIdx); //
+
+NorParaBlock * GetNorParaBlock(int bIdx); // ȡز
+
+void SetNorParaNameString(int bIdx, void * pName); // ò
+void SetNorParaList(int bIdx, void * pPara); // òб
+void LoadNorDefPara(int bIdx); // Ĭϲ
+void CheckParaRange(int bIdx); // Χ(ȫ)
+void CheckAParaRange(int bIdx, int id); // Χ()
+
+s32 GetANorPara(int bIdx, int id); //õֵ
+void SetANorPara(int bIdx, int id, s32 val); //õֵ
+
+
+//------------------------------------------------------------------------------
+
+#endif // __NORPARAS_H__
diff --git a/NxFuncs/stadc/adcctrl.c b/NxFuncs/stadc/adcctrl.c
new file mode 100644
index 0000000..f92ffad
--- /dev/null
+++ b/NxFuncs/stadc/adcctrl.c
@@ -0,0 +1,321 @@
+
+#include "adcctrl.h"
+
+#if (MAX_ADC1_CHANNEL_NUM != 0 || MAX_ADC2_CHANNEL_NUM != 0 || MAX_ADC3_CHANNEL_NUM != 0)
+
+#include "adc.h"
+
+
+#include "filter.h"
+
+#if (MAX_ADC1_CHANNEL_NUM > 0)
+
+//-------------------------------------------------------------------------------
+
+// ad ˲ȼ
+#ifndef ADC1_FILTER_NUM
+#define ADC1_FILTER_NUM (20) // ˲
+#endif
+
+#ifndef HADC1
+#define HADC1 hadc1
+#endif
+
+#define ADC1VALBUFSIZE (ADC1_FILTER_NUM * MAX_ADC1_CHANNEL_NUM)
+
+u16 g_adc1valuebuf[ADC1VALBUFSIZE];
+
+LPF1stData g_adc1lpf1st[MAX_ADC1_CHANNEL_NUM];
+LPF2ndData g_adc1lpf2nd[MAX_ADC1_CHANNEL_NUM];
+static int g_adc1Inited = 0;
+
+void InitADC1(void)
+{
+ int i;
+
+ if (g_adc1Inited == 0)
+ {
+ g_adc1Inited = 1;
+ memset(g_adc1valuebuf, 0, ADC1VALBUFSIZE*sizeof(u16));
+
+ // ʼ˲
+ for (i = 0; i < MAX_ADC1_CHANNEL_NUM; i++)
+ {
+ memcpy(&g_adc1lpf1st[i], &defaultLPF1st, sizeof(LPF1stData));
+ memcpy(&g_adc1lpf2nd[i], &defaultLPF2nd, sizeof(LPF2ndData));
+ }
+ HAL_ADC_Start_DMA(&HADC1, (u32*)(&g_adc1valuebuf[0]), ADC1VALBUFSIZE);
+ HAL_ADC_Start(&HADC1);
+ }
+}
+
+void ADC1IntProc(void)
+{
+/*
+ if(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == SET)
+ {
+ ADC_ClearFlag(ADC1,ADC_FLAG_EOC);
+ }
+*/
+}
+
+/*
+ * HAL_ADC_PollForConversion(&HADC1, 0); // ȴת
+ * if (HAL_IS_BIT_SET(HAL_ADC_GetState(&HADC1), HAL_ADC_STATE_REG_EOC))
+ * ADCжģʽֵֻ֧ͨ
+ * ADCжϻص
+ */
+void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
+{
+ static int i = 0;
+
+ g_adc1valuebuf[i] = HAL_ADC_GetValue(hadc);
+ i++;
+ if (i >= ADC1VALBUFSIZE)
+ {
+ i = 0;
+ }
+}
+
+s32 GetADC1Value(int channelIdx, int flev)
+{
+ int i;
+ s32 value = 0;
+ int buff[ADC1_FILTER_NUM];
+ int * pTBuf;
+ u16 * pSBuf;
+
+ if (g_adc1Inited == 0 || channelIdx < 0 || channelIdx >= MAX_ADC1_CHANNEL_NUM)
+ {
+ return 0;
+ }
+
+ // ǰͨIJɼ
+ pSBuf = &(g_adc1valuebuf[channelIdx]);
+ pTBuf = &(buff[0]);
+ for (i = 0; i < ADC1_FILTER_NUM; i++)
+ {
+ *pTBuf = (int)(*pSBuf);
+ pTBuf++;
+ pSBuf += MAX_ADC1_CHANNEL_NUM;
+ }
+
+ // ĬΪλֵƽ˲
+ value = MAFilter(buff, ADC1_FILTER_NUM);
+
+ // һ˲
+ if (flev >= 1)
+ {
+ value = LPF1st(&g_adc1lpf1st[channelIdx], value);
+ }
+
+ // ˲
+ if (flev >= 2)
+ {
+ value = LPF2nd(&g_adc1lpf2nd[channelIdx], value);
+ }
+
+ return value;
+}
+
+#endif
+
+//----------------------------------------------
+
+#if (MAX_ADC2_CHANNEL_NUM > 0)
+
+// ad ˲ȼ
+#ifndef ADC2_FILTER_NUM
+#define ADC2_FILTER_NUM (10) // ˲
+#endif
+
+#ifndef HADC2
+#define HADC2 hadc2
+#endif
+
+#define ADC2VALBUFSIZE (ADC2_FILTER_NUM * MAX_ADC2_CHANNEL_NUM)
+
+u16 g_adc2valuebuf[ADC2VALBUFSIZE];
+
+LPF1stData g_adc2lpf1st[MAX_ADC2_CHANNEL_NUM];
+LPF2ndData g_adc2lpf2nd[MAX_ADC2_CHANNEL_NUM];
+static int g_adc2Inited = 0;
+
+void InitADC2(void)
+{
+ int i;
+
+ if (g_adc2Inited == 0)
+ {
+ g_adc2Inited = 1;
+ memset(g_adc2valuebuf, 0, ADC2VALBUFSIZE*sizeof(u16));
+
+ // ʼ˲
+ for (i = 0; i < MAX_ADC2_CHANNEL_NUM; i++)
+ {
+ memcpy(&g_adc2lpf1st[i], &defaultLPF1st, sizeof(LPF1stData));
+ memcpy(&g_adc2lpf2nd[i], &defaultLPF2nd, sizeof(LPF2ndData));
+ }
+
+ HAL_ADC_Start_DMA(&HADC2, (u32*)(&g_adc2valuebuf[0]), ADC2VALBUFSIZE);
+ HAL_ADC_Start(&HADC2);
+ }
+}
+
+void ADC2IntProc(void)
+{
+/*
+ if(ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC) == SET)
+ {
+ ADC_ClearFlag(ADC2,ADC_FLAG_EOC);
+ }
+*/
+}
+
+
+s32 GetADC2Value(int channelIdx, int flev)
+{
+ int i;
+ s32 value = 0;
+ int buff[ADC2_FILTER_NUM];
+ int * pTBuf;
+ u16 * pSBuf;
+
+ if (g_adc2Inited == 0 || channelIdx < 0 || channelIdx >= MAX_ADC2_CHANNEL_NUM)
+ {
+ return 0;
+ }
+
+ // ǰͨIJɼ
+ pSBuf = &(g_adc2valuebuf[channelIdx]);
+ pTBuf = &(buff[0]);
+ for (i = 0; i < ADC2_FILTER_NUM; i++)
+ {
+ *pTBuf = (int)(*pSBuf);
+ pTBuf++;
+ pSBuf += MAX_ADC2_CHANNEL_NUM;
+ }
+
+ // ĬΪλֵƽ˲
+ value = MAFilter(buff, ADC2_FILTER_NUM);
+
+ // һ˲
+ if (flev >= 1)
+ {
+ value = LPF1st(&g_adc2lpf1st[channelIdx], value);
+ }
+
+ // ˲
+ if (flev >= 2)
+ {
+ value = LPF2nd(&g_adc2lpf2nd[channelIdx], value);
+ }
+
+ return value;
+}
+
+#endif
+
+//-------------------------------------------------------------------------------
+
+#if (MAX_ADC3_CHANNEL_NUM > 0)
+// ad ˲ȼ
+#ifndef ADC3_FILTER_NUM
+#define ADC3_FILTER_NUM 5
+#endif
+
+#ifndef HADC3
+#define HADC3 hadc3
+#endif
+
+#define ADC3VALBUFSIZE (ADC3_FILTER_NUM * MAX_ADC3_CHANNEL_NUM)
+
+u16 g_adc3valuebuf[ADC3VALBUFSIZE];
+
+LPF1stData g_adc3lpf1st[MAX_ADC3_CHANNEL_NUM];
+LPF2ndData g_adc3lpf2nd[MAX_ADC3_CHANNEL_NUM];
+static int g_adc3Inited = 0;
+
+
+void InitADC3(void)
+{
+ int i;
+
+ if (g_adc3Inited == 0)
+ {
+ g_adc3Inited = 1;
+ memset(g_adc3valuebuf, 0, ADC3VALBUFSIZE*sizeof(u16));
+
+ // ʼ˲
+ for (i = 0; i < MAX_ADC3_CHANNEL_NUM; i++)
+ {
+ memcpy(&g_adc3lpf1st[i], &defaultLPF1st, sizeof(LPF1stData));
+ memcpy(&g_adc3lpf2nd[i], &defaultLPF2nd, sizeof(LPF2ndData));
+ }
+
+ HAL_ADC_Start_DMA(&HADC3, (u32*)(&g_adc3valuebuf[0]), ADC3VALBUFSIZE);
+ HAL_ADC_Start(&HADC3);
+ }
+}
+
+
+
+void ADC3IntProc(void)
+{
+/*
+ if(ADC_GetFlagStatus(ADC3, ADC_FLAG_EOC) == SET)
+ {
+ ADC_ClearFlag(ADC3,ADC_FLAG_EOC);
+ }
+*/
+}
+
+
+s32 GetADC3Value(int channelIdx, int flev)
+{
+ int i;
+ s32 value = 0;
+ int buff[ADC3_FILTER_NUM];
+ int * pTBuf;
+ u16 * pSBuf;
+
+ if (g_adc3Inited == 0 || channelIdx < 0 || channelIdx >= MAX_ADC3_CHANNEL_NUM)
+ {
+ return 0;
+ }
+
+ // ǰͨIJɼ
+ pSBuf = &(g_adc3valuebuf[channelIdx]);
+ pTBuf = &(buff[0]);
+ for (i = 0; i < ADC3_FILTER_NUM; i++)
+ {
+ *pTBuf = (int)(*pSBuf);
+ pTBuf++;
+ pSBuf += MAX_ADC3_CHANNEL_NUM;
+ }
+
+ // ĬΪλֵƽ˲
+ value = MAFilter(buff, ADC3_FILTER_NUM);
+
+ // һ˲
+ if (flev >= 1)
+ {
+ value = LPF1st(&g_adc3lpf1st[channelIdx], value);
+ }
+
+ // ˲
+ if (flev >= 2)
+ {
+ value = LPF2nd(&g_adc3lpf2nd[channelIdx], value);
+ }
+
+ return value;
+}
+
+
+#endif
+
+//-------------------------------------------------------------------------------
+
+#endif
+
diff --git a/NxFuncs/stadc/adcctrl.h b/NxFuncs/stadc/adcctrl.h
new file mode 100644
index 0000000..96833b3
--- /dev/null
+++ b/NxFuncs/stadc/adcctrl.h
@@ -0,0 +1,44 @@
+
+#ifndef __ADCCTRL_H__
+#define __ADCCTRL_H__
+
+#include "config.h"
+
+#ifndef MAX_ADC1_CHANNEL_NUM // ֧ͨ
+#define MAX_ADC1_CHANNEL_NUM 0
+#endif
+
+#ifndef MAX_ADC2_CHANNEL_NUM // ֧ͨ
+#define MAX_ADC2_CHANNEL_NUM 0
+#endif
+
+#ifndef MAX_ADC3_CHANNEL_NUM // ֧ͨ
+#define MAX_ADC3_CHANNEL_NUM 0
+#endif
+
+
+#if (MAX_ADC1_CHANNEL_NUM > 0)
+void InitADC1(void);
+s32 GetADC1Value(int channelIdx, int flev); // ȡADC1ֵ
+void ADC1IntProc(void); // ADCжӦ
+
+#endif
+
+#if (MAX_ADC2_CHANNEL_NUM > 0)
+
+void InitADC2(void);
+s32 GetADC2Value(int channelIdx, int lev); // ȡADC2ֵ
+void ADC2IntProc(void); // ADCжӦ
+
+#endif
+
+#if (MAX_ADC3_CHANNEL_NUM > 0)
+
+void InitADC3(void);
+s32 GetADC3Value(int channelIdx, int lev); // ȡADC3ֵ
+void ADC3IntProc(void); // ADCжӦ
+
+#endif
+
+#endif /* __ADC_H__ */
+
diff --git a/NxFuncs/stadc/filter.c b/NxFuncs/stadc/filter.c
new file mode 100644
index 0000000..7a89115
--- /dev/null
+++ b/NxFuncs/stadc/filter.c
@@ -0,0 +1,155 @@
+
+#define _IN_FILTER_C
+#include "filter.h"
+
+//------------------------------------------------------
+// һͺ˲
+#if (1)
+
+int LPF1st(LPF1stData * pLpf1st, int newData)
+{
+ int data = 0;
+ if (pLpf1st != NULL)
+ {
+ if (pLpf1st->f1value < 0)
+ {
+ pLpf1st->f1value = newData;
+ }
+
+ // һͺ˲
+ pLpf1st->f1value = newData * pLpf1st->lowpassxs + pLpf1st->f1value * (1-pLpf1st->lowpassxs);
+ data = pLpf1st->f1value;
+ }
+
+ return data;
+}
+
+#endif
+
+// IIR˲
+#if (1)
+
+//------------------------------------------------------
+
+int LPF2nd(LPF2ndData * pLpf2nd, int newData)
+{
+ int data = 0;
+
+ if (pLpf2nd != NULL)
+ {
+ if (pLpf2nd->f2value < 0)
+ {
+ pLpf2nd->preout = newData;
+ pLpf2nd->lastout = newData;
+ }
+
+ // ڶIIR˲ʽ:Yn)= b0*xn + b1*xn-1 + b2*xn-2 - (a1*xn-1 + a2*xn-2)
+
+ // ˴b1 * xn-1 + b2 * xn-2 b1b2ϵΪ0
+ pLpf2nd->f2value = (newData * pLpf2nd->b0)+ (pLpf2nd->lastout * pLpf2nd->a1) - (pLpf2nd->preout * pLpf2nd->a2);
+
+ // ֵ´
+ pLpf2nd->preout = pLpf2nd->lastout;
+ pLpf2nd->lastout = pLpf2nd->f2value;
+ data = pLpf2nd->lastout;
+ }
+
+ return data;
+}
+
+#endif
+
+//------------------------------------------------------
+
+// Ȩƽ˲
+#if (1)
+
+// Ȩֵ
+int WRAFilter(int * pBuff, int len)
+{
+ float value = 0;
+ int i;
+ int coe, coesum;
+
+ if (pBuff == NULL || len <= 0)
+ {
+ return 0;
+ }
+
+ coe = 1; // Ȩֵ1ʼ
+ coesum = 0;
+ for (i = 0; i < len; i++)
+ {
+ value += *pBuff++ * coe; // Ȩ
+ coesum += coe;
+ coe++; // ȨֵӣȨֵ
+ }
+ value /= coesum; // Ȩƽֵ
+
+ return value;
+}
+
+#endif
+
+//------------------------------------------------------
+
+// λֵƽ˲
+#if (1)
+
+int MAFilter(int * pBuff, int len)
+{
+ int i;
+ s32 value = 0;
+
+ if (pBuff == NULL || len <= 0)
+ {
+ return 0;
+ }
+
+ if (len <= 5) // ٣ֱȡƽֵ
+ {
+ // ȡƽ
+ for (i = 0; i < len; i++)
+ {
+ value += *pBuff++;
+ }
+ value /= len;
+ }
+ else
+ {
+ s32 min, max, temp;
+ min = max = *pBuff; // һֵ
+
+ // ȡֵۼӺͲõСֵ
+ for (i = 0; i < len; i++)
+ {
+ temp = *pBuff++;
+ value += temp; // ϵǰֵ
+ if (min > temp)
+ {
+ min = temp;
+ }
+ if (max < temp)
+ {
+ max = temp;
+ }
+ }
+
+ // ۼӺͼȥСֵ
+ value -= min;
+ value -= max;
+
+ // ʣݵƽֵ
+ value /= (len-2);
+ }
+
+ return value;
+}
+
+#endif
+
+
+//------------------------------------------------------
+
+//------------------------------------------------------
+
diff --git a/NxFuncs/stadc/filter.h b/NxFuncs/stadc/filter.h
new file mode 100644
index 0000000..259cf60
--- /dev/null
+++ b/NxFuncs/stadc/filter.h
@@ -0,0 +1,79 @@
+
+
+#ifndef __FILTER_H__
+#define __FILTER_H__
+
+#include "config.h"
+
+//----------------------------------------------------------
+
+// λֵƽ˲
+int MAFilter(int * pBuff, int len);
+
+//----------------------------------------------------------
+
+// Ȩƽ˲(Ȩֵ)
+int WRAFilter(int * pBuff, int len);
+
+//----------------------------------------------------------
+
+// һͨ˲
+typedef struct
+{
+ float f1value;
+ float lowpassxs;
+}LPF1stData;
+
+#ifdef _IN_FILTER_C
+// οĬֵ
+const LPF1stData defaultLPF1st =
+{
+ -1,
+ 0.5f,
+};
+#else
+extern const LPF1stData defaultLPF1st;
+#endif
+
+int LPF1st(LPF1stData * pLpf1st, int newData);
+
+//----------------------------------------------------------
+// ˲
+typedef struct
+{
+ float f2value;
+ //
+ float b0;
+ float a1;
+ float a2;
+
+ float preout;
+ float lastout;
+}LPF2ndData;
+
+#ifdef _IN_FILTER_C
+// οĬֵ
+// ֹƵ(Ƶf0):30Hz Ƶfs:500Hz
+const LPF2ndData defaultLPF2nd =
+{
+ -1,
+ 0.1883633f,
+ 1.023694f,
+ 0.2120577f,
+ 0,
+ 0,
+};
+#else
+extern const LPF2ndData defaultLPF2nd;
+#endif
+
+int LPF2nd(LPF2ndData * pLpf2nd, int newData);
+
+//----------------------------------------------------------
+
+
+
+
+
+#endif
+
diff --git a/NxFuncs/stdebug/stdebug.c b/NxFuncs/stdebug/stdebug.c
new file mode 100644
index 0000000..3a8be45
--- /dev/null
+++ b/NxFuncs/stdebug/stdebug.c
@@ -0,0 +1,84 @@
+
+
+#include "stdebug.h"
+#include "shell.h"
+#include "inout.h"
+#include "trigger.h"
+#include "delay.h"
+
+//------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+void OutStackInfo(int type, u32 stackaddr)
+{
+ typedef struct
+ {
+ u32 R0;
+ u32 R1;
+ u32 R2;
+ u32 R3;
+ u32 R12;
+ u32 LR;
+ u32 PC;
+ u32 xPSR;
+ } StackData;
+
+#ifndef SetLedOn
+#define SetLedOn()
+#endif
+
+#ifndef SetLedOff
+#define SetLedOff()
+#endif
+
+#if (1)
+ StackData * pStack = (StackData *)(stackaddr); // ̣߳ʹ MSPջ
+
+ SetConsoleOutType(0); // Ƕ
+
+ while (1)
+ {
+ printf("\r\n-----------------------------------------\r\n");
+ if (type == 0)
+ {
+ printf("In HardFault_Handler\r\n");
+ }
+ else if (type == 1)
+ {
+ printf("In MemManage_Handler\r\n");
+ }
+ else if (type == 2)
+ {
+ printf("In BusFault_Handler\r\n");
+ }
+ else if (type == 3)
+ {
+ printf("In UsageFault_Handler\r\n");
+ }
+ else if (type == 4)
+ {
+ printf("In NMI_Handler\r\n");
+ }
+
+ printf("Regs In stack\r\n");
+
+ printf ("R0 = 0x%lx\r\n", pStack->R0);
+ printf ("R1 = 0x%lx\r\n", pStack->R1);
+ printf ("R2 = 0x%lx\r\n", pStack->R2);
+ printf ("R3 = 0x%lx\r\n", pStack->R3);
+ printf ("R12 = 0x%lx\r\n",pStack->R12);
+ printf ("R14[LR] = 0x%lx\r\n", pStack->LR);
+ printf ("R15[PC] = 0x%lx\r\n", pStack->PC);
+ printf ("xPSR = 0x%lx\r\n", pStack->xPSR);
+
+ for (int i = 0; i < 10; i++)
+ {
+ SetLedOn();
+ DelayMs(50);
+ SetLedOff();
+ DelayMs(100);
+ }
+ }
+#endif
+}
+
+//------------------------------------------------------------------------------------------------------------------------------------------------------------
diff --git a/NxFuncs/stdebug/stdebug.h b/NxFuncs/stdebug/stdebug.h
new file mode 100644
index 0000000..ee3d035
--- /dev/null
+++ b/NxFuncs/stdebug/stdebug.h
@@ -0,0 +1,16 @@
+
+
+#ifndef __STDEBUG_H__
+#define __STDEBUG_H__
+
+#include "config.h"
+
+//-------------------------------------------------------------------------------
+
+void OutStackInfo(int type, u32 stackaddr);
+
+//-------------------------------------------------------------------------------
+
+#endif
+
+
diff --git a/NxFuncs/stepdriver/tmc260.c b/NxFuncs/stepdriver/tmc260.c
new file mode 100644
index 0000000..4d15006
--- /dev/null
+++ b/NxFuncs/stepdriver/tmc260.c
@@ -0,0 +1,1321 @@
+
+
+#define _IN_TMC260_C
+#include "tmc260.h"
+
+//-------------------------------------------------------------------------
+
+#if (TMC260_DRV_NUM != 0)
+
+//-------------------------------------------------------------------------
+
+#include "trigger.h"
+#include "shell.h"
+#include "inout.h"
+
+//-------------------------------------------------------------------------
+
+
+//------------------------------------------------------------------------
+
+typedef struct
+{
+ TSpiCtrlConfig spiCtrlConfig;
+ TStepDirConfig stepDirConfig;
+ TChopperConfig chopperConfig;
+ TSmartEnergyControl smartEnergyControl;
+ TStallGuardConfig stallGuardConfig;
+ TDriverConfig driverConfig;
+
+ TReadStatus readStatus;
+ u32 readData;
+}TCConfig;
+
+//------------------------------------------------------------------------
+
+TCConfig g_tcConfig[TMC260_DRV_NUM];
+
+//------------------------------------------------------------------------
+
+#define SReadWrite(cs, dat) SpiReadWrite(cs, dat, 20) // д20λ
+
+void SpiCsOff(SpiCs cs)
+{
+#if (TMC260_DRV_NUM >= 1)
+ SetDriver1CsOff();
+#endif
+#if (TMC260_DRV_NUM >= 2)
+ SetDriver2CsOff();
+#endif
+#if (TMC260_DRV_NUM >= 3)
+ SetDriver3CsOff();
+#endif
+#if (TMC260_DRV_NUM >= 4)
+ SetDriver4CsOff();
+#endif
+#if (TMC260_DRV_NUM >= 5)
+ SetDriver5CsOff();
+#endif
+#if (TMC260_DRV_NUM >= 6)
+ SetDriver6CsOff();
+#endif
+}
+
+void SpiCsOn(SpiCs cs)
+{
+ SpiCsOff(cs);
+
+ switch(cs)
+ {
+ case SC_MOTO1:
+#if (TMC260_DRV_NUM >= 1)
+ SetDriver1CsOn();
+#endif
+ break;
+ case SC_MOTO2:
+#if (TMC260_DRV_NUM >= 2)
+ SetDriver2CsOn();
+#endif
+ break;
+ case SC_MOTO3:
+#if (TMC260_DRV_NUM >= 3)
+ SetDriver3CsOn();
+#endif
+ break;
+ case SC_MOTO4:
+#if (TMC260_DRV_NUM >= 4)
+ SetDriver4CsOn();
+#endif
+ break;
+ case SC_MOTO5:
+#if (TMC260_DRV_NUM >= 5)
+ SetDriver5CsOn();
+#endif
+ break;
+ case SC_MOTO6:
+#if (TMC260_DRV_NUM >= 6)
+ SetDriver6CsOn();
+#endif
+ break;
+ default:
+ break;
+ }
+}
+
+// ģ SPI ӳ֧64λ
+uint64_t SpiReadWrite(SpiCs cs, uint64_t dat, u8 bitlen)
+{
+ int i;
+ uint64_t rslt;
+ uint64_t mod;
+
+ SClockHigh();
+ SpiCsOn(cs); // ƬѡЧʼִжд
+
+ rslt = 0;
+ mod = 0x01;
+ mod <<= (bitlen-1);
+
+ for(i = 0; i < bitlen; i++)
+ {
+ // ú
+ if ((dat&mod) != 0)
+ {
+ SMdoDataOne();
+ }
+ else
+ {
+ SMdoDataZero();
+ }
+
+ SClockLow(); // Ϊ͵ƽ½оƬ
+ SClockHigh(); // ΪߵƽоƬȡúõ
+
+ if (SMdiRead() != 0) // ȡ
+ {
+ rslt |= mod;
+ }
+ mod >>= 1;
+ }
+
+ SpiCsOff(cs);
+ //printf("SPI cs =0x%x, data =0x%x, rslt = 0x%x \r\n",cs,dat,rslt);
+
+ return(rslt);
+}
+
+//------------------------------------------------------------------------
+
+int GetIdxFormCs(SpiCs moto)
+{
+ int idx = moto - 1;
+ if (idx < 0 || idx >= TMC260_DRV_NUM)
+ {
+ printf("not support moto idx\r\n");
+ return -1;
+ }
+ return idx;
+}
+
+//------------------------------------------------------------------------
+// ϸóʼӳ
+void WriteStepDirConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = DRVCTRL0;
+
+ if (g_tcConfig[idx].stepDirConfig.intpol != 0)
+ {
+ temp |= INTPOL; // ʹ16Ƶ
+ }
+
+ if (g_tcConfig[idx].stepDirConfig.dEdge != 0)
+ {
+ temp |= DEDGE; // ʹ˫
+ }
+
+ if (g_tcConfig[idx].stepDirConfig.mRes > MRES1)
+ {
+ g_tcConfig[idx].stepDirConfig.mRes = MRES1;
+ }
+
+ temp |= g_tcConfig[idx].stepDirConfig.mRes;
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+//------------------------------------------------------------------------
+// SPI
+
+void WriteSpiCtrlConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = DRVCTRL1;
+
+ if (g_tcConfig[idx].spiCtrlConfig.polarityA != 0)
+ {
+ temp |= PHA;
+ }
+
+ if (g_tcConfig[idx].spiCtrlConfig.currentA > 255)
+ {
+ g_tcConfig[idx].spiCtrlConfig.currentA = 255;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].spiCtrlConfig.currentA) << 9;
+
+ if (g_tcConfig[idx].spiCtrlConfig.polarityB != 0)
+ {
+ temp |= PHB;
+ }
+
+ if (g_tcConfig[idx].spiCtrlConfig.currentB > 255)
+ {
+ g_tcConfig[idx].spiCtrlConfig.currentB = 255;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].spiCtrlConfig.currentB);
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+
+//------------------------------------------------------------------------
+// նĴʼ
+
+void WriteChopperConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = CHOPCONF;
+
+ if (g_tcConfig[idx].chopperConfig.blankTime > 3)
+ {
+ g_tcConfig[idx].chopperConfig.blankTime = 3;
+ }
+
+ if (g_tcConfig[idx].chopperConfig.hysteresisDecay > 3)
+ {
+ g_tcConfig[idx].chopperConfig.hysteresisDecay = 3;
+ }
+
+ if (g_tcConfig[idx].chopperConfig.hysteresisEnd > 15)
+ {
+ g_tcConfig[idx].chopperConfig.hysteresisEnd = 15;
+ }
+
+ if (g_tcConfig[idx].chopperConfig.hysteresisStart > 7)
+ {
+ g_tcConfig[idx].chopperConfig.hysteresisStart = 7;
+ }
+
+ if (g_tcConfig[idx].chopperConfig.tOff > 15)
+ {
+ g_tcConfig[idx].chopperConfig.tOff = 15;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].chopperConfig.blankTime) << 15;
+
+ if (g_tcConfig[idx].chopperConfig.chopperMode != 0)
+ {
+ temp |= CHM;
+ }
+
+ if (g_tcConfig[idx].chopperConfig.randomTOff != 0)
+ {
+ temp |= RNDTF;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].chopperConfig.hysteresisDecay) << 11;
+ temp |= ((u32)g_tcConfig[idx].chopperConfig.hysteresisEnd) << 7;
+ temp |= ((u32)g_tcConfig[idx].chopperConfig.hysteresisStart) << 4;
+ if (g_tcConfig[idx].chopperConfig.enable != 0)
+ {
+ temp |= ((u32)g_tcConfig[idx].chopperConfig.tOff);
+ }
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+//------------------------------------------------------------------------
+// ӦƳʼӳ
+void WriteStallGuardConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = SGCSCONF;
+
+ // 8 λзתΪ7λз, 7λз7λͷλ(-64--63֮ͬ
+ if (g_tcConfig[idx].stallGuardConfig.stallGuardThreshold > 63)
+ {
+ g_tcConfig[idx].stallGuardConfig.stallGuardThreshold = 63;
+ }
+ else if (g_tcConfig[idx].stallGuardConfig.stallGuardThreshold < -64)
+ {
+ g_tcConfig[idx].stallGuardConfig.stallGuardThreshold = -64;
+ }
+
+ if(g_tcConfig[idx].stallGuardConfig.filterEnable != 0)
+ {
+ temp |= SFILT;
+ }
+
+ temp |= (((u32) g_tcConfig[idx].stallGuardConfig.stallGuardThreshold & 0x7f) << 8);
+ temp |= (g_tcConfig[idx].stallGuardConfig.currentScale & 0x1F);
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+//------------------------------------------------------------------------
+// ӦƳʼ
+void WriteSmartEnergyConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = SMARTEN;
+
+ if (g_tcConfig[idx].smartEnergyControl.smartIMin != 0)
+ {
+ temp |= SEIMIN;
+ }
+
+ if (g_tcConfig[idx].smartEnergyControl.smartDownStep > 3)
+ {
+ g_tcConfig[idx].smartEnergyControl.smartDownStep = 3;
+ }
+
+ if (g_tcConfig[idx].smartEnergyControl.smartStallLevelMax > 15)
+ {
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMax = 15;
+ }
+
+ if (g_tcConfig[idx].smartEnergyControl.smartUpStep > 3)
+ {
+ g_tcConfig[idx].smartEnergyControl.smartUpStep = 3;
+ }
+
+ if (g_tcConfig[idx].smartEnergyControl.smartStallLevelMin > 15)
+ {
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMin = 15;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].smartEnergyControl.smartDownStep) << 13;
+ temp |= ((u32)g_tcConfig[idx].smartEnergyControl.smartStallLevelMax) << 8;
+ temp |= ((u32)g_tcConfig[idx].smartEnergyControl.smartUpStep) << 5;
+ temp |= ((u32)g_tcConfig[idx].smartEnergyControl.smartStallLevelMin);
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+
+
+//------------------------------------------------------------------------
+// ƼĴʼ
+
+void WriteDriverConfig(SpiCs moto)
+{
+ u32 temp;
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ temp = DRVCONF;
+
+ if (g_tcConfig[idx].driverConfig.testMode != 0)
+ {
+ temp |= TST;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].driverConfig.slopeHighSide & 0x03) << 14;
+ temp |= ((u32)g_tcConfig[idx].driverConfig.slopeLowSide & 0x03) << 12;
+
+ if (g_tcConfig[idx].driverConfig.protectionDisable != 0)
+ {
+ temp |= DISS2G;
+ }
+
+ temp |= ((u32)g_tcConfig[idx].driverConfig.protectionTimer & 0x03) << 8;
+
+ if (g_tcConfig[idx].driverConfig.stepDirDisable != 0)
+ {
+ temp |= SDOFF;
+ }
+
+ if (g_tcConfig[idx].driverConfig.vSenseScale != 0)
+ {
+ temp |= VSENSE;
+ }
+
+ temp |= ((u32) g_tcConfig[idx].driverConfig.readBackSelect & 0x03) << 4;
+
+ g_tcConfig[idx].readData = SReadWrite(moto, temp);
+}
+
+//------------------------------------------------------------------------
+// ȡ״ֵ̬
+
+void ReadDriverState(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ WriteDriverConfig(moto);
+
+ switch(g_tcConfig[idx].driverConfig.readBackSelect) // ȡ,0:λ,1:ֵ0--9λ, 2:ֵ5λ(5--9λ)õֵС
+ {
+ case 0: // 0 Aλ
+ {
+ g_tcConfig[idx].readStatus.phases = (g_tcConfig[idx].readData >> 18) & 0x01; // STEP/DIRģʽµļλ; 0OA1OA2š 1OA2OA1š
+ g_tcConfig[idx].readStatus.mSteps = (g_tcConfig[idx].readData >> 10) & 0x1FF; // ȦAұеλ
+ break;
+ }
+ case 1: // 1 ֵ
+ {
+ g_tcConfig[idx].readStatus.stallGuard = (g_tcConfig[idx].readData >> 10) & 0x3FF;
+ break;
+ }
+ case 2: // 2ظ5λǰֵС
+ {
+ g_tcConfig[idx].readStatus.stallGuard &= 0x1f;
+ g_tcConfig[idx].readStatus.stallGuard |= (g_tcConfig[idx].readData >> 10) & 0x3E0;
+ g_tcConfig[idx].readStatus.smartEnergy = (g_tcConfig[idx].readData >> 10) & 0x1f;
+ break;
+ }
+ }
+
+ g_tcConfig[idx].readStatus.flags = g_tcConfig[idx].readData & 0xff; // ͣٱ־λ, STEP
+}
+
+//------------------------------------------------------------------------
+// ʼ
+
+void InitMotorDrivers(SpiCs moto)
+{
+ int idx;
+
+ idx = moto-1;
+ if (idx < 0 || idx >= TMC260_DRV_NUM)
+ {
+ return;
+ }
+
+ memset(&(g_tcConfig[idx]), 0, sizeof(TCConfig));
+
+ g_tcConfig[idx].stallGuardConfig.filterEnable = 1; // ʧ˲ 0:ģʽ1: 4fullstep˲
+ g_tcConfig[idx].stallGuardConfig.stallGuardThreshold = 2; // ʧ-64~63ֵԽԽͣС-10
+ g_tcConfig[idx].stallGuardConfig.currentScale = 1; // 0~31
+ WriteStallGuardConfig(moto); // 0xd020a
+
+ g_tcConfig[idx].driverConfig.slopeHighSide = 2; // Ϲʹܿб0:С3:
+ g_tcConfig[idx].driverConfig.slopeLowSide = 2; // ¹ʹܿб0:С3:
+ g_tcConfig[idx].driverConfig.protectionDisable = 0; // 0:·ʹ 1:ʹ
+ g_tcConfig[idx].driverConfig.protectionTimer = 0; // ·ʱ0: 3.2uS, 1: 1.6uS, 2: 1.2uS, 3: 0.8uS
+ g_tcConfig[idx].driverConfig.stepDirDisable = 0; // 0: 巽ģʽ1:SPIģʽ
+ g_tcConfig[idx].driverConfig.vSenseScale = 0; // οѹ0: 305mV, 1: 165mV
+ g_tcConfig[idx].driverConfig.readBackSelect = 1; // ȡ,0:λ,1:ֵ0--9λ, 2:ֵ5λ(5--9λ)õֵС
+ WriteDriverConfig(moto); // 0xea010
+
+ g_tcConfig[idx].smartEnergyControl.smartIMin = 1; // ܿС0: 1/2, 1: 1/4
+ g_tcConfig[idx].smartEnergyControl.smartDownStep = 0; // ٶ0: 32, 1: 8, 2: 2, 3: 1
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMax = 0; // λȫ0~15
+ g_tcConfig[idx].smartEnergyControl.smartUpStep = 0; // ٶ0: 1, 1: 2, 2: 4, 3: 8
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMin = 0; // λȫ0~15
+ WriteSmartEnergyConfig(moto); // 0xa8000
+
+ g_tcConfig[idx].stepDirConfig.intpol = 0; // 16Ƶģʽ
+ g_tcConfig[idx].stepDirConfig.dEdge = 0; // ˫ģʽ
+ g_tcConfig[idx].stepDirConfig.mRes = MRES4; // ϸ
+ WriteStepDirConfig(moto); // 0x0
+
+ g_tcConfig[idx].chopperConfig.blankTime = 1; // նհʱ䣬Ҳǹضʱ䣬0: 16, 1: 24, 2: 36, 3: 54
+ g_tcConfig[idx].chopperConfig.chopperMode = 0; // 0: նģʽ, 1: ϵģʽһѡ0
+ g_tcConfig[idx].chopperConfig.hysteresisDecay = 0; // ˥0...3, 0:fast decrement 3:very slow decrement
+ g_tcConfig[idx].chopperConfig.hysteresisEnd = 3; // ˥ֵ 0...15
+ g_tcConfig[idx].chopperConfig.hysteresisStart = 3; // ˥ʼֵ 0...7
+ g_tcConfig[idx].chopperConfig.tOff = 5; // ն˥ʱ䣬Ӱ쿪Ƶ
+ g_tcConfig[idx].chopperConfig.enable = 1; // mosfet
+ WriteChopperConfig(moto); // 0x881b5
+}
+
+//------------------------------------------------------------------------------------------------------------------------------------------------
+
+
+//------------------------------------------------------------------------
+// ϸӳ
+void SetStepDirMStepRes(SpiCs moto, u32 microstepResolution)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stepDirConfig.mRes = microstepResolution;
+ WriteStepDirConfig(moto);
+}
+
+//
+void SetStepDirInterpolation(SpiCs moto, u32 interpolation)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stepDirConfig.intpol = interpolation;
+ WriteStepDirConfig(moto);
+}
+
+//
+void SetStepDirDoubleEdge(SpiCs moto, u32 doubleEdge)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stepDirConfig.dEdge = doubleEdge;
+ WriteStepDirConfig(moto);
+}
+
+//
+u32 GetStepDirMStepRes(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stepDirConfig.mRes;
+}
+
+//
+u32 GetStepDirInterpolation(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stepDirConfig.intpol;
+}
+
+//
+u32 GetStepDirDoubleEdge(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stepDirConfig.dEdge;
+}
+
+//------------------------------------------------------------------------
+//
+void SetChopperBlankTime(SpiCs moto, u32 blankTime)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.blankTime = blankTime;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperMode(SpiCs moto, u32 mode)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.chopperMode = mode;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperRandomTOff(SpiCs moto, u32 randomTOff)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.randomTOff = randomTOff;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperHysteresisDecay(SpiCs moto, u32 hysteresisDecay)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.hysteresisDecay = hysteresisDecay;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperHysteresisEnd(SpiCs moto, u32 hysteresisEnd)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.hysteresisEnd = hysteresisEnd;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperHysteresisStart(SpiCs moto, u32 hysteresisStart)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.hysteresisStart = hysteresisStart;
+ WriteChopperConfig(moto);
+}
+
+//
+void SetChopperTOff(SpiCs moto, u32 tOff)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.tOff = tOff;
+ WriteChopperConfig(moto);
+}
+
+void SetChopperEnable(SpiCs moto, u32 enable)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].chopperConfig.enable = enable;
+ WriteChopperConfig(moto);
+}
+
+//
+u32 GetChopperBlankTime(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.blankTime;
+}
+
+//
+u32 GetChopperMode(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.chopperMode;
+}
+
+//
+u32 GetChopperRandomTOff(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.randomTOff;
+}
+
+//
+u32 GetChopperHysteresisDecay(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.hysteresisDecay;
+}
+
+//
+u32 GetChopperHysteresisEnd(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.hysteresisEnd;
+}
+
+//
+u32 GetChopperHysteresisStart(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.hysteresisStart;
+}
+
+//
+u32 GetChopperTOff(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.tOff;
+}
+
+u32 GetChopperEnable(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].chopperConfig.enable;
+}
+
+//------------------------------------------------------------------------
+//
+void SetSmartEnergyIMin(SpiCs moto, u32 smartIMin)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].smartEnergyControl.smartIMin = smartIMin;
+ WriteSmartEnergyConfig(moto);
+}
+
+//
+void SetSmartEnergyDownStep(SpiCs moto, u32 smartDownStep)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].smartEnergyControl.smartDownStep = smartDownStep;
+ WriteSmartEnergyConfig(moto);
+}
+
+//
+void SetSmartEnergyStallLevelMax(SpiCs moto, u32 stallLevelMax)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMax = stallLevelMax;
+ WriteSmartEnergyConfig(moto);
+}
+
+//
+void SetSmartEnergyUpStep(SpiCs moto, u32 smartUpStep)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].smartEnergyControl.smartUpStep = smartUpStep;
+ WriteSmartEnergyConfig(moto);
+}
+
+//
+void SetSmartEnergyStallLevelMin(SpiCs moto, u32 stallLevelMin)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].smartEnergyControl.smartStallLevelMin = stallLevelMin;
+ WriteSmartEnergyConfig(moto);
+}
+
+//
+u32 GetSmartEnergyIMin(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].smartEnergyControl.smartIMin;
+}
+
+//
+u32 GetSmartEnergyDownStep(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].smartEnergyControl.smartDownStep;
+}
+
+//
+u32 GetSmartEnergyStallLevelMax(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].smartEnergyControl.smartStallLevelMax;
+}
+
+//
+u32 GetSmartEnergyUpStep(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].smartEnergyControl.smartUpStep;
+}
+
+//
+u32 GetSmartEnergyStallLevelMin(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].smartEnergyControl.smartStallLevelMin;
+}
+
+//------------------------------------------------------------------------
+//
+void SetStallGuardFilter(SpiCs moto, u32 enable)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stallGuardConfig.filterEnable = enable;
+ WriteStallGuardConfig(moto);
+}
+
+//
+void SetStallGuardThreshold(SpiCs moto, s32 threshold)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stallGuardConfig.stallGuardThreshold = threshold;
+ WriteStallGuardConfig(moto);
+}
+
+//
+void SetStallGuardCurrentScale(SpiCs moto, u32 currentScale)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].stallGuardConfig.currentScale = currentScale;
+ WriteStallGuardConfig(moto);
+}
+
+//
+u32 GetStallGuardFilter(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stallGuardConfig.filterEnable;
+}
+
+//
+s32 GetStallGuardThreshold(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stallGuardConfig.stallGuardThreshold;
+}
+
+//
+u32 GetStallGuardCurrentScale(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].stallGuardConfig.currentScale;
+}
+
+//------------------------------------------------------------------------
+//
+void SetDriverSlopeHighSide(SpiCs moto, u32 slopeHighSide)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.slopeHighSide = slopeHighSide;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverSlopeLowSide(SpiCs moto, u32 slopeLowSide)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.slopeHighSide = slopeLowSide;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverDisableProtection(SpiCs moto, u32 disableProtection)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.protectionDisable = disableProtection;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverProtectionTimer(SpiCs moto, u32 protectionTimer)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.protectionTimer = protectionTimer;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverStepDirectionOff(SpiCs moto, u32 sDOff)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.stepDirDisable = sDOff;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverVSenseScale(SpiCs moto, u32 scale)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.vSenseScale = scale;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverReadSelect(SpiCs moto, u32 readSelect)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.readBackSelect = readSelect;
+ WriteDriverConfig(moto);
+}
+
+//
+void SetDriverTestMode(SpiCs moto, u32 testMode)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return;
+ }
+ g_tcConfig[idx].driverConfig.testMode = testMode;
+ WriteDriverConfig(moto);
+}
+
+//
+u32 GetDriverSlopeHighSide(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.slopeHighSide;
+}
+
+//
+u32 GetDriverSlopeLowSide(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.slopeLowSide;
+}
+
+//
+u32 GetDriverDisableProtection(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.protectionDisable;
+}
+
+//
+u32 GetDriverProtectionTimer(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.protectionTimer;
+}
+
+//
+u32 GetDriverStepDirectionOff(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.stepDirDisable;
+}
+
+//
+u32 GetDriverVSenseScale(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.vSenseScale;
+}
+
+//
+u32 GetDriverReadSelect(SpiCs moto)
+{
+ int idx;
+ idx = moto-1;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.readBackSelect;
+}
+
+//
+u32 GetDriverTestMode(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].driverConfig.testMode;
+}
+
+//------------------------------------------------------------------------
+
+u32 GetPhases(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+
+ return g_tcConfig[idx].readStatus.phases;
+}
+
+//------------------------------------------------------------------------
+u32 GetMStepPos(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+
+ return g_tcConfig[idx].readStatus.mSteps;
+}
+
+//------------------------------------------------------------------------
+u32 GetStallGuard(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+
+ return g_tcConfig[idx].readStatus.stallGuard;
+}
+
+//------------------------------------------------------------------------
+u32 GetSmartEnergy(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+
+ return g_tcConfig[idx].readStatus.smartEnergy;
+}
+
+//------------------------------------------------------------------------
+//
+u32 GetDriverFlag(SpiCs moto)
+{
+ int idx;
+ idx = GetIdxFormCs(moto);
+ if (idx < 0)
+ {
+ return 0;
+ }
+ return g_tcConfig[idx].readStatus.flags;
+}
+
+//
+void DriveDisable(SpiCs moto)
+{
+ SetChopperEnable(moto, 0);
+}
+
+//
+void DriveEnable(SpiCs moto)
+{
+ SetChopperEnable(moto, 1);
+}
+
+//----------------------------------------------------------------------------------------------------------------------------------------------
+
+
+//------------------------------------------------------------------------
+
+//------------------------------------------------------------------------
+
+
+void InitTmc260(void)
+{
+ InitMotorDrivers(SC_MOTO1);
+ InitMotorDrivers(SC_MOTO2);
+ InitMotorDrivers(SC_MOTO3);
+ InitMotorDrivers(SC_MOTO4);
+ InitMotorDrivers(SC_MOTO5);
+ InitMotorDrivers(SC_MOTO6);
+}
+
+//------------------------------------------------------------------------
+
+int GetResConfigFromLvnum(int subd)
+{
+ switch(subd)
+ {
+ case 1: // 1ϸ
+ return MRES1;
+ case 2: // 2ϸ
+ return MRES2;
+ case 4: // 4ϸ
+ return MRES4;
+ case 8: // 8ϸ
+ return MRES8;
+ case 16: // 16ϸ
+ return MRES16;
+ case 32: // 32ϸ
+ return MRES32;
+ case 64: // 64ϸ
+ return MRES64;
+ case 128: // 128ϸ
+ return MRES128;
+ case 256: // 256ϸ
+ return MRES256;
+ default:
+ return MRES256;
+ };
+}
+
+#endif
+
+
diff --git a/NxFuncs/stepdriver/tmc260.h b/NxFuncs/stepdriver/tmc260.h
new file mode 100644
index 0000000..5b8fd58
--- /dev/null
+++ b/NxFuncs/stepdriver/tmc260.h
@@ -0,0 +1,355 @@
+
+
+#ifndef __TMC260_H__
+#define __TMC260_H__
+
+
+#include "config.h"
+#include "inout.h"
+
+//------------------------------------------------------------
+
+// Ĵλ
+
+// Ĵ5, ÿ20λ
+
+// ַ
+#define CFR 0x80000
+#define CFRSEL1 0x40000
+#define CFRSEL0 0x20000
+
+#define DRVCTRL0 0 // SDOFF == 0 ʱ
+#define DRVCTRL1 0 // SDOFF == 1 ʱ
+#define CHOPCONF (CFR)
+#define SMARTEN (CFR|CFRSEL0)
+#define SGCSCONF (CFR|CFRSEL1)
+#define DRVCONF (CFR|CFRSEL1|CFRSEL0)
+
+//------------------------------------------------------------
+
+// SPIʽƼĴ
+// sdoff == 1 DRVCTRL spiʽ
+
+#ifdef DRVCTRL1
+
+// SPI
+typedef struct
+{
+ u32 polarityA; // A; 0, OA1ܽŵOA2ܽ; 1, OA2ܽŵOA1ܽ
+ u32 currentA; // ȦAĴСΧΪ0248ͺƫȫʹá ʩͺƫƺĽֵܳ255
+
+ u32 polarityB; // B; 0, OB1ܽŵOB2ܽ; 1, OB2ܽŵOB1ܽ
+ u32 currentB; // ȦBĴСΧΪ0248ͺƫȫʹá ʩͺƫƺĽֵܳ255
+
+}TSpiCtrlConfig;
+
+#define PHA 0x20000
+#define CA 0x1FE00
+#define PHB 0x00100
+#define CB 0x000FF
+
+#endif
+
+
+
+
+
+
+#endif
+
+
+
+
+//------------------------------------------------------------
+
+// +Ʒʽ ƼĴ
+
+// sdoff == 0 DRVCTRL Ϊ step dir ʽ
+
+#ifdef DRVCTRL0
+
+typedef struct
+{
+ u32 intpol; // Ƶ
+ u32 dEdge; // ˫
+ u32 mRes; //
+}TStepDirConfig;
+
+#define INTPOL 0x00200 // ʹ16Ƶ
+
+#define DEDGE 0x00100 // ʹ˫壬ԼٶԲƵʵҪ
+
+#define MRES1 0x00008 // 1ϸ
+#define MRES2 0x00007 // 2ϸ
+#define MRES4 0x00006 // 4ϸ
+#define MRES8 0x00005 // 8ϸ
+#define MRES16 0x00004 // 16ϸ
+#define MRES32 0x00003 // 32ϸ
+#define MRES64 0x00002 // 64ϸ
+#define MRES128 0x00001 // 128ϸ
+#define MRES256 0x00000 // 256ϸ
+
+#define MRES 0x0000F // ֻ4λЧ
+
+//------------------------------------------------------------
+
+// նĴ
+#ifdef CHOPCONF
+
+typedef struct
+{
+ u32 blankTime; // Ƚհʱѡ; 00հʱΪ 16 ʱ; 01հʱΪ 24 ʱ; 10հʱΪ 36 ʱ; 11հʱΪ 54 ʱ;
+ u32 chopperMode; // նģʽ; 0ģʽ 1Toff ΪĿ˥ģʽ
+ u32 randomTOff; // TOFF ʱ: 0նʱ̶ 1նʱɵ
+ u32 hysteresisDecay; // chopperMode==0ʱ, ˥; 0016 ʱ; 0132 ʱ; 1048 ʱ; 1164 ʱ;
+ // chopperMode==1ʱ, FDMODE ; bit0==1: ֹȽΪ˥ֹ; bit1:˥ʱλ
+ u32 hysteresisEnd; // chopperMode==0ʱ, ˥λֵ; 0--15 Ӧ˥ֵΪ -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 9, 10, 11, 12
+ // chopperMode==1ʱ, Ҳƫ
+ u32 hysteresisStart; // chopperMode==0ʱ, ˥ʼֵ, ˥ 0--7hysteresisEnd 1 -- 8
+ // chopperMode==1ʱ, ˥ʱ, ʱ = (((hysteresisDecay&0x02) << 2) | (hysteresisStart&0x07)) * 32 ʱ
+ u32 tOff; // ˥εijʱ; 1, TBL(blankTime) С 24 ʱ; 2--15, ʹùʽ 12 + (32 x tOffAndDisable) С 64 ʱڡ
+ u32 enable; // mosfet == 0, ֹ; = 1,
+
+}TChopperConfig;
+
+
+#define TBL 0x18000 // 2λ
+
+#define CHM 0x04000
+#define RNDTF 0x02000
+#define HDEC 0x01800 // 2λ
+#define HEND 0x00780 // 4λ
+#define HSTRT 0x00070 // 3λ
+#define TOFF 0x0000F // 4λ
+
+#define DRIVE_OFF 0
+#define DRIVE_ON 1
+
+
+#endif
+
+
+//------------------------------------------------------------
+
+// Ĵ (coolStep )
+
+#ifdef SMARTEN
+
+typedef struct
+{
+ u32 smartIMin; // ܿС; = 01/2趨; = 1, 1/4趨
+ u32 smartDownStep; // Сٶ; 00ÿ 32 ˥ֵСһλ; 01ÿ 8 ˥ֵСһλ; 10ÿ 2 ˥ֵСһλ; 11ÿ1˥ֵСһλ
+ u32 smartStallLevelMax; // Сʱص˥ֵ; ؼֵ>=(SEMIN+SEMAX+1)*32 صȫֵ 趨Χ 0--15
+ u32 smartUpStep; // ; 00: ÿ 1 زֵһλ; 01: ÿ 2 زֵһλ; 00: ÿ 4 زֵһλ; 00: ÿ 8 زֵһλ;
+ u32 smartStallLevelMin; // ܵƵСؼֵ͵ʹ; ؼֵ < SEMIN*32СתǶȽ; 0ֹ; 1--15 ؼֵ
+}TSmartEnergyControl;
+
+#define SEIMIN 0x08000
+
+#define SEND 0x06000 // 2λ
+#define SEMAX 0x00F00 // 4λ
+#define SEUP 0x00060 // 2λ
+#define SEMIN 0x0000F // 4λ
+
+#endif
+
+
+//------------------------------------------------------------
+// ʧٱ͵趨Ĵ
+
+#ifdef SGCSCONF
+
+typedef struct
+{
+ u32 filterEnable; // ʹʧټ˲; 0, ģʽ, 췴Ӧʱ; 1, ģʽÿIJһθ£Բṹı仯߾;
+ s32 stallGuardThreshold; // ʧټֵⷧ趨ֵԽ, Խ, ʧʱתԽ; з, ÷ΧΪ-64 -- +63 һΪ0õ-10
+ u32 currentScale; // ű趨ֵ 0--31 Ӧ 1/32 -- 32/32. CS = 0, 1/32
+
+}TStallGuardConfig;
+
+
+#define SFILT 0x10000
+#define SGT 0x07F00 // 7λ
+#define CS 0x0001F // 5λ
+
+
+
+#endif
+
+
+
+//------------------------------------------------------------
+// оƬüĴ
+
+#ifdef DRVCONF
+
+typedef struct
+{
+ u32 testMode; // Ϊģʽ; һΪ 0λ 1 ʱSG_TST ֲֵ, TEST_ANA ģֵͨ SGT1 SGT0
+ u32 slopeHighSide; // ߶ؿ; 00Сֵ; 01Сֵ+tc; 10мֵ+tc 11ֵ; ¶Ȳģʽ£趨ֵΪǿȵһ
+ u32 slopeLowSide; // Ͷؿ; 0001Сֵ; 10мֵ; 11ֵ
+ u32 protectionDisable; // ·ر; 0, ʹ; 1, ر
+ u32 protectionTimer; // ·ⶨʱ; 003.2us011.6us101.2us0.8us
+ u32 stepDirDisable; // ͷģʽر; 0ʹͷģʽ1ʹ SPI ģʽرͷģʽ
+ u32 vSenseScale; // 趨IJֵ߽; 0ѹֵ 305mV; 1:ѹֵ 165mV. (ָǰΪ31DACֵΪ255)
+ u32 readBackSelect; // λѡ, 00λã01ظֵ10ظֵܵ11δʹ
+}TDriverConfig;
+
+#define TST 0x10000
+#define SLPH 0x0C000
+#define SLPL 0x03000
+
+#define DISS2G 0x00400
+#define TS2G 0x00300
+#define SDOFF 0x00080
+#define VSENSE 0x00040
+#define RDSEL 0x00030
+
+#endif
+
+//------------------------------------------------------------
+
+// ȡϢĴ
+typedef struct
+{
+ u32 phases; // : 0OA1OA2š1OA2OA1š
+ u32 mSteps; // STEP/DIRģʽȦAұеλá
+ u32 stallGuard; // ʧټֵ
+ u32 smartEnergy; // ֵ
+ u32 flags; // ־
+
+}TReadStatus;
+
+
+#define MSTEP 0xFFC00
+#define SG 0xFFC00
+#define SE 0x03C00
+
+
+// flags
+#define ST_STST 0x0080 // ָʾ 1ָʾ 2^20 ηʱûв
+#define ST_OLB 0x0040 // B ָʾնʱΪ 1 һ1/16 ͨʱ
+#define ST_OLA 0x0020 // A ָʾնʱΪ 1 һ1/16 ͨʱ
+#define ST_S2GB 0x0010 // B ·ָʾ, ·նֹ·һ 3 ʱҪλ
+#define ST_S2GA 0x0008 // A ·ָʾ, ·նֹ·һ 3 ʱҪλ
+#define ST_OTPW 0x0004 // Ԥ1ִбֵ
+#define ST_OT 0x0002 // ±־, 1¶
+#define ST_SG 0x0001 // ״̬1طֵSG ߵƽ
+
+
+//------------------------------------------------------------
+
+
+#ifndef TMC260_DRV_NUM
+#define TMC260_DRV_NUM 0
+#endif
+
+#if (TMC260_DRV_NUM > 6)
+#unfine TMC260_DRV_NUM
+#define TMC260_DRV_NUM 6
+#endif
+
+#if (TMC260_DRV_NUM < 0)
+#unfine TMC260_DRV_NUM
+#define TMC260_DRV_NUM 0
+#endif
+
+//------------------------------------------------------------
+
+typedef enum
+{
+ SC_MOTO1=1,
+ SC_MOTO2,
+ SC_MOTO3,
+ SC_MOTO4,
+ SC_MOTO5,
+ SC_MOTO6,
+}SpiCs;
+
+//------------------------------------------------------------
+
+void WriteStepDirConfig(SpiCs moto);
+void WriteSpiCtrlConfig(SpiCs moto);
+void WriteChopperConfig(SpiCs moto);
+void WriteStallGuardConfig(SpiCs moto);
+void WriteSmartEnergyConfig(SpiCs moto);
+void WriteDriverConfig(SpiCs moto);
+void ReadDriverState(SpiCs moto);
+
+void InitMotorDrivers(SpiCs moto);
+
+void SetStepDirMStepRes(SpiCs moto, u32 microstepResolution);
+void SetStepDirInterpolation(SpiCs moto, u32 interpolation);
+void SetStepDirDoubleEdge(SpiCs moto, u32 doubleEdge);
+u32 GetStepDirMStepRes(SpiCs moto);
+u32 GetStepDirInterpolation(SpiCs moto);
+u32 GetStepDirDoubleEdge(SpiCs moto);
+void SetChopperBlankTime(SpiCs moto, u32 blankTime);
+void SetChopperMode(SpiCs moto, u32 mode);
+void SetChopperRandomTOff(SpiCs moto, u32 randomTOff);
+void SetChopperHysteresisDecay(SpiCs moto, u32 hysteresisDecay);
+void SetChopperHysteresisEnd(SpiCs moto, u32 hysteresisEnd);
+void SetChopperHysteresisStart(SpiCs moto, u32 hysteresisStart);
+void SetChopperTOff(SpiCs moto, u32 tOff);
+u32 GetChopperBlankTime(SpiCs moto);
+u32 GetChopperMode(SpiCs moto);
+u32 GetChopperRandomTOff(SpiCs moto);
+u32 GetChopperHysteresisDecay(SpiCs moto);
+u32 GetChopperHysteresisEnd(SpiCs moto);
+u32 GetChopperHysteresisStart(SpiCs moto);
+u32 GetChopperTOff(SpiCs moto);
+void SetSmartEnergyIMin(SpiCs moto, u32 smartIMin);
+void SetSmartEnergyDownStep(SpiCs moto, u32 smartDownStep);
+void SetSmartEnergyStallLevelMax(SpiCs moto, u32 stallLevelMax);
+void SetSmartEnergyUpStep(SpiCs moto, u32 smartUpStep);
+void SetSmartEnergyStallLevelMin(SpiCs moto, u32 stallLevelMin);
+u32 GetSmartEnergyIMin(SpiCs moto);
+u32 GetSmartEnergyDownStep(SpiCs moto);
+u32 GetSmartEnergyStallLevelMax(SpiCs moto);
+u32 GetSmartEnergyUpStep(SpiCs moto);
+u32 GetSmartEnergyStallLevelMin(SpiCs moto);
+void SetStallGuardFilter(SpiCs moto, u32 enable);
+void SetStallGuardThreshold(SpiCs moto, s32 threshold);
+void SetStallGuardCurrentScale(SpiCs moto, u32 currentScale);
+u32 GetStallGuardFilter(SpiCs moto);
+s32 GetStallGuardThreshold(SpiCs moto);
+u32 GetStallGuardCurrentScale(SpiCs moto);
+void SetDriverSlopeHighSide(SpiCs moto, u32 slopeHighSide);
+void SetDriverSlopeLowSide(SpiCs moto, u32 slopeLowSide);
+void SetDriverDisableProtection(SpiCs moto, u32 disableProtection);
+void SetDriverProtectionTimer(SpiCs moto, u32 protectionTimer);
+void SetDriverStepDirectionOff(SpiCs moto, u32 sDOff);
+void SetDriverVSenseScale(SpiCs moto, u32 scale);
+void SetDriverReadSelect(SpiCs moto, u32 readSelect);
+void SetDriverTestMode(SpiCs moto, u32 testMode);
+u32 GetDriverSlopeHighSide(SpiCs moto);
+u32 GetDriverSlopeLowSide(SpiCs moto);
+u32 GetDriverDisableProtection(SpiCs moto);
+u32 GetDriverProtectionTimer(SpiCs moto);
+u32 GetDriverStepDirectionOff(SpiCs moto);
+u32 GetDriverVSenseScale(SpiCs moto);
+u32 GetDriverReadSelect(SpiCs moto);
+u32 GetDriverTestMode(SpiCs moto);
+
+//------------------------------------------------------------
+
+u32 GetPhases(SpiCs moto);
+u32 GetMStepPos(SpiCs moto);
+u32 GetStallGuard(SpiCs moto);
+u32 GetSmartEnergy(SpiCs moto);
+u32 GetDriverFlag(SpiCs moto);
+
+void DriveDisable(SpiCs moto);
+void DriveEnable(SpiCs moto);
+
+//------------------------------------------------------------
+
+void InitTmc260(void);
+
+void SetAsDriver(void);
+
+int GetResConfigFromLvnum(int subd);
+
+#endif
+
+
diff --git a/NxFuncs/stiap/stapp.c b/NxFuncs/stiap/stapp.c
new file mode 100644
index 0000000..7deb652
--- /dev/null
+++ b/NxFuncs/stiap/stapp.c
@@ -0,0 +1,493 @@
+
+#define _IN_STAPP_C
+#include "stapp.h"
+
+#if (APP_SAVE_TO != APP_SAVE_NONE)
+
+#include "crc32.h"
+#include "cpuid.h"
+#include "stiap.h"
+
+#include "stflash.h"
+
+//-------------------------------------------------------------------------------
+
+
+
+
+
+//-------------------------------------------------------------------------------
+
+// ļ
+
+//-------------------------------------------------------------------------------
+
+typedef struct
+{
+ char xorbuf[8];
+ u8 xchgbuf[8];
+ u32 datalen;
+ u32 bincrc;
+ u32 rnpucrc;
+ u32 hddatcrc;
+ u8 rev[1024-8-8-8-8];
+}GNPUHead;
+
+GNPUHead g_gnpuHead =
+{
+#if (CUR_UPFL == GAUF_PMB1) // ͼ
+ {
+ 'G', 'O', 'A', 'P', 'M', 'B', 'O', 'S',
+ },
+ {
+ 4, 6, 7, 2, 3, 5, 8, 1,
+ },
+#elif (CUR_UPFL == GAUF_EMB1) // 廨/
+ {
+ 'G', 'O', 'A', 'E', 'M', 'B', 'O', 'S',
+ },
+ {
+ 1, 3, 5, 2, 4, 8, 6, 7,
+ },
+#elif (CUR_UPFL == GAUF_EHA1) // ƽͷ
+ {
+ 'G', 'O', 'A', 'E', 'H', 'A', 'O', 'S',
+ },
+ {
+ 5, 1, 3, 2, 7, 4, 8, 6,
+ },
+#elif (CUR_UPFL == GAUF_EHB1) // ͷ
+ {
+ 'G', 'O', 'A', 'E', 'H', 'B', 'O', 'S',
+ },
+ {
+ 1, 5, 2, 4, 3, 7, 6, 8,
+ },
+#elif (CUR_UPFL == GAUF_EMCLA1) // ƽ廻ɫ
+ {
+ 'G', 'O', 'A', 'E', 'C', 'L', 'A', '1',
+ },
+ {
+ 6, 1, 7, 4, 2, 5, 3, 8,
+ },
+#elif (CUR_UPFL == GAUF_EXTIO) // չIO忨
+#else
+ {
+ 'R', 'P', 'U', 'P', 'D', 'A', 'T', 'E',
+ },
+ {
+ 1, 2, 3, 4, 5, 6, 7, 8,
+ },
+#endif
+ 0, 0, 0, 0,
+ {
+ 0,
+ },
+};
+
+// RNPU
+int DecodeData(u8 * pBuf, int len)
+{
+ int i, j, k, num1;
+ u8 tpbuf[8], opbuf[8];
+ u8 temp, mod;
+
+ if (pBuf == NULL || len == 0)
+ {
+ return -1;
+ }
+
+ for (i = 0; i < len && ((len - i) >= 8); i += 8)
+ {
+ // ÿ8ֽһݣ8ֽڵݣ
+ memcpy(tpbuf, &(pBuf[i]), 8);
+
+ // ݽ8ֽڵ˳
+ memcpy(opbuf, tpbuf, 8);
+ for (j = 0; j < 8; j++)
+ {
+ tpbuf[g_gnpuHead.xchgbuf[j]-1] = opbuf[j];
+ }
+
+ // λ1ĸ
+ num1 = 0;
+ for (j = 0; j < 8; j++)
+ {
+ mod = 0x01;
+ for (k = 0; k < 8; k++)
+ {
+ if ((tpbuf[j] & mod) != 0)
+ {
+ num1++;
+ }
+ mod *= 2;
+ }
+ }
+
+ // ݸѭλƣżƣ
+ if ((num1 & 0x01) != 0) //
+ {
+ // ѭ
+ for (j = 0; j < num1; j++)
+ {
+ mod = tpbuf[7];
+ for (k = 0; k < 8; k++)
+ {
+ temp = tpbuf[k];
+ tpbuf[k] >>= 1; //
+ if ((mod & 0x01) != 0)
+ {
+ tpbuf[k] |= 0x80;
+ }
+ mod = temp;
+ }
+ }
+ }
+ else // ż
+ {
+ // ѭ
+ for (j = 0; j < num1; j++)
+ {
+ mod = tpbuf[0];
+ for (k = 7; k >= 0; k--)
+ {
+ temp = tpbuf[k];
+ tpbuf[k] <<= 1; //
+ if ((mod & 0x80) != 0)
+ {
+ tpbuf[k] |= 0x01;
+ }
+ mod = temp;
+ }
+ }
+ }
+
+ // ݺͼַ
+ for (j = 0; j < 8; j++)
+ {
+ tpbuf[j] ^= g_gnpuHead.xorbuf[j];
+ }
+
+ // õյĽ
+ memcpy(&(pBuf[i]), tpbuf, 8);
+ }
+
+ return 0;
+}
+
+//-------------------------------------------------------------------------------
+
+typedef struct
+{
+ int enFlag;
+ int saveOffset;
+ int isrnpufile;
+ u32 bincrc;
+ u32 rnpucrc;
+ int rsvCounter;
+
+}SaveAppCtrl;
+
+SaveAppCtrl g_saveAppCtrl;
+
+void InitSaveApp(void)
+{
+ g_gnpuHead.datalen = 0;
+ g_gnpuHead.bincrc = 0;
+ g_gnpuHead.rnpucrc = 0;
+ g_gnpuHead.hddatcrc = 0;
+
+ g_saveAppCtrl.saveOffset = 0;
+ g_saveAppCtrl.isrnpufile = 0;
+
+ g_saveAppCtrl.bincrc = CRC32_INIT;
+ g_saveAppCtrl.rnpucrc = CRC32_INIT;
+ g_saveAppCtrl.rsvCounter = 0;
+
+ IAPCleanUpdateArea(); // NORflashļ
+}
+
+// һݵapp
+int SaveAppData(int idx, u8 * pBuf, int len, u32 ofst)
+{
+ u32 addr, wtlen;
+ int i, thislen;
+ //printf("SaveAppData idx=%d, len=%d, ofst=0x%x\r\n", idx, len, ofst);
+
+ if (idx < 0 ||
+ pBuf == NULL ||
+ (len != SUPPORT_LEN_1 && len != SUPPORT_LEN_2) ||
+ 0 )
+ {
+ printf("SaveAppData para err\r\n");
+ return -1;
+ }
+
+ // ļͷ
+ if (ofst == 0 && idx == 0 && g_saveAppCtrl.saveOffset < sizeof(g_gnpuHead))
+ {
+ if (ofst == 0 && idx == 0)
+ {
+ printf("process file head\r\n");
+
+ if (memcmp(pBuf, g_gnpuHead.xorbuf, 8) == 0 &&
+ memcmp(&(pBuf[8]), g_gnpuHead.xchgbuf, 8) == 0 &&
+ 1 )
+ {
+ u32 hdcrc, hddatsize;
+ g_saveAppCtrl.isrnpufile = 1;
+ // У
+ g_saveAppCtrl.bincrc = CRC32_INIT;
+ g_saveAppCtrl.rnpucrc = CRC32_INIT;
+
+ g_gnpuHead.datalen = *((u32*)&(pBuf[16]));
+ g_gnpuHead.bincrc = *((u32*)&(pBuf[20]));
+ g_gnpuHead.rnpucrc = *((u32*)&(pBuf[24]));
+ g_gnpuHead.hddatcrc = *((u32*)&(pBuf[28]));
+
+ hddatsize = sizeof(g_gnpuHead) - sizeof(g_gnpuHead.rev) - 4;
+ hdcrc = CalcCrc32((u8*)(&g_gnpuHead), hddatsize);
+
+ if (hdcrc == g_gnpuHead.hddatcrc)
+ {
+ g_saveAppCtrl.rsvCounter = g_gnpuHead.datalen;
+ return 0;
+ }
+ else
+ {
+ printf("file head crc error\r\n");
+ return -2;
+ }
+ }
+ else
+ {
+ printf("bin file not support\r\n"); // Ϊbinļȫ
+ return -1;
+ }
+ }
+ else
+ {
+ printf("file not correct\r\n");
+ return 0;
+ }
+ }
+ else
+ {
+ }
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ addr = NOR_APP_ADDR;
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ addr = EXRAM_APP_ADDR;
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ addr = APP_ADDR_BEG;
+#else
+ addr = 0;
+#endif
+
+ addr += ofst;
+ addr += ((idx-1)*len); // дַʹidx*len; ڶ,ߴݰʱַƫ
+ wtlen = len;
+
+ g_saveAppCtrl.saveOffset += len;
+
+ if (g_saveAppCtrl.isrnpufile != 0)
+ {
+ if (g_saveAppCtrl.rsvCounter > len)
+ {
+ thislen = len;
+ g_saveAppCtrl.rsvCounter -= len;
+ }
+ else
+ {
+ thislen = g_saveAppCtrl.rsvCounter;
+ g_saveAppCtrl.rsvCounter = 0;
+ }
+ for (i = 0; i < thislen; i++)
+ {
+ g_saveAppCtrl.rnpucrc = AddCrc32(g_saveAppCtrl.rnpucrc, pBuf[i]);
+ }
+
+ DecodeData(pBuf, thislen); //
+
+ for (i = 0; i < thislen; i++)
+ {
+ g_saveAppCtrl.bincrc = AddCrc32(g_saveAppCtrl.bincrc, pBuf[i]);
+ }
+
+ for (i = thislen; i < len; i++)
+ {
+ pBuf[i] = 0xff;
+ }
+ }
+ else
+ {
+ thislen = len;
+ }
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ printf("save to norflash, addr=0x%lx, wtlen=%d\r\n", addr, wtlen);
+ DatFlashWrData(addr, pBuf, wtlen);
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ printf("save to exram, addr=0x%lx, wtlen=%d\r\n", addr, wtlen);
+ memcpy((void*)addr, (void*)pBuf, wtlen);
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ printf("save to in flash addr=0x%lx, wtlen=%d\r\n", addr, wtlen);
+ STMFlashWrite(addr, (u16*)pBuf, wtlen/2, 1);
+#else
+ printf("not support addr=0x%lx, wtlen=%d\r\n", addr, wtlen);
+#endif
+ return thislen;
+}
+
+// жϽǷ
+// ؽյ
+int IsAppReceiveDone(void)
+{
+ return (int)g_gnpuHead.datalen - (int)g_saveAppCtrl.rsvCounter;
+}
+
+u32 GetAppSaveDataCrc(u32 addr, u32 size)
+{
+#define RD_DAT_BUF_LEN (1024) // ֽ
+
+ // flashٴ֤
+ u32 crc;
+
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+ u8 rdata[RD_DAT_BUF_LEN];
+#else
+ u8 volatile rdata[RD_DAT_BUF_LEN];
+#endif
+
+ int i, thislen, rsvlen;
+ rsvlen = size;
+ crc = CRC32_INIT;
+
+ while(addr < APP_ADDR_BEG+size)
+ {
+ if (rsvlen > RD_DAT_BUF_LEN)
+ {
+ thislen = RD_DAT_BUF_LEN;
+ rsvlen -= RD_DAT_BUF_LEN;
+ }
+ else
+ {
+ thislen = rsvlen;
+ rsvlen = 0;
+ }
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ DatFlashRdData(addr, rdata, RD_DAT_BUF_LEN); // ȡһ
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ memcpy(rdata, (void*)addr, RD_DAT_BUF_LEN);
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ STMFlashRead(addr, (u16*)rdata, RD_DAT_BUF_LEN/2);
+#else
+#endif
+
+ for (i = 0; i < thislen; i++)
+ {
+ crc = AddCrc32(crc, rdata[i]);
+ }
+
+ addr += RD_DAT_BUF_LEN; // ַ
+ }
+ return crc;
+}
+
+
+int IsSaveDataCorrect(void)
+{
+ u32 crc, hddatsize;
+ int rslt;
+
+ if (g_saveAppCtrl.isrnpufile == 0)
+ {
+ printf("g_isrnpufile == 0\r\n");
+ return 0;
+ }
+
+ hddatsize = sizeof(g_gnpuHead) - sizeof(g_gnpuHead.rev) - 4; //
+ crc = CalcCrc32((u8*)(&g_gnpuHead), hddatsize);
+
+ rslt = -1;
+
+ printf("check g_gnpuHead crc = 0x%lx \r\n",crc);
+ printf("g_gnpuHead.hddatcrc = 0x%lx \r\n",g_gnpuHead.hddatcrc);
+ printf("g_gnpuHead.bincrc = 0x%lx \r\n",g_gnpuHead.bincrc);
+ printf("g_saveAppCtrl.bincrc = 0x%lx \r\n",g_saveAppCtrl.bincrc);
+ printf("g_gnpuHead.rnpucrc = 0x%lx \r\n",g_gnpuHead.rnpucrc);
+ printf("g_saveAppCtrl.rnpucrc = 0x%lx \r\n",g_saveAppCtrl.rnpucrc);
+ printf("g_gnpuHead.datalen = 0x%lx \r\n",g_gnpuHead.datalen);
+ printf("g_saveAppCtrl.rsvCounter = 0x%lx \r\n",g_saveAppCtrl.rsvCounter);
+
+ if (g_gnpuHead.hddatcrc == crc &&
+ g_gnpuHead.bincrc == g_saveAppCtrl.bincrc &&
+ g_gnpuHead.rnpucrc == g_saveAppCtrl.rnpucrc &&
+ 1 )
+ {
+ crc = GetAppSaveDataCrc(APP_ADDR_BEG, g_gnpuHead.datalen);
+
+ printf("calc crc = 0x%x, g_gnpuHead.bincrc = 0x%x\r\n", crc, g_gnpuHead.bincrc);
+
+ if (g_gnpuHead.bincrc == crc)
+ {
+ rslt = 0;
+ }
+ else
+ {
+ printf("re calc file data crc error\r\n");
+ }
+ }
+ else
+ {
+ printf("receive file crc error\r\n");
+ }
+
+ return rslt;
+}
+
+
+// APP
+void StartAppUpdate(int reboot)
+{
+ if (IsSaveDataCorrect() == 0)
+ {
+ u32 rdstart, wrstart, len, wtlen, check;
+
+ rdstart = (APP_ADDR_BEG - APP_SAVE_BASE);
+ wrstart = (STM32_APP_ADDR - STM32_FLASH_BASE); // ļʼַ
+ len = g_gnpuHead.datalen;
+ wtlen = (g_gnpuHead.datalen + STM32_FLASH_RW_SIZE - 1) / STM32_FLASH_RW_SIZE;
+ wtlen *= STM32_FLASH_RW_SIZE;
+ check = g_gnpuHead.bincrc;
+
+ printf("StartAppUpdate rdstart = 0x%x, wrstart = 0x%x, len = %d, wtlen = %d, wcrc=0x%x\r\n", rdstart, wrstart, len, wtlen, check);
+
+ IapWritePara(rdstart, wrstart, len, wtlen, check);
+
+#if (1) // Ϊ֣Ҫ
+ RestartMcu(); // MCU
+#else
+ if (reboot != 0)
+ {
+ RestartMcu(); // MCU
+ }
+ else
+ {
+ UpdateApp(); // ļ
+ JumpToApp(); // APP
+ }
+#endif
+ }
+ else
+ {
+ printf("IsSaveDataCorrect failed\r\n");
+ }
+}
+
+
+#endif
+
+
+
diff --git a/NxFuncs/stiap/stapp.h b/NxFuncs/stiap/stapp.h
new file mode 100644
index 0000000..783d885
--- /dev/null
+++ b/NxFuncs/stiap/stapp.h
@@ -0,0 +1,76 @@
+
+#ifndef __STAPP_H__
+#define __STAPP_H__
+
+#include "config.h"
+
+//-----------------------------------------------------
+
+#define APP_SAVE_NONE 0
+#define APP_SAVE_NORFLASH 1 // ⲿnorflash
+#define APP_SAVE_EXRAM 2 // ⲿRAM
+#define APP_SAVE_INFLASH 3 // ֱFLASH(Cortex-M4ֹʹø÷ʽ)
+
+#ifndef APP_SAVE_TO
+#define APP_SAVE_TO APP_SAVE_NONE //
+#endif
+
+//-----------------------------------------------------
+
+// ļͷ
+typedef struct
+{
+// 0x00
+ char fileName[32]; // ļ
+// 0x20
+ u32 dataSize; // ֽ
+ u32 dataChecksum; // ۼУ
+
+// 0x28
+ u8 reserved1[0x30-0x28]; // 1
+
+// 0x30
+ u8 reserved2[0x64-0x30]; // 2
+
+// 0x64
+ u8 reserved3[0x80-0x64]; // 3
+
+// 0x80
+ u8 reserved4[0x100-0x80]; // 4
+}__attribute__ ((packed)) AppFileHead;
+
+
+// ļƽṹ
+typedef struct
+{
+ int enflag; // ļЧ־
+ AppFileHead fileHead; // ļͷ
+
+ u8 pAppBuff[1024]; // ݴ洢ַ
+
+}AppFileCtrl;
+
+//-----------------------------------------------------
+
+#ifdef _IN_STAPP_C
+AppFileCtrl g_appFile;
+#else
+extern AppFileCtrl g_appFile;
+#endif
+
+//-----------------------------------------------------
+
+// ֵ֧ݰ
+#define SUPPORT_LEN_1 128 // for xmodem
+#define SUPPORT_LEN_2 1024 // for xmodem or ethernet
+
+void InitSaveApp(void);
+int SaveAppData(int idx, u8 * pBuf, int len, u32 ofst);
+int IsAppReceiveDone(void);
+int IsSaveDataCorrect(void);
+void StartAppUpdate(int reboot);
+u32 GetAppSaveDataCrc(u32 addr, u32 size);
+
+//-----------------------------------------------------
+
+#endif
diff --git a/NxFuncs/stiap/stflash.c b/NxFuncs/stiap/stflash.c
new file mode 100644
index 0000000..7c48388
--- /dev/null
+++ b/NxFuncs/stiap/stflash.c
@@ -0,0 +1,610 @@
+
+#include "stflash.h"
+#include "trigger.h"
+
+//--------------------------------------------------------------------
+
+#define STM32_FLASH_TIMOUT -1 // ʱ
+#define STM32_FLASH_OK 0 //
+#define STM32_FLASH_BUSY 1 // æ
+#define STM32_FLASH_ERROR 2 //
+
+//--------------------------------------------------------------------
+
+#define MAX_WAIT_TIME 2000 // ȴʱ2
+
+//--------------------------------------------------------------------
+
+// ȴ
+// waitmsȴʱ(ms)
+int FlashWaitNoBusy(int waitms)
+{
+ int timout = waitms;
+ u32 timer;
+ u32 tick = GetMsSoftTimer();
+
+ do
+ {
+ if (READ_BIT(FLASH->SR, FLASH_SR_BSY) != (FLASH_SR_BSY))
+ {
+ break;
+ }
+ timer = GetMsSoftTimer();
+
+ if ((timer - tick) > timout)
+ {
+ return STM32_FLASH_TIMOUT;
+ }
+ }while (1);
+
+ if ((FLASH->SR & (FLASH_SR_EOP)) != 0)
+ {
+ CLEAR_BIT(FLASH->SR, FLASH_SR_EOP);
+ }
+#if (0)
+ timer = GetMsSoftTimer();
+ printf("FlashWaitNoBusy time=%d\r\n", timer - tick);
+#endif
+
+ return STM32_FLASH_OK;
+}
+
+// ȡ״̬
+int FLASHGetStatus(void)
+{
+ u32 temp = FLASH->SR;
+
+ if ((temp & FLASH_SR_BSY) != 0)
+ {
+ return STM32_FLASH_BUSY; // æ
+ }
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+ if ((temp & ( FLASH_SR_WRPRTERR | // д
+ FLASH_SR_PGERR | // ̴
+ 0 ) ) != 0)
+#elif (__CORTEX_M == 4)
+ else if ((temp & ( FLASH_SR_WRPERR | // д
+ FLASH_SR_PGAERR | // ̶
+ FLASH_SR_PGPERR | // λ
+ FLASH_SR_PGSERR | // ˳
+ // FLASH_SR_RDERR |
+ 0 ) ) != 0)
+#endif
+ {
+ return STM32_FLASH_ERROR; //
+ }
+
+ return STM32_FLASH_OK; //
+}
+
+// õ
+int GetFlashSectorIdx(u32 faddr)
+{
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+ if (faddr >= STM32_FLASH_BASE)
+ {
+ faddr -= STM32_FLASH_BASE;
+ if (faddr <= STM32_FLASH_SIZE)
+ {
+ faddr /= STM32_FLASH_SEC_SIZE;
+ if (faddr < STM32_FLASH_SEC_NUM)
+ {
+ return faddr;
+ }
+ }
+ }
+
+#elif (__CORTEX_M == 4)
+
+#define FLS_RGCK(ad) \
+ if (faddr < STM32_FLASH_ADDR_SECTOR_##ad)\
+ {\
+ return (ad-1);\
+ }\
+ else \
+//------
+ FLS_RGCK(0)
+ FLS_RGCK(1)
+ FLS_RGCK(2)
+ FLS_RGCK(3)
+ FLS_RGCK(4)
+ FLS_RGCK(5)
+ FLS_RGCK(6)
+ FLS_RGCK(7)
+
+ if (faddr < STM32_FLASH_ADDR_SECTOR_7 + STM32_FLASH_SIZE_SECTOR_7)
+ {
+ return 7;
+ }
+#endif
+ return -1;
+}
+
+u32 GetFlashSectorBegAddr(u32 sidx)
+{
+ u32 addr = STM32_FLASH_BASE;
+
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+
+ if (sidx < STM32_FLASH_SEC_NUM)
+ {
+ addr += sidx * STM32_FLASH_SEC_SIZE;
+ }
+ else
+ {
+ addr += STM32_FLASH_SIZE;
+ }
+
+#elif (__CORTEX_M == 4)
+ switch (sidx)
+ {
+ case 0:
+ addr = STM32_FLASH_ADDR_SECTOR_0;
+ break;
+ case 1:
+ addr = STM32_FLASH_ADDR_SECTOR_1;
+ break;
+ case 2:
+ addr = STM32_FLASH_ADDR_SECTOR_2;
+ break;
+ case 3:
+ addr = STM32_FLASH_ADDR_SECTOR_3;
+ break;
+ case 4:
+ addr = STM32_FLASH_ADDR_SECTOR_4;
+ break;
+ case 5:
+ addr = STM32_FLASH_ADDR_SECTOR_5;
+ break;
+ case 6:
+ addr = STM32_FLASH_ADDR_SECTOR_6;
+ break;
+ case 7:
+ addr = STM32_FLASH_ADDR_SECTOR_7;
+ break;
+ default:
+ break;
+ }
+#endif
+ return addr;
+}
+
+int GetFlashSectorSize(u32 sidx)
+{
+ int size = 0;
+
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+
+ size = STM32_FLASH_SEC_SIZE;
+#elif (__CORTEX_M == 4)
+ switch (sidx)
+ {
+ case 0:
+ size = STM32_FLASH_SIZE_SECTOR_0;
+ break;
+ case 1:
+ size = STM32_FLASH_SIZE_SECTOR_1;
+ break;
+ case 2:
+ size = STM32_FLASH_SIZE_SECTOR_2;
+ break;
+ case 3:
+ size = STM32_FLASH_SIZE_SECTOR_3;
+ break;
+ case 4:
+ size = STM32_FLASH_SIZE_SECTOR_4;
+ break;
+ case 5:
+ size = STM32_FLASH_SIZE_SECTOR_5;
+ break;
+ case 6:
+ size = STM32_FLASH_SIZE_SECTOR_6;
+ break;
+ case 7:
+ size = STM32_FLASH_SIZE_SECTOR_7;
+ break;
+ default:
+ break;
+ }
+#endif
+ return size;
+}
+
+int GetSecRemainSize(u32 faddr)
+{
+ int sidx = GetFlashSectorIdx(faddr);
+ int slen = GetFlashSectorSize(sidx);
+ u32 baddr = GetFlashSectorBegAddr(sidx);
+ if (sidx < 0 || slen <= 0)
+ {
+ return -1;
+ }
+
+ return (baddr + slen - faddr);
+}
+
+//--------------------------------------------------------------------
+
+//
+void FLASHUnlock()
+{
+// printf("FLASHUnlock beg\r\n");
+
+ if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET)
+ {
+ WRITE_REG(FLASH->KEYR, FLASH_KEY1);
+ WRITE_REG(FLASH->KEYR, FLASH_KEY2);
+ }
+
+ while((READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET))
+ {}
+// printf("FLASHUnlock ok\r\n");
+}
+
+//
+void FLASHLock()
+{
+// printf("FLASHLock\r\n");
+
+ SET_BIT(FLASH->CR, FLASH_CR_LOCK); //
+}
+
+// STM32 flash д
+// ȡַָİ
+// faddr:ַ(˵ַΪ2ı)
+// data:
+void FLASHProgramHalfWord(uint32_t faddr, uint16_t data)
+{
+#if (__CORTEX_M == 4)
+ CLEAR_BIT(FLASH->CR, FLASH_CR_PSIZE);
+ SET_BIT(FLASH->CR, FLASH_PSIZE_HALF_WORD); // д
+#endif
+ SET_BIT(FLASH->CR, FLASH_CR_PG); //
+
+ *(__IO uint16_t*)faddr = data;
+}
+
+// STM32 flash
+// ȡַָİ(16λ)
+// faddr:ַ(˵ַΪ2ı)
+// ֵ:Ӧ
+u16 FlashRDHalfWord(u32 faddr)
+{
+ return *( __IO uint16_t*)faddr;
+}
+
+//
+void FLASHEraseSector(uint32_t secIdx)
+{
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+ SET_BIT(FLASH->CR, FLASH_CR_PER);
+ WRITE_REG(FLASH->AR, secIdx * STM32_FLASH_SEC_SIZE + STM32_FLASH_BASE);
+ SET_BIT(FLASH->CR, FLASH_CR_STRT);
+#elif (__CORTEX_M == 4)
+ CLEAR_BIT(FLASH->CR, FLASH_CR_PSIZE);
+ SET_BIT(FLASH->CR, FLASH_PSIZE_HALF_WORD); // д
+ SET_BIT(FLASH->CR, FLASH_CR_SER); // òʽ
+
+ CLEAR_BIT(FLASH->CR, FLASH_CR_SNB); // ַ
+ FLASH->CR |= (secIdx << FLASH_CR_SNB_Pos); // õַ
+ SET_BIT(FLASH->CR, FLASH_CR_STRT); // ʼ
+#endif
+}
+
+//-----------------------------------------------
+
+// д
+// wrAddr: ʼַ
+// pBuffer: ָ
+// hwNumToWrite: (16λ)
+int STMFlashWrNoCheck(u32 wrAddr, u16 *pBuffer, u16 hwNumToWrite)
+{
+ int rslt;
+ u16 i;
+ for (i = 0; i < hwNumToWrite; i++)
+ {
+ FLASHProgramHalfWord(wrAddr, *pBuffer);
+ pBuffer++;
+ wrAddr += 2; // ַ2
+
+ // ȴд
+ rslt = FlashWaitNoBusy(MAX_WAIT_TIME);
+ if (rslt != STM32_FLASH_OK)
+ {
+ rslt = FLASHGetStatus();
+ break;
+ }
+ FLASH->CR &= (~FLASH_CR_PG);
+ }
+ return rslt;
+}
+
+
+//-----------------------------------------------
+//
+
+int FLASHEraseSectorProc(uint32_t secIdx)
+{
+ int rslt;
+
+ if (secIdx < 0 || secIdx >= STM32_FLASH_SEC_NUM)
+ {
+ return STM32_FLASH_ERROR;
+ }
+
+ rslt = FlashWaitNoBusy(MAX_WAIT_TIME);
+ if (rslt != STM32_FLASH_OK)
+ {
+ rslt = FLASHGetStatus();
+ return rslt;
+ }
+
+ FLASHEraseSector(secIdx);
+
+ rslt = FlashWaitNoBusy(MAX_WAIT_TIME);
+ if (rslt != STM32_FLASH_OK)
+ {
+ rslt = FLASHGetStatus();
+ return rslt;
+ }
+#if (__CORTEX_M == 0 || __CORTEX_M == 3)
+ CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
+#elif (__CORTEX_M == 4)
+ CLEAR_BIT(FLASH->CR, (FLASH_CR_SER | FLASH_CR_SNB));
+#endif
+
+ return STM32_FLASH_OK;
+}
+
+//-----------------------------------------------
+
+
+void STMFlashUnlock()
+{
+ FLASHUnlock();
+}
+
+void STMFlashLock()
+{
+ FLASHLock();
+}
+
+int STMFlashErase(u32 secIdx, int secnums)
+{
+ int rslt = 0;
+
+ FLASHUnlock();
+
+ for (int i = 0; i < secnums; i++)
+ {
+ rslt = FLASHEraseSectorProc(secIdx);
+ if (rslt != STM32_FLASH_OK)
+ {
+ printf("STMFlashErase error, rslt=%d\r\n", rslt);
+ rslt = -1;
+ break;
+ }
+#if (0)
+ if (STMFlashCheck(secIdx * STM32_FLASH_SEC_SIZE + STM32_FLASH_BASE, 0, STM32_FLASH_SEC_SIZE) != 0)
+ {
+ printf("STMFlashErase and STMFlashCheck err, \r\n");
+ }
+#endif
+ secIdx++;
+ }
+
+ FLASHLock(); //
+
+ return rslt;
+}
+//-----------------------------------------------
+
+// ַָʼָȵ
+// rdAddr: ʼַ
+// pBuffer: ָ
+// hwNumOfRead: (16λ)
+int STMFlashRead(u32 rdAddr, u16 * pBuffer, u16 hwNumOfRead)
+{
+ u16 i;
+ if (pBuffer == NULL ||
+ rdAddr < STM32_FLASH_BASE ||
+ rdAddr + hwNumOfRead*2 > STM32_FLASH_BASE+STM32_FLASH_SIZE)
+ {
+ return -1;
+ }
+
+ for (i = 0; i < hwNumOfRead; i++)
+ {
+ *pBuffer = FlashRDHalfWord(rdAddr); // ȡ2ֽ
+ pBuffer++;
+ rdAddr += 2; // ַ2
+ }
+ return 0;
+}
+
+// ַָʼȽָȵǷһ
+// ckAddr: ʼַ
+// pBuffer: ָ
+// hwNumOfChekc: (16λ)
+// ֵ: 0, ȫ
+//
+int STMFlashCheck(u32 ckAddr, u16 * pBuffer, u16 hwNumOfChekc)
+{
+ int i;
+ u16 tprd, tpdat;
+ for(i = 0; i < hwNumOfChekc; i++)
+ {
+ tprd = FlashRDHalfWord(ckAddr); // ȡ2ֽ
+ if (pBuffer != NULL)
+ {
+ tpdat = *pBuffer;
+ }
+ else
+ {
+ tpdat = 0xffff;
+ }
+ if (tpdat != tprd)
+ {
+ printf("STMFlashCheck error, tpdat=0x%x, tprd=0x%x, i=%d\r\n", tpdat, tprd, i);
+ return 1;
+ }
+
+ if (pBuffer != NULL)
+ {
+ pBuffer++;
+ }
+ ckAddr += 2; // ַ2
+ }
+ return 0;
+}
+
+// ַָʼдָȵ
+// wrAddr: ʼַ(˵ַΪ2ı)
+// pBuffer: ָ
+// hwNumToWrite: (16λ)(Ҫд16λݵĸ)
+// svwhenera == 0, ʱд֮
+// svwhenera == 1, ʱд֮ǰ
+// svwhenera == 2, ʱд֮
+// svwhenera == 3, ʱд֮
+
+// ʹsdram һοռ䣨128K
+
+int STMFlashWrite(u32 wrAddr, u16 * pBuffer, u16 hwNumToWrite, int svwhenera)
+{
+ int rslt;
+ u16 * thiswrbuff;
+
+ u32 addr, addrEnd, thiswraddr;
+ u32 wrlen, thiswrlen;
+ int thissidx, thisslen;
+ u32 thisaddr, thislen;
+
+#if (NO_BUFF_WHEN_WT == 0)
+ u32 i;
+
+ u16 tempbuf[STM32_FLASH_SEC_SIZE/2];
+
+#endif
+
+ addr = wrAddr;
+ wrlen = hwNumToWrite * 2;
+ addrEnd = wrAddr + wrlen;
+
+ if (wrAddr < STM32_FLASH_BASE || (addrEnd > (STM32_FLASH_BASE + STM32_FLASH_SIZE)))
+ {
+ return -1; // Ƿַ
+ }
+
+ FLASHUnlock(); // flash
+
+ //
+ while (addr < addrEnd)
+ {
+ thisaddr = addr; // ʼַ
+
+ thissidx = GetFlashSectorIdx(thisaddr);
+ thisslen = GetFlashSectorSize(thissidx);
+ if (thissidx < 0 || thisslen <= 0)
+ {
+ return -1;
+ }
+
+ thislen = GetSecRemainSize(thisaddr); // ʣ
+ if (thislen > wrlen)
+ {
+ thislen = wrlen;
+ }
+
+ rslt = FlashWaitNoBusy(MAX_WAIT_TIME);
+ if (rslt != STM32_FLASH_OK)
+ {
+ rslt = FLASHGetStatus();
+ printf("STMFlashWrite error, FlashWaitNoBusy=%d\r\n", rslt);
+ return rslt;
+ }
+
+#if (NO_BUFF_WHEN_WT == 0)
+ // жǷҪ
+ STMFlashRead(thisaddr, tempbuf, thislen/2); //
+ for (i = 0; i < thislen/2; i++) // ǷҪ
+ {
+ #if (1) // st ڲ flash ֧дflashijЩ1λ0λ flash֧֣
+ if (tempbuf[i] != 0xffff) // ֻҪȫ1, Ͳ
+ #else
+ if ((tempbuf[i] & pBuffer[i]) != pBuffer[i]) // ֮ҪдͬԲ
+ #endif
+ {
+ break; // Ҫ
+ }
+ }
+
+ if (i < thislen/2) // Ҫ
+ {
+ u32 secbegaddr;
+ u8* wrbufaddr;
+
+ // printf("\r\nErase sector %d\r\n", thissidx);
+ secbegaddr = GetFlashSectorBegAddr(thissidx);
+
+ // ȡ
+ if (thisaddr != secbegaddr || thislen != thisslen)
+ {
+ STMFlashRead(secbegaddr, tempbuf, thisslen/2);
+ }
+
+ //
+ if (FLASHEraseSectorProc(thissidx) != STM32_FLASH_OK) //
+ {
+ printf("\r\nErase sector %d error\r\n", thissidx);
+ break;
+ }
+
+ // Ҫдݵ
+ wrbufaddr = (u8*)tempbuf;
+ wrbufaddr += thisaddr-secbegaddr;
+ memcpy(wrbufaddr, pBuffer, thislen);
+
+ if (svwhenera == 0) // ʱд֮
+ {
+ thiswraddr = thisaddr;
+ thiswrbuff = pBuffer;
+ thiswrlen = thislen;
+ }
+ else if (svwhenera == 1) // ʱд֮ǰ
+ {
+ thiswraddr = secbegaddr;
+ thiswrbuff = tempbuf;
+ thiswrlen = thislen + (thisaddr - secbegaddr);
+ }
+ else if (svwhenera == 2) // ʱд֮
+ {
+ thiswraddr = thisaddr;
+ thiswrbuff = (u16*)wrbufaddr;
+ thiswrlen = thisslen - (thisaddr - secbegaddr);
+ }
+ else // if (svwhenera == 3) // ʱд֮
+ {
+ thiswraddr = secbegaddr;
+ thiswrbuff = tempbuf;
+ thiswrlen = thisslen; //
+ }
+ }
+ else
+#endif
+ {
+ thiswraddr = thisaddr;
+ thiswrbuff = pBuffer;
+ thiswrlen = thislen;
+ }
+
+ // д
+ STMFlashWrNoCheck(thiswraddr, thiswrbuff, thiswrlen / 2); // д
+ pBuffer += thislen;
+ addr += thislen;
+ wrlen -= thislen;
+ }
+
+ FLASHLock(); //
+
+ return 0;
+}
diff --git a/NxFuncs/stiap/stflash.h b/NxFuncs/stiap/stflash.h
new file mode 100644
index 0000000..e1a055c
--- /dev/null
+++ b/NxFuncs/stiap/stflash.h
@@ -0,0 +1,139 @@
+
+#ifndef __STFLASH_H__
+#define __STFLASH_H__
+
+#include "config.h"
+
+#ifndef STM32_FLASH_BASE
+#define STM32_FLASH_BASE FLASH_BASE // STM32 FLASH ʼַ
+#endif
+
+#ifdef FLASH_END
+#define STM32_FLASH_SIZE (FLASH_END - FLASH_BASE + 1) // ѡSTM32FLASHС(λΪֽ)
+#else
+#ifdef FLASH_BANK1_END
+#define STM32_FLASH_SIZE (FLASH_BANK1_END - FLASH_BASE + 1) // ѡSTM32FLASHС(λΪֽ)
+#endif
+#endif
+
+
+
+
+#if (__CORTEX_M == 0)
+/*
+ С64Kÿ洢黮Ϊ1Kֽڵҳ(F03x, F04x, F05x)
+
+ ڵ128Kÿ洢黮Ϊ2Kֽڵҳ(F07x, F09x)
+
+
+*/
+#if (STM32_FLASH_SIZE <= (64*1024))
+ #define STM32_FLASH_SEC_SIZE (1*1024) //
+#else
+ #define STM32_FLASH_SEC_SIZE (2*1024) //
+#endif
+
+#define STM32_FLASH_SEC_NUM (STM32_FLASH_SIZE/STM32_FLASH_SEC_SIZE) //
+
+#define STM32_FLASH_RW_SIZE (STM32_FLASH_SEC_SIZE) // ÿζдֽ
+
+#elif (__CORTEX_M == 3)
+
+/*
+ СƷ洢Ϊ4K64λÿ洢黮Ϊ321Kֽڵҳ
+ Ʒ洢Ϊ16K64λÿ洢黮Ϊ1281Kֽڵҳ
+ Ʒ洢Ϊ64K64λÿ洢黮Ϊ2562Kֽڵҳ
+ ͲƷ洢Ϊ32K64λÿ洢黮Ϊ1282Kֽڵҳ
+*/
+
+#if (STM32_FLASH_SIZE <= (128*1024))
+ #define STM32_FLASH_SEC_SIZE (1*1024) // ÿֽ 1Kֽ
+#else
+ #define STM32_FLASH_SEC_SIZE (2*1024) // ÿֽ 2Kֽ
+#endif
+
+#define STM32_FLASH_SEC_NUM (STM32_FLASH_SIZE/STM32_FLASH_SEC_SIZE) //
+
+#define STM32_FLASH_RW_SIZE (STM32_FLASH_SEC_SIZE) // ÿζдֽ
+
+
+#elif (__CORTEX_M == 4)
+
+// STM32 FLASH ʼַ
+#define STM32_FLASH_ADDR_SECTOR_0 ((u32)(STM32_FLASH_BASE + 0x000000)) // 0 ʼַ, 16 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_1 ((u32)(STM32_FLASH_BASE + 0x004000)) // 1 ʼַ, 16 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_2 ((u32)(STM32_FLASH_BASE + 0x008000)) // 2 ʼַ, 16 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_3 ((u32)(STM32_FLASH_BASE + 0x00C000)) // 3 ʼַ, 16 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_4 ((u32)(STM32_FLASH_BASE + 0x010000)) // 4 ʼַ, 64 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_5 ((u32)(STM32_FLASH_BASE + 0x020000)) // 5 ʼַ, 128 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_6 ((u32)(STM32_FLASH_BASE + 0x040000)) // 6 ʼַ, 128 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_7 ((u32)(STM32_FLASH_BASE + 0x060000)) // 7 ʼַ, 128 Kbytes
+
+#if (STM32_FLASH_SIZE > (512*1024))
+#define STM32_FLASH_ADDR_SECTOR_8 ((u32)(STM32_FLASH_BASE + 0x080000)) // 8 ʼַ, 128 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_9 ((u32)(STM32_FLASH_BASE + 0x0A0000)) // 9 ʼַ, 128 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_10 ((u32)(STM32_FLASH_BASE + 0x0C0000)) // 10 ʼַ, 128 Kbytes
+#define STM32_FLASH_ADDR_SECTOR_11 ((u32)(STM32_FLASH_BASE + 0x0E0000)) // 11 ʼַ, 128 Kbytes
+
+#define STM32_FLASH_SEC_NUM 12
+#else
+#define STM32_FLASH_SEC_NUM 8 //
+#endif
+
+#define STM32_FLASH_SIZE_SECTOR_0 ((u32)(16*1024)) // 0 С, 16 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_1 ((u32)(16*1024)) // 1 С, 16 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_2 ((u32)(16*1024)) // 2 С, 16 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_3 ((u32)(16*1024)) // 3 С, 16 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_4 ((u32)(64*1024)) // 4 С, 64 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_5 ((u32)(128*1024)) // 5 С, 128 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_6 ((u32)(128*1024)) // 6 С, 128 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_7 ((u32)(128*1024)) // 7 С, 128 Kbytes
+
+#if (STM32_FLASH_SIZE > (512*1024))
+#define STM32_FLASH_SIZE_SECTOR_8 ((u32)(128*1024)) // 8 С, 128 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_9 ((u32)(128*1024)) // 9 С, 128 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_10 ((u32)(128*1024)) // 10 С, 128 Kbytes
+#define STM32_FLASH_SIZE_SECTOR_11 ((u32)(128*1024)) // 11 С, 128 Kbytes
+#endif
+
+#define STM32_FLASH_RW_SIZE (2*1024) // ÿζдֽ
+
+#endif
+
+#define STM32_APP_ADDR (STM32_FLASH_BASE+STM32_BOOT_SIZE) // Ӧóʼַ(FLASH)
+
+#ifndef STF_UPDATE_SIZE
+#define STF_UPDATE_SIZE (0) // ļ洢ĴС
+#endif
+
+#ifndef STM32_PARA_SIZE
+#define STM32_PARA_SIZE (0) // 洢С
+#endif
+
+#ifdef STM32_FLASH_SEC_SIZE
+#define MARK_SIZE (STM32_FLASH_RW_SIZE) // ־洢ĴС
+
+#define STF_UPDATE_BEGIN (STM32_FLASH_BASE+STM32_FLASH_SIZE-STM32_PARA_SIZE-STF_UPDATE_SIZE-MARK_SIZE)
+
+#define STM32_PARA_ADDR (STM32_FLASH_BASE+STM32_FLASH_SIZE-STM32_PARA_SIZE)
+
+#endif
+
+//-------------------------------------------------------------------------
+// Cortex-M4,FLASHСһ,д
+#ifndef NO_BUFF_WHEN_WT
+#define NO_BUFF_WHEN_WT 0
+#endif
+
+//-------------------------------------------------------------------------
+int GetFlashSectorIdx(u32 faddr);
+
+int STMFlashErase(u32 secIdx, int secnums);
+int STMFlashRead(u32 rdAddr, u16 * pBuffer, u16 hwNumToWrite);
+int STMFlashCheck(u32 ckAddr, u16 * pBuffer, u16 hwNumOfChekc);
+int STMFlashWrite(u32 wrAddr, u16 * pBuffer, u16 hwNumToWrite, int svwhenera);
+
+//-------------------------------------------------------------------------
+
+#endif
+
diff --git a/NxFuncs/stiap/stiap.c b/NxFuncs/stiap/stiap.c
new file mode 100644
index 0000000..53e617f
--- /dev/null
+++ b/NxFuncs/stiap/stiap.c
@@ -0,0 +1,453 @@
+
+#include "stiap.h"
+
+#include "stapp.h"
+
+#include "crc32.h"
+#include "trigger.h"
+#include "shell.h"
+#include "delay.h"
+
+#if (0) // ʱʩ,
+#include "can.h"
+#include "fmc.h"
+#endif
+
+//===================================================================
+// IAP
+// stfaddr: Ӧóʼַ
+// saveaddr: Ӧó NORFLASH RAM ʼַ.
+// size: ӦóС ֽڣ
+
+int WriteAppBinData(u32 stfaddr, u32 saveaddr, u32 size)
+{
+ int rslt = 0;
+ u32 faddr = stfaddr;
+ u32 saddr = saveaddr;
+ u32 wrsize = size;
+ u16 thissize;
+#ifdef STM32_FLASH_SEC_SIZE // ÿֽ
+#define STM32_RW_BUFF_SIZE (STM32_FLASH_SEC_SIZE)
+#else
+#define STM32_RW_BUFF_SIZE (STM32_FLASH_RW_SIZE)
+#endif
+
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH || APP_SAVE_TO == APP_SAVE_INFLASH)
+ u8 iapbuf[STM32_RW_BUFF_SIZE];
+#else
+ u8 * iapbuf;
+#endif
+
+#if (NO_BUFF_WHEN_WT == 1) // 20230928 ljs дʱǰӦ,дʧ
+ u32 secIdx = GetFlashSectorIdx(faddr);
+ u32 secnums = GetFlashSectorIdx(faddr+wrsize);
+ secnums = secnums - secIdx + 1;
+ STMFlashErase(secIdx, secnums);
+#endif
+
+ printf("Write data to addr = 0x%x begin\r\n", (unsigned int)faddr);
+ while (wrsize > 0)
+ {
+ if (wrsize < STM32_RW_BUFF_SIZE)
+ {
+ thissize = wrsize;
+ }
+ else
+ {
+ thissize = STM32_RW_BUFF_SIZE;
+ }
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ DatFlashRdData(saddr, iapbuf, thissize); // norflash
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ iapbuf = (u8*)saddr; // ram
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ STMFlashRead(saddr, (u16*)iapbuf, thissize/2); // st flash
+#else
+ break;
+#endif
+
+ STMFlashWrite(faddr, (u16*)iapbuf, thissize/2, 1); // дݵstm32flash
+
+ rslt = STMFlashCheck(faddr, (u16*)iapbuf, thissize/2); // ȷ
+ if (rslt != 0)
+ {
+ printf("\r\nWriteAppBinData error. addr=0x%x, size=%d\r\n", (unsigned int)faddr, thissize);
+ break;
+ }
+ PutChar('.');
+ faddr += thissize; // ָƫ
+ saddr += thissize; // ָƫ
+ wrsize -= thissize;
+ }
+
+ printf("write data finish\r\n");
+
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+ if (rslt == 0)
+ {
+ // У
+ printf("WriteAppBinData finish, check all data\r\n");
+ rslt = STMFlashCheck(stfaddr, (u16*)saveaddr, size/2); // ȷ
+ if (rslt == 0)
+ {
+ printf("WriteAppBinData ok\r\n");
+ }
+ }
+#endif
+
+ if (rslt != 0)
+ {
+ printf("WriteAppBinData failed\r\n");
+ }
+
+ return rslt;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+// 20230523 ʹⲿRAM
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+char g_appEnFlag[16] = {0xff};
+void SetAppEnFlag(int flag)
+{
+ if (flag == 0)
+ {
+ memset(g_appEnFlag, 0xff, 16);
+ }
+ else
+ {
+ strcpy(g_appEnFlag, APP_RIGHT);
+ }
+}
+
+int IsAppRight(void)
+{
+ if (strcmp((void*)APP_RIGHT, g_appEnFlag) != 0)
+ {
+ return -1;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+#endif
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+
+// bootloader ӿں
+// ļӴ洢APP
+int UpdateApp(void)
+{
+ int rslt = 0;
+ u32 saveaddr; // ݶȡַ
+ u32 stfaddr; // дַ
+ u32 appsize, wsize;
+ u32 crc;
+ IapHead iaphd;
+ u32 resetaddr, stacktop;
+
+ memset(&iaphd, 0, sizeof(IapHead));
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ u32 taddr = (u32)(&iaphd);
+ DatFlashRdData(APP_MARK_ADDR, (u8 *)(taddr), sizeof(IapHead)/sizeof(u8)); //
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ memcpy((void*)(&iaphd), (void*)APP_MARK_ADDR, sizeof(IapHead)); // iaphead
+ SetAppEnFlag(1);
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ u32 taddr = (u32)(&iaphd);
+ STMFlashRead(APP_MARK_ADDR, (u16*)(taddr), sizeof(IapHead)/sizeof(u16));
+#endif
+
+ crc = CalcCrc32((u8*)&(iaphd), sizeof(IapHead)-sizeof(iaphd.checkcrc)); // У֮ǰֶ
+
+ printf("UpdateApp begin\r\n");
+#if (0)
+ printf("iaphd.upmask=%s\r\n", iaphd.upmask);
+ printf("iaphd.rdaddr=0x%x\r\n", iaphd.rdaddr);
+ printf("iaphd.wraddr=0x%x\r\n", iaphd.wraddr);
+ printf("iaphd.size=0x%x\r\n", iaphd.size);
+ printf("iaphd.wsize=0x%x\r\n", iaphd.wsize);
+ printf("iaphd.appcheck=0x%x\r\n", iaphd.appcheck);
+ printf("calc iaphd crc = 0x%x, save iaphd.checkcrc = 0x%x\r\n", crc, iaphd.checkcrc);
+#endif
+
+ // У
+ if (crc != iaphd.checkcrc)
+ {
+ printf("updatedata checkcrc err\r\n");
+ return -1; // У
+ }
+
+ if (strcmp((void*)STM32_MARK, iaphd.upmask) != 0) // Ƚ
+ {
+ printf("updatedata upmask err\r\n");
+ return 0; // һ,
+ }
+
+ saveaddr = iaphd.rdaddr + APP_SAVE_BASE; // ȡַ
+ stfaddr = iaphd.wraddr + STM32_FLASH_BASE; // дַ
+ appsize = iaphd.size;
+ wsize = iaphd.wsize;
+
+ if ((stfaddr < STM32_APP_ADDR) ||
+ (stfaddr >= (STM32_FLASH_BASE + STM32_FLASH_SIZE)) ||
+ (saveaddr < APP_ADDR_BEG) ||
+ 0 ) // ַҪ
+ {
+ printf("flash addr error\r\n");
+ return -2;
+ }
+
+ crc = GetAppSaveDataCrc(saveaddr, appsize);
+
+ if (crc != iaphd.appcheck)
+ {
+ printf("save data crc check error, crc=0x%x, appcheck=0x%x\r\n", crc, iaphd.appcheck);
+ return -2;
+ }
+
+ // Ӵ洢жȡλַջַ
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ {
+ u8 buff[8];
+ DatFlashRdData(APP_ADDR_BEG, buff, 8);
+ stacktop = *(__IO uint32_t*)(buff); // ջַ
+ resetaddr = *(__IO uint32_t*)(buff+4); // λַ
+ }
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM || APP_SAVE_TO == APP_SAVE_INFLASH)
+ stacktop = *(__IO uint32_t*)(APP_ADDR_BEG); // ջַ
+ resetaddr = *(__IO uint32_t*)(APP_ADDR_BEG+4); // λַ
+#else
+ return -2;
+#endif
+
+ printf("save file stacktop = 0x%x, resetaddr=0x%x\r\n", (unsigned int)stacktop, (unsigned int)resetaddr);
+ if ((resetaddr >= STM32_APP_ADDR) &&
+ ((resetaddr & 0xFF000000) == 0x08000000) && // жǷΪ0X08XXXXXX
+ ((stacktop & 0x2FFC0000) == 0x20000000) && // ջַǷϷ
+ 1 )
+ {
+ printf("save data ok\r\n");
+ }
+ else
+ {
+ printf("save data not right\r\n");
+ return -2;
+ }
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+ SetAppEnFlag(0); // appȷ־....
+#endif
+ printf("UpdateApp: from add=0x%x to stadd=0x%x, size=%d, wsize=%d\r\n", saveaddr, stfaddr, appsize, wsize);
+
+ rslt = WriteAppBinData(stfaddr, saveaddr, wsize); // FLASH
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ DatFlash4kErase(APP_MARK_ADDR, 1); // , ־,
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ memset((void*)APP_MARK_ADDR, 0xff, IAPHEAD_LEN); // ȫдΪ0xff
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ STMFlashErase(GetFlashSectorIdx(APP_MARK_ADDR), 1);
+#endif
+
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+ if (rslt == 0)
+ {
+ SetAppEnFlag(1);
+ }
+#endif
+ return rslt;
+}
+
+// ر
+__WEAK void CloseAllPeripheral()
+{
+ __disable_irq(); // رж
+
+#if (0) // ʱʩ,
+ HAL_DeInit();
+
+ LL_GPIO_DeInit(GPIOA);
+ LL_GPIO_DeInit(GPIOB);
+ LL_GPIO_DeInit(GPIOC);
+ LL_GPIO_DeInit(GPIOD);
+ LL_GPIO_DeInit(GPIOE);
+ LL_GPIO_DeInit(GPIOF);
+ LL_GPIO_DeInit(GPIOG);
+
+ LL_EXTI_DeInit();
+
+ HAL_ADC_DeInit(&hadc3);
+
+ HAL_CAN_DeInit(&HCAN);
+
+ HAL_SRAM_DeInit(&hsram1);
+ HAL_SRAM_DeInit(&hsram2);
+ HAL_SRAM_DeInit(&hsram3);
+ HAL_SRAM_DeInit(&hsram4);
+
+ LL_SPI_DeInit(SPI1);
+ LL_SPI_DeInit(SPI2);
+
+ LL_TIM_DeInit(TIM1);
+ LL_TIM_DeInit(TIM2);
+ LL_TIM_DeInit(TIM3);
+ LL_TIM_DeInit(TIM4);
+ LL_TIM_DeInit(TIM5);
+ LL_TIM_DeInit(TIM6);
+ LL_TIM_DeInit(TIM7);
+ LL_TIM_DeInit(TIM8);
+
+ LL_USART_DeInit(USART1);
+ LL_USART_DeInit(USART2);
+ LL_USART_DeInit(USART3);
+ LL_USART_DeInit(UART4);
+ LL_USART_DeInit(UART5);
+#else
+ LL_EXTI_DeInit();
+#endif
+
+ __disable_irq(); // رж
+}
+
+//===================================================================
+
+// תӦó
+int JumpToApp(void)
+{
+ typedef void (*iapfun)(void); // һ͵IJ.
+ int rslt;
+ u32 resetaddr, stacktop;
+
+ printf("Begin run app\r\n");
+
+ // flashжȡλַջַ
+ stacktop = *(__IO uint32_t*)(STM32_APP_ADDR); // ջַ
+ resetaddr = *(__IO uint32_t*)(STM32_APP_ADDR+4); // λַ
+ rslt = 0;
+
+#if (APP_SAVE_TO == APP_SAVE_EXRAM)
+ rslt = IsAppRight();
+#endif
+
+ printf("stacktop = 0x%x, resetaddr=0x%x\r\n", (unsigned int)stacktop, (unsigned int)resetaddr);
+
+ DelayMs(100);
+
+ if ( (rslt == 0) &&
+ (resetaddr >= STM32_APP_ADDR) &&
+ ((resetaddr & 0xFF000000) == 0x08000000) && // жǷΪ0X08XXXXXX
+ ((stacktop & 0x2FFC0000) == 0x20000000) && // ջַǷϷ
+ 1 )
+ {
+ iapfun jump;
+
+ printf("Jump to app address\r\n");
+
+ DelayMs(100);
+
+ CloseAllPeripheral();
+ DelayMs(100);
+
+ jump = (iapfun)(resetaddr); // ûڶΪʼַ(λַ)
+ __set_MSP(stacktop); // ʼ APP ջָ (ûĵһڴջַ)
+ jump(); // תAPP.
+ }
+
+ printf("run app failed\r\n");
+
+ return -1;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+// app iapģ鹦ܽӿں
+
+void IAPCleanUpdateArea(void)
+{
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ // norflash Ŀ
+ u32 addr;
+ int erflag;
+ int count = 0;
+
+ printf("IAPCleanUpdateArea, erase begin\r\n");
+
+ addr = NOR_SAVE_BASE;
+ while(addr < NOR_SAVE_END)
+ {
+ erflag = IsDatFlashEmpty(addr, SNF_BYTES_PER_SEC); // жһǷΪ
+
+ if (erflag != 0)
+ {
+ DatFlash4kErase(addr, 1); // һ
+ PutChar('.');
+ count++;
+ //erflag = IsDatFlashEmpty(addr, SNF_BYTES_PER_SEC); // жһǷΪ
+ //printf("erase failed, addr=%d, idx=%d, flag=%d\r\n", addr, (addr-NOR_SAVE_BASE)/SNF_BYTES_PER_SEC, erflag);
+ }
+ addr += SNF_BYTES_PER_SEC; // ַ
+ }
+
+ printf("IAPCleanUpdateArea finish, count=%d\r\n", count);
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ memset((void*)EXRAM_SAVE_BASE, 0xff, STM32_FLASH_SIZE); // ȫдΪ0xff
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ STMFlashErase(GetFlashSectorIdx(APP_SAVE_BASE), (STF_UPDATE_SIZE+MARK_SIZE)/STM32_FLASH_SEC_SIZE);
+#endif
+}
+
+// дʼַ, Ⱥ־
+void IapWritePara(u32 rdAddr, u32 wrAddr, u32 len, u32 wlen, u32 check)
+{
+ // ݳȱΪ(STM32_FLASH_SEC_SIZE)
+ IapHead iaphd;
+ memset(&iaphd, 0xff, sizeof(IapHead));
+
+ strcpy(iaphd.upmask, STM32_MARK);
+ iaphd.rdaddr = rdAddr;
+ iaphd.wraddr = wrAddr;
+ iaphd.size = len;
+ iaphd.wsize = wlen;
+ iaphd.appcheck = check;
+ iaphd.checkcrc = CalcCrc32((u8*)&(iaphd.upmask[0]), sizeof(IapHead)-sizeof(iaphd.checkcrc)); // У֮ǰֶ
+
+ printf("IapWritePara begin\r\n");
+
+#if (0)
+ printf("iaphd.upmask %s\r\n", iaphd.upmask);
+ printf("iaphd.rdaddr=0x%x\r\n", iaphd.rdaddr);
+ printf("iaphd.wraddr=0x%x\r\n", iaphd.wraddr);
+ printf("iaphd.size=0x%x\r\n", iaphd.size);
+ printf("iaphd.wsize=0x%x\r\n", iaphd.wsize);
+ printf("iaphd.appcheck=0x%x\r\n", iaphd.appcheck);
+ printf("iaphd.checkcrc = 0x%x\r\n", iaphd.checkcrc);
+#endif
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+ DatFlash4kErase(NOR_MARK_ADDR, 1); // 4k
+ u32 taddr = (u32)(&iaphd);
+ DatFlashWrData(NOR_MARK_ADDR, (u8*)(taddr), sizeof(IapHead)/sizeof(u8)); // д
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+ memcpy((void*)EXRAM_MARK_ADDR, (void*)(&(iaphd)), sizeof(IapHead));
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+ STMFlashErase(GetFlashSectorIdx(APP_MARK_ADDR), 1);
+ u32 taddr = (u32)(&iaphd);
+ STMFlashWrite(APP_MARK_ADDR, (u16*)(taddr), sizeof(IapHead)/sizeof(u16), 3); // д
+#endif
+
+ printf("IapWritePara end\r\n");
+
+ DelayMs(100);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+
diff --git a/NxFuncs/stiap/stiap.h b/NxFuncs/stiap/stiap.h
new file mode 100644
index 0000000..69e8724
--- /dev/null
+++ b/NxFuncs/stiap/stiap.h
@@ -0,0 +1,116 @@
+
+#ifndef __STIAP_H__
+#define __STIAP_H__
+
+#include "config.h"
+#include "stflash.h"
+#include "stapp.h"
+
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+#include "norflash.h"
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+#include "corefmc.h"
+#endif
+//-------------------------------------------------------------------------------
+/*
+ iap Ƴ
+ ͨ bootloader app
+ ֧ ݵ norflash exram st-flash Ȼдapp
+*/
+#if (APP_SAVE_TO == APP_SAVE_NORFLASH)
+
+#define NOR_SAVE_BASE (SNF_UPDATE_BEGIN) // NORflashдIAPݵĻַ = 32MB-512KB
+#define NOR_SAVE_SIZE (SNF_UPDATE_SIZE) // NORflashдIAPС
+
+#define NOR_SAVE_END (NOR_SAVE_BASE+NOR_SAVE_SIZE)
+
+#define NOR_MARK_ADDR (NOR_SAVE_BASE) // NORflashд־ַ1K
+#define NOR_APP_ADDR (NOR_SAVE_BASE+STM32_BOOT_SIZE) // NORflashӦóʼַ
+
+#define MASK_BUF_LEN 0x80
+
+
+ #define APP_SAVE_BASE NOR_SAVE_BASE
+ #define APP_ADDR_BEG NOR_APP_ADDR
+ #define APP_MARK_ADDR NOR_MARK_ADDR
+
+
+#elif (APP_SAVE_TO == APP_SAVE_EXRAM)
+
+#define EXRAM_SAVE_BASE CORE_SDRAM2_ADDR_BEG //
+
+#define EXRAM_APP_ADDR (EXRAM_SAVE_BASE + STM32_BOOT_SIZE) // APP ʼַ
+#define TMP_SEC_ADDR EXRAM_SAVE_BASE // ʱݴ洢ַ
+#define MAX_TMP_SIZE (STM32_BOOT_SIZE) // STM32_BOOT_SIZE
+
+#define EXRAM_MARK_ADDR TMP_SEC_ADDR
+
+#define MASK_BUF_LEN 0x80
+
+ #define APP_SAVE_BASE EXRAM_SAVE_BASE
+ #define APP_ADDR_BEG EXRAM_APP_ADDR
+ #define APP_MARK_ADDR EXRAM_MARK_ADDR
+
+#elif (APP_SAVE_TO == APP_SAVE_INFLASH)
+
+#define INFLASH_SAVE_BASE STF_UPDATE_BEGIN
+
+#define INFLASH_MARK_ADDR INFLASH_SAVE_BASE
+#define INFLASH_APP_ADDR (INFLASH_SAVE_BASE+MARK_SIZE)
+
+ #define MASK_BUF_LEN 0x80
+
+ #define APP_SAVE_BASE INFLASH_SAVE_BASE
+ #define APP_ADDR_BEG INFLASH_APP_ADDR
+ #define APP_MARK_ADDR INFLASH_MARK_ADDR
+#else
+
+#define MASK_BUF_LEN 0x80
+#define APP_SAVE_BASE 0
+#define APP_ADDR_BEG 0
+#define APP_MARK_ADDR 0
+
+#endif
+
+//--------------------------------------------------------------------
+
+#define IAPHEAD_LEN (1*1024)
+
+//--------------------------------------------------------------------
+
+#define STM32_MARK "APP_CAN_UPDATE" // ؼ
+#define APP_RIGHT "APP_FILE_RIGHT"
+
+typedef struct
+{
+ char upmask[MASK_BUF_LEN];
+ u32 rdaddr; // ݶȡƫƵַ
+ u32 wraddr; // дƫƵַ
+ u32 size; // ݳȣֽ
+ u32 wsize; // д볤
+ u32 appcheck; // app ݵУ
+
+ u8 rev[IAPHEAD_LEN - MASK_BUF_LEN - 4*5 - 4];
+ u32 checkcrc; // У
+} __attribute__ ((packed)) IapHead;
+
+//--------------------------------------------------------------------
+
+//bootloader ӿں
+int UpdateApp(void); // ļ
+int JumpToApp(void); // ִflashapp
+
+// ӿں
+void IAPCleanUpdateArea(void); // norflashĿ
+void IapWritePara(u32 rdAddr, u32 wrAddr, u32 len, u32 wlen, u32 check); // дʼַͳȺ־
+void IapRestartMcu(void); // STM32λ
+
+void CloseAllPeripheral(void);
+
+//--------------------------------------------------------------------
+
+
+//--------------------------------------------------------------------
+
+#endif
+
diff --git a/NxFuncs/stm32motos/stm32motos.c b/NxFuncs/stm32motos/stm32motos.c
new file mode 100644
index 0000000..f343a99
--- /dev/null
+++ b/NxFuncs/stm32motos/stm32motos.c
@@ -0,0 +1,1055 @@
+
+#define _IN_STM32MOTOS_C
+#include "stm32motos.h"
+#include "inout.h"
+#include "shell.h"
+
+//----------------------------------------------------------------------
+
+void TestStm32Motos(char * para1, char * para2); //ն˵Խӿ
+
+//---------------------------------------------------------------------------------------------
+
+typedef struct
+{
+ // ò
+ u32 pulseMode; // 0:cw/ccw !=0:pulse/dir
+ u32 startPPS; // ٶ
+ u32 runPPS; // ˶ٶ
+ u32 addPPSG; // ͣٶ
+ u32 brkPPSG; // ɲٶ
+
+ // ˶в
+ s32 realpos; //
+ int runState; // ״̬
+ int dir; // з
+ s32 currentSpd; // ǰٶ
+ u32 currentAcc; // ǰٶ
+ s32 totalAcc; // ۼӼٶ
+ u32 currentPos; // ǰλ
+ u32 totalPos; // λ
+ u32 decPos; // ٵλ
+ int pulseState; // ״̬ 0:ǰΪ0, !=ǰΪ1
+ int startrunflag; // б־
+
+ // ָ
+ u32 funTestTime; // йⲿʱ λ:0.1ms
+ u32 funTestCount; // йⲿʱ
+ int syncList[6]; // ͬƶѡ
+
+ int (*GetNormalStop)(u32,u32); // һֹͣΪʱֹͣ; Ϊʱ㣬ٵֹͣͣٶȽ٣
+ int (*GetQuickStop)(u32,u32); // ֹͣΪʱֹͣ; Ϊʱ㣬ٵֹͣɲٶȽ٣
+ u32 condPara1, condPara2; //
+
+ int blockRunflag; // б־
+ void (*ExecWhenRun)(void); // йִеĺ
+ void (*ExecWhenStart)(void); // ʱִеĺ
+ void (*ExecWhenStop)(void); // ֹͣʱִеĺ
+
+}TimerCtrl;
+
+
+//---------------------------------------------------------------------------------------------
+
+#ifndef SPEED_PSC
+#define SPEED_PSC 72
+#endif
+
+#define SPEED_TIME 100 // 0.1ms
+
+//---------------------------------------------------------------------------------------------
+// TIM1: 첽ٶȿ(0.1ж)
+
+#ifndef SPEED_TIM
+#define SPEED_TIM TIM1
+#endif
+
+#ifndef MOTO1_TIM
+#define MOTO1_TIM TIM2
+#endif
+
+#ifndef MOTO2_TIM
+#define MOTO2_TIM TIM3
+#endif
+
+#ifndef MOTO3_TIM
+#define MOTO3_TIM TIM4
+#endif
+
+#ifndef MOTO4_TIM
+#define MOTO4_TIM TIM5
+#endif
+
+#ifndef MOTO5_TIM
+#define MOTO5_TIM TIM6
+#endif
+
+#ifndef MOTO6_TIM
+#define MOTO6_TIM TIM7
+#endif
+
+//---------------------------------------------------------------------------------------------
+
+// ʱʱӣӦܽţж
+#ifndef MOOT_TIM_PSC
+#define MOOT_TIM_PSC 120 // ԤƵ
+#endif
+
+#define MOTO_FIN ((SYSCLK/MOOT_TIM_PSC)) // ʱƵ = ((RTE_SYSCLK / MOOT_TIM_PSC)/(@25kʱУϵ))
+
+#define SPD_MIN 10 // Ƶ λ: / = (MOTO_FIN / 65535)
+#define SPD_MAX 50000 // Ƶ λ: / = (MOTO_FIN / 10)
+
+#define ADD_MIN 1 // Сٶ
+#define ADD_MAX 100000 // ٶ λ: pps/s
+
+//---------------------------------------------------------------------------------------------
+
+
+OutFunc SoftPwmProc = SetOutputNull;
+
+OutFunc Moto1PulseOn = SetOutputNull;
+OutFunc Moto1PulseOff = SetOutputNull;
+OutFunc Moto1SignOn = SetOutputNull;
+OutFunc Moto1SignOff = SetOutputNull;
+
+OutFunc Moto2PulseOn = SetOutputNull;
+OutFunc Moto2PulseOff = SetOutputNull;
+OutFunc Moto2SignOn = SetOutputNull;
+OutFunc Moto2SignOff = SetOutputNull;
+
+OutFunc Moto3PulseOn = SetOutputNull;
+OutFunc Moto3PulseOff = SetOutputNull;
+OutFunc Moto3SignOn = SetOutputNull;
+OutFunc Moto3SignOff = SetOutputNull;
+
+OutFunc Moto4PulseOn = SetOutputNull;
+OutFunc Moto4PulseOff = SetOutputNull;
+OutFunc Moto4SignOn = SetOutputNull;
+OutFunc Moto4SignOff = SetOutputNull;
+
+OutFunc Moto5PulseOn = SetOutputNull;
+OutFunc Moto5PulseOff = SetOutputNull;
+OutFunc Moto5SignOn = SetOutputNull;
+OutFunc Moto5SignOff = SetOutputNull;
+
+OutFunc Moto6PulseOn = SetOutputNull;
+OutFunc Moto6PulseOff = SetOutputNull;
+OutFunc Moto6SignOn = SetOutputNull;
+OutFunc Moto6SignOff = SetOutputNull;
+
+//---------------------------------------------------------------------------------------------
+
+//
+void SetMotoPulseOn(int curAux, int syncList[6])
+{
+ if ((curAux == 1) || (syncList[1-1] == 1))
+ {
+ Moto1PulseOn();
+ }
+ if ((curAux == 2) || (syncList[2-1] == 1))
+ {
+ Moto2PulseOn();
+ }
+ if ((curAux == 3) || (syncList[3-1] == 1))
+ {
+ Moto3PulseOn();
+ }
+ if ((curAux == 4) || (syncList[4-1] == 1))
+ {
+ Moto4PulseOn();
+ }
+ if ((curAux == 5) || (syncList[5-1] == 1))
+ {
+ Moto5PulseOn();
+ }
+ if ((curAux == 6) || (syncList[6-1] == 1))
+ {
+ Moto6PulseOn();
+ }
+}
+
+//
+void SetMotoPulseOff(int curAux, int syncList[6])
+{
+ if ((curAux == 1) || (syncList[1-1] == 1))
+ {
+ Moto1PulseOff();
+ }
+ if ((curAux == 2) || (syncList[2-1] == 1))
+ {
+ Moto2PulseOff();
+ }
+ if ((curAux == 3) || (syncList[3-1] == 1))
+ {
+ Moto3PulseOff();
+ }
+ if ((curAux == 4) || (syncList[4-1] == 1))
+ {
+ Moto4PulseOff();
+ }
+ if ((curAux == 5) || (syncList[5-1] == 1))
+ {
+ Moto5PulseOff();
+ }
+ if ((curAux == 6) || (syncList[6-1] == 1))
+ {
+ Moto6PulseOff();
+ }
+}
+
+//
+void SetMotoSignOn(int curAux, int syncList[6])
+{
+ if ((curAux == 1) || (syncList[1-1] == 1))
+ {
+ Moto1SignOn();
+ }
+ if ((curAux == 2) || (syncList[2-1] == 1))
+ {
+ Moto2SignOn();
+ }
+ if ((curAux == 3) || (syncList[3-1] == 1))
+ {
+ Moto3SignOn();
+ }
+ if ((curAux == 4) || (syncList[4-1] == 1))
+ {
+ Moto4SignOn();
+ }
+ if ((curAux == 5) || (syncList[5-1] == 1))
+ {
+ Moto5SignOn();
+ }
+ if ((curAux == 6) || (syncList[6-1] == 1))
+ {
+ Moto6SignOn();
+ }
+}
+
+//
+void SetMotoSignOff(int curAux, int syncList[6])
+{
+ if ((curAux == 1) || (syncList[1-1] == 1))
+ {
+ Moto1SignOff();
+ }
+ if ((curAux == 2) || (syncList[2-1] == 1))
+ {
+ Moto2SignOff();
+ }
+ if ((curAux == 3) || (syncList[3-1] == 1))
+ {
+ Moto3SignOff();
+ }
+ if ((curAux == 4) || (syncList[4-1] == 1))
+ {
+ Moto4SignOff();
+ }
+ if ((curAux == 5) || (syncList[5-1] == 1))
+ {
+ Moto5SignOff();
+ }
+ if ((curAux == 6) || (syncList[6-1] == 1))
+ {
+ Moto6SignOff();
+ }
+}
+
+//---------------------------------------
+// ƺ궨
+
+#define USE_MOTO(x) \
+TimerCtrl g_moto##x##TimerCtrl; \
+ \
+/*---------------------------------------*/ \
+void InitStm32Moto##x##OutFunc(OutFunc stepOn, OutFunc StepOff, OutFunc dirOn, OutFunc dirOff) \
+{ \
+ Moto##x##PulseOn = stepOn; \
+ Moto##x##PulseOff = StepOff; \
+ Moto##x##SignOn = dirOn; \
+ Moto##x##SignOff = dirOff; \
+}\
+\
+void InitSTM32Moto##x##Ctrl(void) \
+{ \
+ LL_TIM_ClearFlag_UPDATE(MOTO##x##_TIM); /* жϱ־ */ \
+ LL_TIM_DisableIT_UPDATE(MOTO##x##_TIM); /* رж */ \
+ LL_TIM_DisableCounter(MOTO##x##_TIM); /* رնʱ */ \
+\
+ memset(&g_moto##x##TimerCtrl, 0, sizeof(TimerCtrl)); \
+ g_moto##x##TimerCtrl.pulseMode = MODE_STEPDIR; /* ģʽ */ \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* жϴ */ \
+void STM32Moto##x##IntProc(void) \
+{ \
+ if (LL_TIM_IsActiveFlag_UPDATE(MOTO##x##_TIM) != RESET) /* ָTIMжϷ */ \
+ { \
+ LL_TIM_ClearFlag_UPDATE(MOTO##x##_TIM); /* TIMxжϴλ */ \
+ \
+ if ((g_moto##x##TimerCtrl.currentPos >= g_moto##x##TimerCtrl.totalPos) || /* */ \
+ (g_moto##x##TimerCtrl.runState <= STM32MOTO_STOP) || /* ֹͣź */ \
+ 0 ) \
+ { \
+ SetMotoPulseOff(x,g_moto##x##TimerCtrl.syncList); /* ر */ \
+ SetMotoSignOff(x,g_moto##x##TimerCtrl.syncList); /* رշ */ \
+ LL_TIM_DisableCounter(MOTO##x##_TIM); /* رնʱ */ \
+ if (g_moto##x##TimerCtrl.runState > STM32MOTO_STOP) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_STOP; /* ״̬ */ \
+ g_moto##x##TimerCtrl.startrunflag = 0; /* رб־ */ \
+ if (g_moto##x##TimerCtrl.ExecWhenStop != NULL) \
+ { \
+ g_moto##x##TimerCtrl.ExecWhenStop(); \
+ } \
+ } \
+ } \
+ else \
+ { \
+ LL_TIM_SetAutoReload(MOTO##x##_TIM, (u16)((MOTO_FIN/g_moto##x##TimerCtrl.currentSpd)/2)); /* üֵ */ \
+ \
+ if (g_moto##x##TimerCtrl.pulseState == 0) \
+ { \
+ g_moto##x##TimerCtrl.pulseState = 1; \
+ g_moto##x##TimerCtrl.currentPos++; /* ֵ */ \
+ g_moto##x##TimerCtrl.realpos += g_moto##x##TimerCtrl.dir; \
+ \
+ if (g_moto##x##TimerCtrl.pulseMode == MODE_CWCCW) /* */ \
+ { \
+ if (g_moto##x##TimerCtrl.dir == 1) \
+ { \
+ SetMotoPulseOn(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOn(); */\
+ } \
+ else \
+ { \
+ SetMotoSignOn(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOn(); */\
+ } \
+ } \
+ else \
+ { \
+ SetMotoPulseOn(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOn(); */\
+ } \
+ } \
+ else \
+ { \
+ g_moto##x##TimerCtrl.pulseState = 0; \
+ if (g_moto##x##TimerCtrl.pulseMode == MODE_CWCCW) \
+ { \
+ SetMotoPulseOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOff();*/ \
+ SetMotoSignOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOff();*/ \
+ } \
+ else \
+ { \
+ SetMotoPulseOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOff();*/ \
+ } \
+ } \
+ \
+ /* */ \
+ if (g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) \
+ { \
+ if (g_moto##x##TimerCtrl.currentPos >= (g_moto##x##TimerCtrl.totalPos>>1)) \
+ {/* ǰλƴλƵһ,뽵״̬ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_DEC; \
+ g_moto##x##TimerCtrl.decPos = g_moto##x##TimerCtrl.currentPos; /* ٵλ */ \
+ /*printf("enter dec, spd=%d, pos=%d\r\n", g_moto##x##TimerCtrl.currentSpd, g_moto##x##TimerCtrl.decPos);*/ \
+ } \
+ } \
+ \
+ /* */ \
+ if (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) \
+ { \
+ if (g_moto##x##TimerCtrl.currentPos >= g_moto##x##TimerCtrl.decPos) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_DEC; \
+ g_moto##x##TimerCtrl.currentAcc = g_moto##x##TimerCtrl.addPPSG; /* ǰٶ */ \
+ } \
+ } \
+ } \
+ } \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣٶȿ */ \
+/* ٶȿжӦ */ \
+void STM32Moto##x##Speed (void) \
+{ \
+ /* ֹͣ */ \
+ if (g_moto##x##TimerCtrl.runState <= STM32MOTO_STOP || g_moto##x##TimerCtrl.startrunflag == 0) \
+ { \
+ return; \
+ } \
+ if ((g_moto##x##TimerCtrl.blockRunflag == 0) && (g_moto##x##TimerCtrl.funTestTime != 0)) /* б־ */ \
+ { \
+ g_moto##x##TimerCtrl.funTestCount++; \
+ if ((g_moto##x##TimerCtrl.funTestCount >= g_moto##x##TimerCtrl.funTestTime)) \
+ { \
+ g_moto##x##TimerCtrl.funTestCount = 0; \
+ if (g_moto##x##TimerCtrl.GetNormalStop != NULL) /* һֹͣ */ \
+ { \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) || /* */ \
+ 0 ) \
+ { \
+ if (g_moto##x##TimerCtrl.GetNormalStop(g_moto##x##TimerCtrl.condPara1, g_moto##x##TimerCtrl.condPara2) != 0) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_NSTOP; /* ͣ */ \
+ } \
+ } \
+ } \
+ /* жϿֹͣ */ \
+ if (g_moto##x##TimerCtrl.GetQuickStop != NULL) /* ֹͣ */ \
+ { \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_NSTOP) || /* ͣ */ \
+ 0 ) \
+ { \
+ if (g_moto##x##TimerCtrl.GetQuickStop(g_moto##x##TimerCtrl.condPara1, g_moto##x##TimerCtrl.condPara2) != 0) \
+ { \
+ g_moto##x##TimerCtrl.currentAcc = g_moto##x##TimerCtrl.brkPPSG; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_EMC; /* ͣ */ \
+ } \
+ } \
+ } \
+ if (g_moto##x##TimerCtrl.ExecWhenRun != NULL) /* йִеĺ*/ \
+ { \
+ g_moto##x##TimerCtrl.ExecWhenRun(); \
+ } \
+ } \
+ } \
+ \
+ /* */ \
+ if (g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) \
+ { \
+ g_moto##x##TimerCtrl.totalAcc += g_moto##x##TimerCtrl.currentAcc; /* ۼٶ */ \
+ do\
+ {\
+ if (g_moto##x##TimerCtrl.totalAcc >= 10000)\
+ {\
+ g_moto##x##TimerCtrl.currentSpd += 1; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.totalAcc -= 10000; /* ۼٶ */ \
+ }\
+ else\
+ {\
+ break;\
+ }\
+ }while(1);\
+ if (g_moto##x##TimerCtrl.currentSpd >= (s32)g_moto##x##TimerCtrl.runPPS) \
+ {/* ǰٶȴٶ,״̬ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_RUN; \
+ g_moto##x##TimerCtrl.currentSpd = g_moto##x##TimerCtrl.runPPS; \
+ g_moto##x##TimerCtrl.decPos = (g_moto##x##TimerCtrl.totalPos - g_moto##x##TimerCtrl.currentPos); /* ٵλ */ \
+ /*printf("enter run, spd=%d, decpos=%d\r\n", g_moto##x##TimerCtrl.currentSpd, g_moto##x##TimerCtrl.decPos);*/ \
+ } \
+ } \
+ \
+ /* */ \
+ if (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) /* */ \
+ { \
+ g_moto##x##TimerCtrl.totalAcc -= g_moto##x##TimerCtrl.currentAcc; /* ۼٶ */ \
+ do\
+ {\
+ if ((g_moto##x##TimerCtrl.totalAcc < 0) && (g_moto##x##TimerCtrl.currentSpd > 0))\
+ {\
+ g_moto##x##TimerCtrl.currentSpd -= 1; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.totalAcc += 10000; /* ۼٶ */ \
+ }\
+ else\
+ {\
+ break;\
+ }\
+ }while(1);\
+ if (g_moto##x##TimerCtrl.currentSpd <= (s32)g_moto##x##TimerCtrl.startPPS) \
+ { \
+ g_moto##x##TimerCtrl.currentSpd = g_moto##x##TimerCtrl.startPPS; \
+ } \
+ } \
+ \
+ /* ͣ */ \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_NSTOP) || /* ͣ */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_EMC) || /* ɲ */ \
+ 0) \
+ { \
+ g_moto##x##TimerCtrl.totalAcc -= g_moto##x##TimerCtrl.currentAcc; /* ۼٶ */ \
+ do\
+ {\
+ if ((g_moto##x##TimerCtrl.totalAcc < 0) && (g_moto##x##TimerCtrl.currentSpd > 0))\
+ {\
+ g_moto##x##TimerCtrl.currentSpd -= 1; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.totalAcc += 10000; /* ۼٶ */ \
+ }\
+ else\
+ {\
+ break;\
+ }\
+ }while(1);\
+ if (g_moto##x##TimerCtrl.currentSpd <= (s32)g_moto##x##TimerCtrl.startPPS) \
+ {/* ǰٶСٶ,ֹͣ״̬ */ \
+ SetMotoPulseOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOff();*/ \
+ SetMotoSignOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOff();*/ \
+ LL_TIM_DisableCounter(MOTO##x##_TIM); /* رնʱ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_STOP; /* ״̬ */ \
+ g_moto##x##TimerCtrl.startrunflag = 0; /* رб־ */ \
+ if (g_moto##x##TimerCtrl.ExecWhenStop != NULL) \
+ { \
+ g_moto##x##TimerCtrl.ExecWhenStop(); \
+ } \
+ } \
+ } \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣ */ \
+int STM32Moto##x##Start(MotoCtrl * pCtrl) \
+{ \
+ int runflag = 1;\
+ int rslt = 0;\
+ if (g_moto##x##TimerCtrl.runState <= STM32MOTO_STOP) /* ͣ/״̬ */ \
+ { \
+ if (pCtrl->movement == 0) /* */\
+ { \
+ runflag = 0;\
+ } \
+ if (pCtrl->GetNormalStop != NULL) /* һֹͣ */ \
+ {\
+ rslt = pCtrl->GetNormalStop(pCtrl->condPara1, pCtrl->condPara2); \
+ if (rslt != 0) \
+ { \
+ runflag = 0;\
+ } \
+ } \
+ if (pCtrl->GetQuickStop != NULL) /* ֹͣ */ \
+ { \
+ rslt = pCtrl->GetQuickStop(pCtrl->condPara1, pCtrl->condPara2); \
+ if (rslt != 0) \
+ { \
+ runflag = 0;\
+ } \
+ } \
+ if (runflag == 0) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_STOP; \
+ g_moto##x##TimerCtrl.startrunflag = 0; /* رб־ */ \
+ return rslt; \
+ } \
+ if (pCtrl->ExecWhenStart != NULL) /* ִ */ \
+ { \
+ pCtrl->ExecWhenStart(); \
+ } \
+ /* λ */ \
+ g_moto##x##TimerCtrl.currentPos = 0; /* ǰλ */ \
+ g_moto##x##TimerCtrl.pulseState = 0; /* ǰΪ 0 */ \
+ g_moto##x##TimerCtrl.totalPos = abs(pCtrl->movement); /* λ */ \
+ g_moto##x##TimerCtrl.decPos = g_moto##x##TimerCtrl.totalPos; /* λ */ \
+ if (pCtrl->movement > 0) \
+ {/* */ \
+ g_moto##x##TimerCtrl.dir = 1; \
+ } \
+ else \
+ { \
+ g_moto##x##TimerCtrl.dir = -1; \
+ } \
+ \
+ /* ٶ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_ADD; /* */ \
+ g_moto##x##TimerCtrl.startPPS = pCtrl->startPPS; /* ͣٶ */ \
+ g_moto##x##TimerCtrl.runPPS = pCtrl->runPPS; /* ٶ */ \
+ g_moto##x##TimerCtrl.addPPSG = pCtrl->addPPSG; /* ͣٶ */ \
+ g_moto##x##TimerCtrl.brkPPSG = pCtrl->brkPPSG; /* ɲٶ */ \
+ g_moto##x##TimerCtrl.totalAcc = 0; /* ۼӼٶ */ \
+ \
+ g_moto##x##TimerCtrl.funTestTime = pCtrl->funTestTime; /* йⲿʱ */ \
+ g_moto##x##TimerCtrl.funTestCount = 0; /* йⲿʱ */ \
+\
+ g_moto##x##TimerCtrl.syncList[0] = pCtrl->syncList[0]; /* ͬƶѡ */ \
+ g_moto##x##TimerCtrl.syncList[1] = pCtrl->syncList[1]; /* ͬƶѡ */ \
+ g_moto##x##TimerCtrl.syncList[2] = pCtrl->syncList[2]; /* ͬƶѡ */ \
+ g_moto##x##TimerCtrl.syncList[3] = pCtrl->syncList[3]; /* ͬƶѡ */ \
+ g_moto##x##TimerCtrl.syncList[4] = pCtrl->syncList[4]; /* ͬƶѡ */ \
+ g_moto##x##TimerCtrl.syncList[5] = pCtrl->syncList[5]; /* ͬƶѡ */ \
+ \
+ g_moto##x##TimerCtrl.GetNormalStop = pCtrl -> GetNormalStop; /* һֹͣ */ \
+ g_moto##x##TimerCtrl.GetQuickStop = pCtrl -> GetQuickStop; /* ֹͣ */ \
+ g_moto##x##TimerCtrl.condPara1 = pCtrl -> condPara1; /* 1 */ \
+ g_moto##x##TimerCtrl.condPara2 = pCtrl -> condPara2; /* 2 */ \
+ \
+ g_moto##x##TimerCtrl.blockRunflag = pCtrl -> blockRunflag; /* б־ */ \
+ g_moto##x##TimerCtrl.ExecWhenRun = pCtrl -> ExecWhenRun; /* йִеĺ */ \
+ g_moto##x##TimerCtrl.ExecWhenStart = pCtrl -> ExecWhenStart; /* ʱִеĺ */ \
+ g_moto##x##TimerCtrl.ExecWhenStop = pCtrl -> ExecWhenStop; /* ֹͣʱִеĺ */ \
+ \
+ /* ٶУ */ \
+ if (g_moto##x##TimerCtrl.startPPS > SPD_MAX) \
+ { \
+ g_moto##x##TimerCtrl.startPPS = SPD_MAX; \
+ } \
+ if (g_moto##x##TimerCtrl.startPPS < SPD_MIN) \
+ { \
+ g_moto##x##TimerCtrl.startPPS = SPD_MIN; \
+ } \
+ if (g_moto##x##TimerCtrl.runPPS > SPD_MAX) \
+ { \
+ g_moto##x##TimerCtrl.runPPS = SPD_MAX; \
+ } \
+ if (g_moto##x##TimerCtrl.runPPS < SPD_MIN) \
+ { \
+ g_moto##x##TimerCtrl.runPPS = SPD_MIN; \
+ } \
+ if (g_moto##x##TimerCtrl.startPPS > g_moto##x##TimerCtrl.runPPS) \
+ { \
+ g_moto##x##TimerCtrl.startPPS = g_moto##x##TimerCtrl.runPPS; \
+ } \
+ \
+ /* ٶУ */ \
+ if (g_moto##x##TimerCtrl.addPPSG > ADD_MAX) \
+ { \
+ g_moto##x##TimerCtrl.addPPSG = ADD_MAX; \
+ } \
+ if (g_moto##x##TimerCtrl.addPPSG <= ADD_MIN) \
+ { \
+ g_moto##x##TimerCtrl.addPPSG = ADD_MIN; \
+ } \
+ if (g_moto##x##TimerCtrl.brkPPSG > ADD_MAX) \
+ { \
+ g_moto##x##TimerCtrl.brkPPSG = ADD_MAX; \
+ } \
+ if (g_moto##x##TimerCtrl.brkPPSG <= ADD_MIN) \
+ { \
+ g_moto##x##TimerCtrl.brkPPSG = ADD_MIN; \
+ } \
+ g_moto##x##TimerCtrl.currentSpd = g_moto##x##TimerCtrl.startPPS; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.currentAcc = g_moto##x##TimerCtrl.addPPSG; /* ǰٶ */ \
+ \
+ /* */ \
+ SetMotoPulseOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##PulseOff();*/ \
+ if (g_moto##x##TimerCtrl.pulseMode != MODE_CWCCW) \
+ { \
+ if (g_moto##x##TimerCtrl.dir == 1) \
+ { \
+ SetMotoSignOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOff();*/ \
+ } \
+ else \
+ { \
+ SetMotoSignOn(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOn(); */\
+ } \
+ } \
+ else \
+ { \
+ SetMotoSignOff(x,g_moto##x##TimerCtrl.syncList); /*SetMoto##x##SignOff();*/ \
+ } \
+ \
+ LL_TIM_DisableIT_UPDATE(MOTO##x##_TIM); /* رж */ \
+ LL_TIM_SetAutoReload(MOTO##x##_TIM, (u16)((MOTO_FIN/g_moto##x##TimerCtrl.currentSpd)/2)); /* üֵ */ \
+ LL_TIM_EnableIT_UPDATE(MOTO##x##_TIM); /* ж */ \
+ LL_TIM_EnableCounter(MOTO##x##_TIM); /* ʱ */ \
+ g_moto##x##TimerCtrl.startrunflag = 1; /* б־ */ \
+ \
+ return STM32Moto##x##Run(pCtrl); \
+ } \
+ else \
+ { \
+ printf("moto is running, start failed\r\n"); \
+ return -1; /* */ \
+ } \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣֹͣ */ \
+void STM32Moto##x##Stop(void) \
+{ \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) || /* */ \
+ 0 ) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_NSTOP; /* 뽵ͣ״̬ */ \
+ if (g_moto##x##TimerCtrl.ExecWhenStop != NULL) \
+ { \
+ g_moto##x##TimerCtrl.ExecWhenStop(); \
+ } \
+ } \
+} \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣ */ \
+int STM32Moto##x##Run(MotoCtrl * pCtrl) \
+{ \
+ /* жһֹͣ */ \
+ do \
+ { \
+ if (pCtrl == NULL || \
+ g_moto##x##TimerCtrl.runState <= STM32MOTO_STOP) /* */ \
+ { \
+ break; \
+ } \
+ if (pCtrl->GetNormalStop != NULL) /* һֹͣ */ \
+ { \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) || /* */ \
+ 0 ) \
+ { \
+ if (pCtrl->GetNormalStop(pCtrl->condPara1, pCtrl->condPara2) != 0) \
+ { \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_NSTOP; /* ͣ */ \
+ if (g_moto##x##TimerCtrl.ExecWhenStop != NULL) \
+ { \
+ g_moto##x##TimerCtrl.ExecWhenStop(); \
+ } \
+ } \
+ } \
+ } \
+ /* жϿֹͣ */ \
+ if (pCtrl->GetQuickStop != NULL) /* ֹͣ */ \
+ { \
+ if ((g_moto##x##TimerCtrl.runState == STM32MOTO_ADD) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_RUN) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_DEC) || /* */ \
+ (g_moto##x##TimerCtrl.runState == STM32MOTO_NSTOP) || /* ͣ */ \
+ 0 ) \
+ { \
+ if (pCtrl->GetQuickStop(pCtrl->condPara1, pCtrl->condPara2) != 0) \
+ { \
+ g_moto##x##TimerCtrl.currentAcc = g_moto##x##TimerCtrl.brkPPSG; /* ǰٶ */ \
+ g_moto##x##TimerCtrl.runState = STM32MOTO_EMC; /* ͣ */ \
+ } \
+ } \
+ } \
+ if (pCtrl->ExecWhenRun != NULL) /* йִеĺ*/ \
+ { \
+ pCtrl->ExecWhenRun(); \
+ } \
+ if (pCtrl->blockRunflag == 0) /* б־ */ \
+ { \
+ break; \
+ } \
+ }while(1); \
+ return g_moto##x##TimerCtrl.runState; \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣõ״̬ */ \
+int GetSTM32Moto##x##State(void) \
+{ \
+ return g_moto##x##TimerCtrl.runState; \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣõǰ */ \
+s32 GetSTM32Moto##x##RealPos(void) \
+{ \
+ return g_moto##x##TimerCtrl.realpos; \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣõǰ */ \
+void SetSTM32Moto##x##RealPos(s32 pos) \
+{ \
+ g_moto##x##TimerCtrl.realpos = pos; \
+} \
+ \
+/*-----------------------------------------------------------------------------------*/ \
+/* ܣõģʽ */ \
+void SetSTM32Moto##x##Mode(int mode) \
+{ \
+ g_moto##x##TimerCtrl.pulseMode = mode; \
+} \
+/*-----------------------------------------------------------------------------------*/ \
+
+//----------------------------------------------------------------------
+// 궨
+
+#if (STM32_MOTOS_NUM >= 1)
+ USE_MOTO(1);
+#endif
+#if (STM32_MOTOS_NUM >= 2)
+ USE_MOTO(2);
+#endif
+#if (STM32_MOTOS_NUM >= 3)
+ USE_MOTO(3);
+#endif
+#if (STM32_MOTOS_NUM >= 4)
+ USE_MOTO(4);
+#endif
+#if (STM32_MOTOS_NUM >= 5)
+ USE_MOTO(5);
+#endif
+#if (STM32_MOTOS_NUM >= 6)
+ USE_MOTO(6);
+#endif
+
+//----------------------------------------------------------------------
+// ʼٶȿƶʱж
+void InitSTM32Speed(void)
+{
+#if (STM32_MOTOS_NUM >= 1 || STM32_SOFT_PWM > 0)
+ LL_TIM_ClearFlag_UPDATE(SPEED_TIM); // жϱ־
+ LL_TIM_EnableIT_UPDATE(SPEED_TIM); // ж
+ LL_TIM_EnableCounter(SPEED_TIM); // ʹܶʱ
+#endif
+}
+
+/*-----------------------------------------------------------------------------------*/
+// ٶȿжϴ
+void STM32MotoSpeedIntProc(void)
+{
+#if (STM32_MOTOS_NUM >= 1 || STM32_SOFT_PWM > 0)
+
+ if (LL_TIM_IsActiveFlag_UPDATE(SPEED_TIM) != RESET)
+ {
+ LL_TIM_ClearFlag_UPDATE(SPEED_TIM);
+ #if (STM32_SOFT_PWM > 0)
+ SoftPwmProc();
+ #endif
+ #if (STM32_MOTOS_NUM >= 1)
+ STM32Moto1Speed();
+ #endif
+ #if (STM32_MOTOS_NUM >= 2)
+ STM32Moto2Speed();
+ #endif
+ #if (STM32_MOTOS_NUM >= 3)
+ STM32Moto3Speed();
+ #endif
+ #if (STM32_MOTOS_NUM >= 4)
+ STM32Moto4Speed();
+ #endif
+ #if (STM32_MOTOS_NUM >= 5)
+ STM32Moto5Speed();
+ #endif
+ #if (STM32_MOTOS_NUM >= 6)
+ STM32Moto6Speed();
+ #endif
+ }
+#endif
+}
+
+//----------------------------------------------------------------------
+
+void InitSTM32SoftPwm(OutFunc pwmProc)
+{
+#if (STM32_MOTOS_NUM == 0 && STM32_SOFT_PWM != 0)
+ InitSTM32Speed();
+#endif
+ SoftPwmProc = pwmProc;
+}
+
+//----------------------------------------------------------------------
+
+void InitSTM32Motos(void)
+{
+#if (STM32_MOTOS_NUM > 0)
+ InitSTM32Speed();
+#endif
+
+#if (STM32_MOTOS_NUM >= 1)
+ InitSTM32Moto1Ctrl();
+#endif
+
+#if (STM32_MOTOS_NUM >= 2)
+ InitSTM32Moto2Ctrl();
+#endif
+
+#if (STM32_MOTOS_NUM >= 3)
+ InitSTM32Moto3Ctrl();
+#endif
+
+#if (STM32_MOTOS_NUM >= 4)
+ InitSTM32Moto4Ctrl();
+#endif
+
+#if (STM32_MOTOS_NUM >= 5)
+ InitSTM32Moto5Ctrl();
+#endif
+
+#if (STM32_MOTOS_NUM >= 6)
+ InitSTM32Moto6Ctrl();
+#endif
+
+// AddShellCmd("TMR", "test stm32 moto run", TestStm32Motos);
+}
+
+// -----------------------------------------------------------
+
+//ն˵Խӿ
+void TestStm32Motos(char * para1, char * para2)
+{
+#if (STM32_MOTOS_NUM >= 1)
+ int p1, p2;
+ MotoCtrl mtcfg; // ò
+
+ memset(&mtcfg, 0, sizeof(MotoCtrl));
+
+ if (para1 == NULL || para2 == NULL)
+ {
+ return;
+ }
+
+ printf("para1=%s, para2=%s\r\n", para1, para2);
+
+ p1 = 0;
+ p2 = 0;
+ if (strcmp(para1, "") != 0)
+ {
+ p1 = atoi(para1);
+ if (strcmp(para2, "") != 0)
+ {
+ p2 = atoi(para2);
+ }
+ }
+
+ if (p1 == 0)
+ {//ȡ״̬
+ if (p2 == 0)
+ {
+ g_moto1TimerCtrl.realpos = 0;
+ }
+ else if (p2 == 1)
+ {
+ printf("moto1pos=%ld\r\n", g_moto1TimerCtrl.realpos);
+ }
+
+ if (p2 == 100)
+ {// ״̬
+ printf("moto1 state =%d\r\n",GetSTM32Moto1State());
+ }
+ }
+
+ if (p1 == 1)
+ {//moto1
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto1Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 300;
+ mtcfg.runPPS = 1000;
+ mtcfg.addPPSG = 10;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto1Start (&mtcfg);
+ }
+ }
+#if (STM32_MOTOS_NUM >= 2)
+ if (p1 == 2)
+ {//moto2
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto2Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 300;
+ mtcfg.runPPS = 1000;
+ mtcfg.addPPSG = 10;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto2Start (&mtcfg);
+ }
+ }
+#endif
+#if (STM32_MOTOS_NUM >= 3)
+ if (p1 == 3)
+ {//moto3
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto3Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 50;
+ mtcfg.runPPS = 7000;
+ mtcfg.addPPSG = 5;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto3Start (&mtcfg);
+ }
+ }
+#endif
+#if (STM32_MOTOS_NUM >= 4)
+ if (p1 == 4)
+ {//moto4
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto4Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 50;
+ mtcfg.runPPS = 4000;
+ mtcfg.addPPSG = 5;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto4Start (&mtcfg);
+ }
+ }
+#endif
+#if (STM32_MOTOS_NUM >= 5)
+ if (p1 == 5)
+ {//moto5
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto5Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 100;
+ mtcfg.runPPS = 2000;
+ mtcfg.addPPSG = 50;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto5Start (&mtcfg);
+ }
+ }
+#endif
+#if (STM32_MOTOS_NUM >= 6)
+ if (p1 == 6)
+ {//moto5
+ if (p2 == 0)
+ {// ֹͣ
+ STM32Moto6Stop();
+ }
+ else
+ {
+ mtcfg.movement = p2; // λ
+ mtcfg.startPPS = 100;
+ mtcfg.runPPS = 2000;
+ mtcfg.addPPSG = 50;
+ mtcfg.brkPPSG = 50;
+ mtcfg.GetNormalStop = NULL;
+ mtcfg.GetQuickStop = NULL;
+ mtcfg.condPara1 = 0;
+ mtcfg.condPara2 = 0;
+ STM32Moto6Start (&mtcfg);
+ }
+ }
+
+#endif
+
+#endif
+
+}
+
diff --git a/NxFuncs/stm32motos/stm32motos.h b/NxFuncs/stm32motos/stm32motos.h
new file mode 100644
index 0000000..0d6645f
--- /dev/null
+++ b/NxFuncs/stm32motos/stm32motos.h
@@ -0,0 +1,140 @@
+
+//-------------------------------------------------------------------------------
+// ʵ6·첽˶
+//-------------------------------------------------------------------------------
+
+#ifndef __STM32MOTOS_H__
+#define __STM32MOTOS_H__
+
+#include "config.h"
+
+//-------------------------------------------------------------------------------
+// ʵ6·첽˶
+// ʵֵԶ -- ˶
+
+#ifndef STM32_MOTOS_NUM
+#define STM32_MOTOS_NUM 0 //
+#endif
+
+//---------------------------------------------------------------
+// PWMź
+#ifndef STM32_SOFT_PWM
+#define STM32_SOFT_PWM 0
+#endif
+
+//-------------------------------------------------------------------------------
+
+// ģʽ
+#define MODE_CWCCW 0
+#define MODE_STEPDIR 1
+
+//---------------------------------------------------------------
+// ˶״̬
+#define STM32MOTO_ERR -1 // 쳣
+#define STM32MOTO_STOP 0 // ֹͣ
+#define STM32MOTO_ADD 1 //
+#define STM32MOTO_RUN 2 //
+#define STM32MOTO_DEC 3 // ()
+#define STM32MOTO_NSTOP 4 // ͣ(ͣ)
+#define STM32MOTO_EMC 5 // ɲ(ɲ)
+
+//---------------------------------------------------------------
+// ˶ƽӿ
+typedef struct
+{
+ //
+ s32 movement; // λ
+
+ u32 startPPS; // ٶ
+ u32 runPPS; // ˶ٶ
+ u32 addPPSG; // ͣٶ
+ u32 brkPPSG; // ɲٶ
+
+ u32 funTestTime; // йⲿʱ 0:ⲿ (λ:0.1ms)
+ int syncList[6]; // ͬƶѡ
+
+ // ָ
+ int (*GetNormalStop)(u32,u32); // һֹͣΪʱֹͣ; Ϊʱ㣬ٵֹͣͣٶȽ٣
+ int (*GetQuickStop)(u32,u32); // ֹͣΪʱֹͣ; Ϊʱ㣬ٵֹͣɲٶȽ٣
+ u32 condPara1, condPara2; //
+
+ int blockRunflag; // б־, =1,ͬ˶ =0,,첽˶
+ void (*ExecWhenRun)(void); // йִеĺ
+ void (*ExecWhenStart)(void); // ʱִеĺ
+ void (*ExecWhenStop)(void); // ֹͣʱִеĺ
+
+}MotoCtrl;
+
+//---------------------------------------------------------------
+
+typedef void (*OutFunc)(void);
+
+
+#define MOTO_FUNC_DEF(x) \
+\
+void InitStm32Moto##x##OutFunc(OutFunc stepOn, OutFunc StepOff, OutFunc dirOn, OutFunc dirOff); /* ܣõ */ \
+int STM32Moto##x##Start(MotoCtrl * pCtrl); /* ܣ */ \
+void STM32Moto##x##Stop (void); /* ܣֹͣʱõ */ \
+int STM32Moto##x##Run(MotoCtrl * pCtrl); /* ܣУʱõ */ \
+int GetSTM32Moto##x##State(void); /* ܣõ״̬ʱõ */ \
+void SetSTM32Moto##x##Mode(int mode); /* ܣ巽ʽ */ \
+void SetSTM32Moto##x##RunSpd(u32 spd); /* ܣõתٶ(ʱõ) */ \
+s32 GetSTM32Moto##x##RealPos(void); /* ܣõǰ꣨ʱõ */ \
+void SetSTM32Moto##x##RealPos(s32 pos); /* ܣõǰ꣨ʱõ */ \
+void STM32Moto##x##IntProc(void); /* ܣжϴ */ \
+//-------------------------------
+
+
+//---------------------------------------------------------------
+// ʼ
+void InitSTM32Motos(void);
+void InitSTM32SoftPwm(OutFunc pwmProc);
+
+
+//-------------------------------
+#if (STM32_MOTOS_NUM > 0 || STM32_SOFT_PWM > 0)
+void STM32MotoSpeedIntProc(void); /* ܣжϴ */
+#endif
+
+// MOTO1
+#if (STM32_MOTOS_NUM >= 1)
+MOTO_FUNC_DEF(1);
+#endif
+
+// MOTO2
+#if (STM32_MOTOS_NUM >= 2)
+MOTO_FUNC_DEF(2);
+#endif
+
+// MOTO3
+#if (STM32_MOTOS_NUM >= 3)
+MOTO_FUNC_DEF(3);
+#endif
+
+// MOTO4
+#if (STM32_MOTOS_NUM >= 4)
+MOTO_FUNC_DEF(4);
+#endif
+
+// MOTO5
+#if (STM32_MOTOS_NUM >= 5)
+MOTO_FUNC_DEF(5);
+#endif
+
+// MOTO6
+#if (STM32_MOTOS_NUM >= 6)
+MOTO_FUNC_DEF(6);
+#endif
+
+//---------------------------------------------------------------
+
+
+
+//---------------------------------------------------------------
+
+#endif
+
+
+
+
+
diff --git a/NxFuncs/stpara/stparas.c b/NxFuncs/stpara/stparas.c
new file mode 100644
index 0000000..2093b7c
--- /dev/null
+++ b/NxFuncs/stpara/stparas.c
@@ -0,0 +1,27 @@
+
+//-------------------------------------------------------------------------------
+// File Name: stparas.c
+// Brief:
+// Version: 1.0.0
+// Create Date: 2019/06/25
+// Create by: Marshal Lee
+// Copyright:
+// Copyright (c) 2019, GetonAgain Co., LTD.
+// All rights reserved.
+//
+// Modify by: Marshal Lee
+// Modify Date: 2019/06/25
+//-------------------------------------------------------------------------------
+
+
+#define _IN_STPARAS_C
+#include "stparas.h"
+
+//----------------------------------------------------------
+
+//----------------------------------------------------------
+
+//----------------------------------------------------------
+
+//----------------------------------------------------------
+
diff --git a/NxFuncs/stpara/stparas.h b/NxFuncs/stpara/stparas.h
new file mode 100644
index 0000000..5ae2929
--- /dev/null
+++ b/NxFuncs/stpara/stparas.h
@@ -0,0 +1,286 @@
+
+//-------------------------------------------------------------------------------
+// File Name: stparas.h
+// Brief:
+// Version: 1.0.0
+// Create Date: 2017/05/08
+// Create by: Marshal Lee
+// Copyright:
+// Copyright (c) 2017, GetonAgain Co., LTD.
+// All rights reserved.
+//
+// Modify by: Marshal Lee
+// Modify Date: 2017/05/08
+
+// Modify by: ljs
+// Modify Date: 2021/12/23
+//-------------------------------------------------------------------------------
+
+#ifndef __STPARAS_H__
+#define __STPARAS_H__
+
+#include "config.h"
+#include "stflash.h"
+
+//---------------------------------
+
+#ifndef MAX_PARA_NUM
+#define MAX_PARA_NUM 32
+#endif
+
+#define PARA_NUM (MAX_PARA_NUM-1)
+
+#define PARA_STR_LEN 20
+
+#define PARA_VALID 0x55AA
+
+//
+#define PTYPE_U 0 //
+#define PTYPE_S 1 // з
+#define PTYPE_B 2 // λͼ
+
+//---------------------------------
+
+typedef struct
+{
+ u32 paraEn; // 20211223 ӲЧ־,ڲЧʱԶдĬϲ
+ u32 buf[PARA_NUM];
+} __attribute__ ((packed)) StParaStruct;
+
+//---------------------------------
+
+#define STPARA_ADDR (STM32_PARA_ADDR+0)
+
+//------------------------------------
+
+#define ST_PARAS_CODE(staddr, name) \
+\
+StParaStruct g_##name##Para;\
+u32 * g_p##name##ParaList = NULL;\
+char * g_p##name##ParasName = NULL;\
+\
+int Read##name##ParaData(void)\
+{\
+ int rslt;\
+ u32 rdaddr = (u32)(&g_##name##Para);\
+ rslt = STMFlashRead((u32)(staddr), (u16*)(rdaddr), (sizeof(StParaStruct))/2);\
+ return rslt;\
+}\
+\
+void Write##name##ParaData(void)\
+{\
+ u32 wraddr = (u32)(&g_##name##Para);\
+ STMFlashWrite((u32)(staddr), (u16*)(wraddr), (sizeof(StParaStruct))/2, 3);\
+}\
+\
+void Save##name##Para(void)\
+{\
+ printf("save %s para\r\n", #name);\
+ Write##name##ParaData();\
+}\
+\
+void Set##name##ParaList(void* pDat)\
+{\
+ g_p##name##ParaList = pDat;\
+}\
+\
+void WriteDef##name##Para(void)\
+{\
+ printf("write def %s para\r\n", #name);\
+ if (g_p##name##ParaList != NULL)\
+ {\
+ int offset;\
+ for (int i = 0; i < PARA_NUM; i++)\
+ {\
+ offset = i * 4 + 3;\
+ g_##name##Para.buf[i] = *(g_p##name##ParaList + offset);\
+ }\
+ g_##name##Para.paraEn = PARA_VALID+CUR_MACHINE;\
+ Save##name##Para();\
+ }\
+ else\
+ {\
+ printf("%s para list is NULL\r\n", #name);\
+ }\
+}\
+\
+void Set##name##ParaNameString(void* pDat)\
+{\
+ g_p##name##ParasName = pDat;\
+}\
+\
+void Load##name##Para(void)\
+{\
+ int rslt;\
+ rslt = Read##name##ParaData();\
+ if (rslt != 0 || g_##name##Para.paraEn != (PARA_VALID+CUR_MACHINE))\
+ {\
+ printf("%s para invalid, rslt=%d, paraEn=0x%x\r\n", #name, rslt, g_##name##Para.paraEn);\
+ WriteDef##name##Para();\
+ }\
+ else\
+ {\
+ printf("load %s para successful\r\n", #name);\
+ }\
+}\
+\
+void CheckA##name##ParaRange(int id)\
+{\
+ if (id <= 0 || id > PARA_NUM || g_p##name##ParaList == NULL)\
+ {\
+ return;\
+ }\
+ int paratype, minOffset, maxOffset;\
+ int idx = id - 1;\
+ paratype = (idx * 4);\
+ minOffset = (idx * 4 + 1);\
+ maxOffset = (idx * 4 + 2);\
+ if (*(g_p##name##ParaList+paratype) == PTYPE_U)\
+ {\
+ if (g_##name##Para.buf[idx] < *(g_p##name##ParaList+minOffset))\
+ {\
+ printf(#name " para id=%d, val=%d less than min=%d, set to min\r\n", id, g_##name##Para.buf[idx], *(g_p##name##ParaList+minOffset));\
+ g_##name##Para.buf[idx] = *(g_p##name##ParaList+minOffset);\
+ }\
+ else if (g_##name##Para.buf[idx] > *(g_p##name##ParaList+maxOffset))\
+ {\
+ printf(#name " para id=%d, val=%d more than max=%d, set to max\r\n", id, g_##name##Para.buf[idx], *(g_p##name##ParaList+maxOffset));\
+ g_##name##Para.buf[idx] = *(g_p##name##ParaList+maxOffset);\
+ }\
+ }\
+ else if (*(g_p##name##ParaList+paratype) == PTYPE_S)\
+ {\
+ if ((s32)g_##name##Para.buf[idx] < (s32)*(g_p##name##ParaList+minOffset))\
+ {\
+ printf(#name " para id=%d, val=%d less than min=%d, set to min\r\n", id, (s32)g_##name##Para.buf[idx], (s32)*(g_p##name##ParaList+minOffset));\
+ g_##name##Para.buf[idx] = *(g_p##name##ParaList+minOffset);\
+ }\
+ else if ((s32)g_##name##Para.buf[idx] > (s32)*(g_p##name##ParaList+maxOffset))\
+ {\
+ printf(#name " para id=%d, val=%d more than max=%d, set to max\r\n", id, (s32)g_##name##Para.buf[idx], (s32)*(g_p##name##ParaList+maxOffset));\
+ g_##name##Para.buf[idx] = *(g_p##name##ParaList+maxOffset);\
+ }\
+ }\
+}\
+void Check##name##ParasRange(void)\
+{\
+ for(int i = 1; i <= PARA_NUM; i++)\
+ {\
+ CheckA##name##ParaRange(i);\
+ }\
+}\
+void SetA##name##Para(int id, int val)\
+{\
+ if (id < 1 || id > PARA_NUM)\
+ {\
+ return;\
+ }\
+ int old;\
+ old = (int)g_##name##Para.buf[id-1];\
+ g_##name##Para.buf[id-1] = val;\
+ if (g_p##name##ParasName != NULL)\
+ {\
+ printf("set a para %d. %s = %d, oldvalue=%d\r\n", id, (g_p##name##ParasName+(id-1)*PARA_STR_LEN), g_##name##Para.buf[id-1], old);\
+ }\
+ else\
+ {\
+ printf("set a para %d. = %d, oldvalue=%d\r\n", id, g_##name##Para.buf[id-1], old);\
+ }\
+ CheckA##name##ParaRange(id);\
+}\
+\
+void Show##name##Para(char * para1, char * para2)\
+{\
+ int i;\
+ int paratype;\
+\
+ printf(#name " para:\r\n");\
+\
+ if (g_p##name##ParasName != NULL)\
+ {\
+ for (i = 0; i < PARA_NUM; i++)\
+ {\
+ if (strlen(g_p##name##ParasName+i*PARA_STR_LEN) != 0)\
+ {\
+ paratype = (i * 4);\
+ if (*(g_p##name##ParaList+paratype) == PTYPE_U)\
+ {\
+ printf("%d. %s = %d\r\n", i+1, (g_p##name##ParasName+i*PARA_STR_LEN), g_##name##Para.buf[i]);\
+ DelayMs(2);\
+ }\
+ else if (*(g_p##name##ParaList+paratype) == PTYPE_S)\
+ {\
+ printf("%d. %s = %d\r\n", i+1, (g_p##name##ParasName+i*PARA_STR_LEN), (s32)g_##name##Para.buf[i]);\
+ DelayMs(2);\
+ }\
+ else if (*(g_p##name##ParaList+paratype) == PTYPE_B)\
+ {\
+ printf("%d. %s = 0x%x\r\n", i+1, (g_p##name##ParasName+i*PARA_STR_LEN), g_##name##Para.buf[i]);\
+ DelayMs(2);\
+ }\
+ }\
+ }\
+ }\
+}\
+\
+void Set##name##Para(char * para1, char * para2)\
+{\
+ int p1, p2;\
+\
+ if (para1 == NULL || para2 == NULL)\
+ {\
+ return;\
+ }\
+\
+ if (strcmp(para1, "") == 0 || strcmp(para2, "") == 0)\
+ {\
+ return;\
+ }\
+ p1 = atoi(para1);\
+ p2 = atoi(para2);\
+\
+ if (p1 == 0 && p2 == 0)\
+ {\
+ WriteDef##name##Para();\
+ }\
+ else if (p1 <= PARA_NUM && p1 >= 1)\
+ {\
+ SetA##name##Para(p1, p2);\
+ }\
+ else if (p1 == 1000)\
+ {\
+ Save##name##Para();\
+ }\
+ else\
+ {\
+ }\
+}\
+void Init##name##Paras(void)\
+{\
+ Set##name##ParaList((void*)(&g_def##name##ParaList));\
+\
+ Load##name##Para();\
+\
+ Set##name##ParaNameString((void*)(&g_##name##ParaStrList[0][0]));\
+\
+ Check##name##ParasRange();\
+\
+ AddShellCmd("SHOW"#name"PARA", "show "#name" paras", Show##name##Para);\
+ AddShellCmd("SET"#name"PARA", "set "#name" paras", Set##name##Para);\
+}\
+//----------------------
+
+
+
+
+
+//---------------------------------
+
+
+
+//---------------------------------
+
+
+#endif
+
+
diff --git a/NxFuncs/transdata/transdata.c b/NxFuncs/transdata/transdata.c
new file mode 100644
index 0000000..0ad4841
--- /dev/null
+++ b/NxFuncs/transdata/transdata.c
@@ -0,0 +1,232 @@
+
+#define _IN_TRANSDATA_C
+
+#include "transdata.h"
+
+#if (TRANS_APP_FILE == 1 || TRANS_DATA_FILE == 1)
+
+#include "comm.h"
+#include "canctrl.h"
+#include "crc16.h"
+
+void InitFileTransCtrl(FileTransCtrl * pfileTransCtrl)
+{
+ //printf("InitFileTransCtrl\r\n");
+ memset(pfileTransCtrl, 0, sizeof(FileTransCtrl));
+}
+
+int WriteRsvBitmap(u32 idx, u8 sta, FileTransCtrl * pfileTransCtrl)
+{
+ u8 mod;
+ u32 baddr, yus;
+
+ if (idx >= LEN_RSV_BMP*8)
+ {
+ printf("error in WriteRsvBitmap idx=%d, packetNum=%d\r\n", idx, pfileTransCtrl->packetNum);
+ return -1;
+ }
+
+ baddr = (idx)/8;
+ if (baddr >= LEN_RSV_BMP)
+ {
+ printf("error in WriteRsvBitmap baddr=%d, lenBmp=%d\r\n",baddr, pfileTransCtrl->lenBmp);
+ return -1;
+ }
+
+ yus = idx%8;
+ mod = 0x01;
+ while (yus != 0)
+ {
+ yus--;
+ mod <<= 1;
+ }
+
+ if (sta == 0)
+ {
+ pfileTransCtrl->rsvBitmap[baddr] &= ~mod;
+ }
+ else
+ {
+ pfileTransCtrl->rsvBitmap[baddr] |= mod;
+ }
+ return 0;
+}
+
+int IsResvFinish(FileTransCtrl * pfileTransCtrl)
+{
+ u8 mod;
+ u32 zss, yus;
+ u32 i;
+
+ zss = (pfileTransCtrl->packetNum)/8;
+ yus = pfileTransCtrl->packetNum%8;
+
+ for (i = 0; i < zss; i++)
+ {
+ if (pfileTransCtrl->rsvBitmap[i] != 0xff)
+ {
+ return FALSE;
+ }
+ }
+
+ mod = 0x01;
+ for (i = 0; i < yus; i++)
+ {
+ if ((pfileTransCtrl->rsvBitmap[zss] & mod) == 0)
+ {
+ return FALSE;
+ }
+ mod <<= 1;
+ }
+
+ return TRUE;
+}
+
+/*
+ * ݴ䴦
+ *return: 0:
+ *
+ */
+int TransDataProc(BoardFileCanCtrl filecan, FileTransCtrl * pfileTransCtrl, u8 nodetype)
+{
+ if (filecan.head.sync[0] == CDP_SYNC[0] &&
+ filecan.head.sync[1] == CDP_SYNC[1] &&
+ filecan.head.sync[2] == CDP_SYNC[2] &&
+ 1) // ݰͷ
+ {
+ //printf("get a packet head,id=%d\r\n", filecan.head.pktId);
+ if (filecan.head.pktId == FILE_HEAD_ID) // ļ
+ {
+ printf("start receive file\r\n");
+ InitFileTransCtrl(pfileTransCtrl);
+ pfileTransCtrl->pBoardFile = &g_boardFile;
+ pfileTransCtrl->transActive = TRANS_ACTIVE;
+ pfileTransCtrl->transflag = TRANS_READY;
+ pfileTransCtrl->rsvPktCount = 0;
+ }
+ // ¼ǰյݰID,֡,crcУ
+ pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId = filecan.head.pktId;
+ pfileTransCtrl->pBoardFile->filepkt.pktHead.head.fnum = filecan.head.fnum;
+ pfileTransCtrl->pBoardFile->filepkt.pktHead.head.crc = filecan.head.crc;
+ pfileTransCtrl->rsvFrameCount = 0;
+ }
+ else //
+ {
+ //printf("get a packet data\r\n");
+ if (pfileTransCtrl->transActive != TRANS_ACTIVE)
+ {
+ //printf("TransDataProc file not active\r\n");
+ return -1;
+ }
+
+ if (pfileTransCtrl->transflag != TRANS_READY &&
+ pfileTransCtrl->transflag != TRANS_DOING &&
+ 1 )
+ {
+ //printf("TransDataProc file not ready\r\n");
+ return -2;
+ }
+
+ if (pfileTransCtrl->transflag == TRANS_READY)
+ {
+ pfileTransCtrl->transflag = TRANS_DOING;
+ }
+
+ // ݿ
+ memcpy(&pfileTransCtrl->pBoardFile->filepkt.pktData[pfileTransCtrl->rsvFrameCount].data, &filecan.data, CAN_DATA_LEN);
+ pfileTransCtrl->rsvFrameCount++;
+
+ // жݰǷ
+ if (pfileTransCtrl->rsvFrameCount == pfileTransCtrl->pBoardFile->filepkt.pktHead.head.fnum)
+ {// ,У
+ //printf("a packet receive over\r\n");
+ u16 crc = CalcCrc16((u8*)&pfileTransCtrl->pBoardFile->filepkt.pktData, pfileTransCtrl->pBoardFile->filepkt.pktHead.head.fnum*CAN_DATA_LEN);
+ if (crc == pfileTransCtrl->pBoardFile->filepkt.pktHead.head.crc)
+ {// Уȷ
+ if (pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId == FILE_HEAD_ID)
+ {// ļݰ,ļͷ
+ printf("receive start over\r\n");
+ memcpy(&pfileTransCtrl->pBoardFile->fileHead, &pfileTransCtrl->pBoardFile->filepkt.pktData, 6*CAN_DATA_LEN);// 6Ϊļͷ֡
+ if (pfileTransCtrl->pBoardFile->fileHead.nodeType != nodetype)
+ {
+ printf("send to nodetype=0x%x\r\n", pfileTransCtrl->pBoardFile->fileHead.nodeType);
+ pfileTransCtrl->transActive = TRANS_NONE;
+ pfileTransCtrl->transflag = TRANS_NOT_BEG;
+ return -3;
+ }
+ pfileTransCtrl->packetNum = ((pfileTransCtrl->pBoardFile->fileHead.dataSize+1024-1)/1024);
+ pfileTransCtrl->lenBmp = (pfileTransCtrl->packetNum+CAN_DATA_LEN-1)/CAN_DATA_LEN;
+
+ printf("now dataChecksum=%d, receive:dataSize=%d, dataChecksum=0x%x\r\n",
+ pfileTransCtrl->dataChecksum,
+ pfileTransCtrl->pBoardFile->fileHead.dataSize,
+ pfileTransCtrl->pBoardFile->fileHead.dataChecksum);
+
+ if (pfileTransCtrl->pBoardFile->fileHead.fileType == FILE_TYPE_PGM)
+ {
+ InitSaveApp(); // Ҫһʱ
+ }
+ }
+ else
+ {
+ pfileTransCtrl->dataChecksum += CalcCheckSum((u8*)&pfileTransCtrl->pBoardFile->filepkt.pktData, 128*CAN_DATA_LEN);// 128CAN֡
+ if (pfileTransCtrl->pBoardFile->fileHead.fileType == FILE_TYPE_PGM)
+ {// ļ,norflash,дλͼ
+ int rst, idx;
+ u32 ofst;
+ idx = (pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId == 0 ? 0:1);
+ if (pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId == 0)
+ {
+ ofst = 0;
+ }
+ else
+ {
+ ofst = (pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId-1)*pfileTransCtrl->pBoardFile->filepkt.pktHead.head.fnum*CAN_DATA_LEN;
+ }
+ rst = SaveAppData(idx,
+ (u8*)&pfileTransCtrl->pBoardFile->filepkt.pktData,
+ pfileTransCtrl->pBoardFile->filepkt.pktHead.head.fnum*CAN_DATA_LEN,
+ ofst);
+ if (rst >= 0)
+ {
+ pfileTransCtrl->rsvPktCount++;
+ WriteRsvBitmap(pfileTransCtrl->pBoardFile->filepkt.pktHead.head.pktId, 1, pfileTransCtrl);
+ }
+ else
+ {
+ printf("TransDataProc WriteFileApp error rst= %d \r\n", rst);
+ }
+ }
+ }
+ // 鿴λͼǷ
+ if ((IsResvFinish(pfileTransCtrl) == TRUE) && (pfileTransCtrl->rsvPktCount == pfileTransCtrl->packetNum))
+ {
+ //if (pfileTransCtrl->dataChecksum == pfileTransCtrl->pBoardFile->fileHead.dataChecksum)
+ if (1)
+ {
+ pfileTransCtrl->transflag = TRANS_DONE; //
+ printf("TransDataProc Receive file finish\r\n");
+ }
+ else
+ {
+ printf("TransDataProc dataChecksum error, calc=0x%x, send=0x%x\r\n",
+ pfileTransCtrl->dataChecksum, pfileTransCtrl->pBoardFile->fileHead.dataChecksum);
+ }
+ }
+ }
+ else
+ {
+ printf("TransDataProc check crc error\r\n");
+ }
+ }
+ }
+ return 0;
+}
+
+int GetLenBmp(FileTransCtrl * pfileTransCtrl)
+{
+ return pfileTransCtrl->lenBmp;
+}
+
+
+#endif
diff --git a/NxFuncs/transdata/transdata.h b/NxFuncs/transdata/transdata.h
new file mode 100644
index 0000000..6e7ad20
--- /dev/null
+++ b/NxFuncs/transdata/transdata.h
@@ -0,0 +1,171 @@
+
+
+#ifndef _TRANSDATA_H_
+#define _TRANSDATA_H_
+
+#include "config.h"
+
+#if (TRANS_APP_FILE == 1)
+#include "stapp.h"
+#endif
+
+
+#if (TRANS_DATA_FILE == 1)
+#include "datafile.h"
+#endif
+
+#define LEN_RSV_BMP 1024 // λͼ
+
+#define FILE_HEAD_ID 0xFFFF // ΧļݰID
+
+#define TRANS_NONE 0x00
+#define TRANS_ACTIVE 0x5A
+
+#define TRANS_NOT_BEG 0x00 // ûյ
+#define TRANS_READY 0x01 //
+#define TRANS_DOING 0x02 // ڽ
+#define TRANS_DONE 0x03 //
+#define TRANS_REQUEST 0x04 // ģʽ
+
+#define FILE_TYPE_DAT 0x00 // ļ
+#define FILE_TYPE_PGM 0x02 // ļ
+#define FILE_TYPE_BOARD 0x03 // Χļ
+#define FILE_TYPE_FRAME 0x04 // ߿͵ļ(ҪڹɺԶлԭļ,ҲҪλ·ļ)
+
+// Χļͷ
+typedef struct
+{
+// 0x00
+ char fileName[32]; // ļ
+// 0x20
+ u32 dataSize; // ֽ
+ u32 dataChecksum; // ۼУ
+
+ u8 protocol; // ļҪЭ
+ u8 nodeid; // ļҪĽڵID,0Ϊ㲥
+ u8 fileType; // ļ
+ u8 nodeType; // 20220608 ļҪĽڵ
+
+// 0x2C
+ u8 reserved1[0x30-0x2C]; // 1
+
+// 0x30
+ u8 reserved2[0x64-0x30]; // 2
+
+// 0x64
+ u8 reserved3[0x80-0x64]; // 3
+
+// 0x80
+ u8 reserved4[0x100-0x80]; // 4
+}__attribute__ ((packed)) BoardFileHead;
+
+// ΧļCAN֡ƽṹ
+typedef union
+{
+ u8 data[8];
+
+ struct
+ {
+ u8 sync[3];
+ u16 pktId; // ID
+ u8 fnum; // ֡
+ u16 crc;
+ } __attribute__ ((packed)) head;
+
+ struct
+ {
+ u32 datasize; // ֽ
+ u32 dataChecksum; // ۼУ
+ } __attribute__ ((packed)) check;
+
+ struct
+ {
+ u8 protocol; // ļҪЭ
+ u8 nodeid; // ļҪĽڵID,0Ϊ㲥
+ u8 fileType; // ļ
+ u8 nodeType; // ļҪĽڵ
+
+ u8 rev[4];
+ } __attribute__ ((packed)) info;
+
+}BoardFileCanCtrl;
+
+// Χļݰƽṹ
+// һݰ129CAN֡
+typedef struct
+{
+ BoardFileCanCtrl pktHead;
+ BoardFileCanCtrl pktData[128];
+
+}BoardFilePacketCtrl;
+
+// Χļƽṹ
+typedef struct
+{
+ BoardFileHead fileHead; // ļͷ
+ BoardFilePacketCtrl filepkt; // յݰ
+
+}BoardFileCtrl;
+
+// ݽտ
+typedef struct
+{
+ u8 transActive; // ṹЧ
+ u8 transflag; // սȱ־ = 0, δʼ; = 1, ڽ; = 2
+
+ //---------------ļ--------------------
+ u8 fileType; // ļ
+ u8 fileIdx; // Ϊļţ֧16ļ
+ u16 fileId; // ļID
+
+#if (TRANS_DATA_FILE == 1)
+ DatFileCtrl * pDatFile;
+#endif
+
+#if (TRANS_APP_FILE == 1)
+ AppFileCtrl * pAppFile;
+#endif
+ //---------------ļ--------------------
+
+ //---------------Χļ--------------------
+ u16 rsvPktCount; // ݰ
+ u8 rsvFrameCount; // ֡
+ u32 dataChecksum; // ۼУ
+
+ BoardFileCtrl * pBoardFile;
+ //---------------Χļ--------------------
+
+ u32 packetNum; // ĸ
+
+ u16 lenBmp; // λͼЧ
+ u8 rsvBitmap[LEN_RSV_BMP]; // ļսȱ־λͼ
+
+} __attribute__ ((packed)) FileTransCtrl;
+
+
+#define CDPSYNC_LEN 3
+#ifdef _IN_TRANSDATA_C
+const u8 CDP_SYNC[CDPSYNC_LEN] =
+{
+ 'C','D','P',
+};
+#else
+extern const u8 CDP_SYNC[];
+#endif
+
+void InitFileTransCtrl(FileTransCtrl * pfileTransCtrl);
+
+int WriteRsvBitmap(u32 idx, u8 sta, FileTransCtrl * pfileTransCtrl);
+int IsResvFinish(FileTransCtrl * pfileTransCtrl);
+
+int TransDataProc(BoardFileCanCtrl filecan, FileTransCtrl * pfileTransCtrl, u8 nodetype); // Χļմ
+
+int GetLenBmp(FileTransCtrl * pfileTransCtrl);
+
+#ifdef _IN_TRANSDATA_C
+BoardFileCtrl g_boardFile;
+#else
+extern BoardFileCtrl g_boardFile;
+#endif
+
+#endif /* _TRANSDATA_H_ */
diff --git a/RemoteSystemsTempFiles/.project b/RemoteSystemsTempFiles/.project
new file mode 100644
index 0000000..5447a64
--- /dev/null
+++ b/RemoteSystemsTempFiles/.project
@@ -0,0 +1,12 @@
+
+