code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otgd_fs_int.h
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Endpoint interrupt's service routines prototypes.
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_INT_H
#define __USB_INT_H
/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#ifdef STM32F10X_CL
/* Interrupt Handlers functions */
uint32_t OTGD_FS_Handle_Sof_ISR(void);
uint32_t OTGD_FS_Handle_RxStatusQueueLevel_ISR(void);
uint32_t OTGD_FS_Handle_GInNakEff_ISR(void);
uint32_t OTGD_FS_Handle_GOutNakEff_ISR(void);
uint32_t OTGD_FS_Handle_EarlySuspend_ISR(void);
uint32_t OTGD_FS_Handle_USBSuspend_ISR(void);
uint32_t OTGD_FS_Handle_UsbReset_ISR(void);
uint32_t OTGD_FS_Handle_EnumDone_ISR(void);
uint32_t OTGD_FS_Handle_IsoOutDrop_ISR(void);
uint32_t OTGD_FS_Handle_EOPF_ISR(void);
uint32_t OTGD_FS_Handle_EPMismatch_ISR(void);
uint32_t OTGD_FS_Handle_InEP_ISR(void);
uint32_t OTGD_FS_Handle_OutEP_ISR(void);
uint32_t OTGD_FS_Handle_IncomplIsoIn_ISR(void);
uint32_t OTGD_FS_Handle_IncomplIsoOut_ISR(void);
uint32_t OTGD_FS_Handle_Wakeup_ISR(void);
#endif /* STM32F10X_CL */
/* External variables --------------------------------------------------------*/
#endif /* __USB_INT_H */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/inc/otgd_fs_int.h
|
C
|
asf20
| 2,489
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_regs.h
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Interface prototype functions to USB cell registers
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_REGS_H
#define __USB_REGS_H
#ifndef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
typedef enum _EP_DBUF_DIR
{
/* double buffered endpoint direction */
EP_DBUF_ERR,
EP_DBUF_OUT,
EP_DBUF_IN
}EP_DBUF_DIR;
/* endpoint buffer number */
enum EP_BUF_NUM
{
EP_NOBUF,
EP_BUF0,
EP_BUF1
};
/* Exported constants --------------------------------------------------------*/
#define RegBase (0x40005C00L) /* USB_IP Peripheral Registers base address */
#define PMAAddr (0x40006000L) /* USB_IP Packet Memory Area base address */
/******************************************************************************/
/* General registers */
/******************************************************************************/
/* Control register */
#define CNTR ((__IO unsigned *)(RegBase + 0x40))
/* Interrupt status register */
#define ISTR ((__IO unsigned *)(RegBase + 0x44))
/* Frame number register */
#define FNR ((__IO unsigned *)(RegBase + 0x48))
/* Device address register */
#define DADDR ((__IO unsigned *)(RegBase + 0x4C))
/* Buffer Table address register */
#define BTABLE ((__IO unsigned *)(RegBase + 0x50))
/******************************************************************************/
/* Endpoint registers */
/******************************************************************************/
#define EP0REG ((__IO unsigned *)(RegBase)) /* endpoint 0 register address */
/* Endpoint Addresses (w/direction) */
#define EP0_OUT ((uint8_t)0x00)
#define EP0_IN ((uint8_t)0x80)
#define EP1_OUT ((uint8_t)0x01)
#define EP1_IN ((uint8_t)0x81)
#define EP2_OUT ((uint8_t)0x02)
#define EP2_IN ((uint8_t)0x82)
#define EP3_OUT ((uint8_t)0x03)
#define EP3_IN ((uint8_t)0x83)
#define EP4_OUT ((uint8_t)0x04)
#define EP4_IN ((uint8_t)0x84)
#define EP5_OUT ((uint8_t)0x05)
#define EP5_IN ((uint8_t)0x85)
#define EP6_OUT ((uint8_t)0x06)
#define EP6_IN ((uint8_t)0x86)
#define EP7_OUT ((uint8_t)0x07)
#define EP7_IN ((uint8_t)0x87)
/* endpoints enumeration */
#define ENDP0 ((uint8_t)0)
#define ENDP1 ((uint8_t)1)
#define ENDP2 ((uint8_t)2)
#define ENDP3 ((uint8_t)3)
#define ENDP4 ((uint8_t)4)
#define ENDP5 ((uint8_t)5)
#define ENDP6 ((uint8_t)6)
#define ENDP7 ((uint8_t)7)
/******************************************************************************/
/* ISTR interrupt events */
/******************************************************************************/
#define ISTR_CTR (0x8000) /* Correct TRansfer (clear-only bit) */
#define ISTR_DOVR (0x4000) /* DMA OVeR/underrun (clear-only bit) */
#define ISTR_ERR (0x2000) /* ERRor (clear-only bit) */
#define ISTR_WKUP (0x1000) /* WaKe UP (clear-only bit) */
#define ISTR_SUSP (0x0800) /* SUSPend (clear-only bit) */
#define ISTR_RESET (0x0400) /* RESET (clear-only bit) */
#define ISTR_SOF (0x0200) /* Start Of Frame (clear-only bit) */
#define ISTR_ESOF (0x0100) /* Expected Start Of Frame (clear-only bit) */
#define ISTR_DIR (0x0010) /* DIRection of transaction (read-only bit) */
#define ISTR_EP_ID (0x000F) /* EndPoint IDentifier (read-only bit) */
#define CLR_CTR (~ISTR_CTR) /* clear Correct TRansfer bit */
#define CLR_DOVR (~ISTR_DOVR) /* clear DMA OVeR/underrun bit*/
#define CLR_ERR (~ISTR_ERR) /* clear ERRor bit */
#define CLR_WKUP (~ISTR_WKUP) /* clear WaKe UP bit */
#define CLR_SUSP (~ISTR_SUSP) /* clear SUSPend bit */
#define CLR_RESET (~ISTR_RESET) /* clear RESET bit */
#define CLR_SOF (~ISTR_SOF) /* clear Start Of Frame bit */
#define CLR_ESOF (~ISTR_ESOF) /* clear Expected Start Of Frame bit */
/******************************************************************************/
/* CNTR control register bits definitions */
/******************************************************************************/
#define CNTR_CTRM (0x8000) /* Correct TRansfer Mask */
#define CNTR_DOVRM (0x4000) /* DMA OVeR/underrun Mask */
#define CNTR_ERRM (0x2000) /* ERRor Mask */
#define CNTR_WKUPM (0x1000) /* WaKe UP Mask */
#define CNTR_SUSPM (0x0800) /* SUSPend Mask */
#define CNTR_RESETM (0x0400) /* RESET Mask */
#define CNTR_SOFM (0x0200) /* Start Of Frame Mask */
#define CNTR_ESOFM (0x0100) /* Expected Start Of Frame Mask */
#define CNTR_RESUME (0x0010) /* RESUME request */
#define CNTR_FSUSP (0x0008) /* Force SUSPend */
#define CNTR_LPMODE (0x0004) /* Low-power MODE */
#define CNTR_PDWN (0x0002) /* Power DoWN */
#define CNTR_FRES (0x0001) /* Force USB RESet */
/******************************************************************************/
/* FNR Frame Number Register bit definitions */
/******************************************************************************/
#define FNR_RXDP (0x8000) /* status of D+ data line */
#define FNR_RXDM (0x4000) /* status of D- data line */
#define FNR_LCK (0x2000) /* LoCKed */
#define FNR_LSOF (0x1800) /* Lost SOF */
#define FNR_FN (0x07FF) /* Frame Number */
/******************************************************************************/
/* DADDR Device ADDRess bit definitions */
/******************************************************************************/
#define DADDR_EF (0x80)
#define DADDR_ADD (0x7F)
/******************************************************************************/
/* Endpoint register */
/******************************************************************************/
/* bit positions */
#define EP_CTR_RX (0x8000) /* EndPoint Correct TRansfer RX */
#define EP_DTOG_RX (0x4000) /* EndPoint Data TOGGLE RX */
#define EPRX_STAT (0x3000) /* EndPoint RX STATus bit field */
#define EP_SETUP (0x0800) /* EndPoint SETUP */
#define EP_T_FIELD (0x0600) /* EndPoint TYPE */
#define EP_KIND (0x0100) /* EndPoint KIND */
#define EP_CTR_TX (0x0080) /* EndPoint Correct TRansfer TX */
#define EP_DTOG_TX (0x0040) /* EndPoint Data TOGGLE TX */
#define EPTX_STAT (0x0030) /* EndPoint TX STATus bit field */
#define EPADDR_FIELD (0x000F) /* EndPoint ADDRess FIELD */
/* EndPoint REGister MASK (no toggle fields) */
#define EPREG_MASK (EP_CTR_RX|EP_SETUP|EP_T_FIELD|EP_KIND|EP_CTR_TX|EPADDR_FIELD)
/* EP_TYPE[1:0] EndPoint TYPE */
#define EP_TYPE_MASK (0x0600) /* EndPoint TYPE Mask */
#define EP_BULK (0x0000) /* EndPoint BULK */
#define EP_CONTROL (0x0200) /* EndPoint CONTROL */
#define EP_ISOCHRONOUS (0x0400) /* EndPoint ISOCHRONOUS */
#define EP_INTERRUPT (0x0600) /* EndPoint INTERRUPT */
#define EP_T_MASK (~EP_T_FIELD & EPREG_MASK)
/* EP_KIND EndPoint KIND */
#define EPKIND_MASK (~EP_KIND & EPREG_MASK)
/* STAT_TX[1:0] STATus for TX transfer */
#define EP_TX_DIS (0x0000) /* EndPoint TX DISabled */
#define EP_TX_STALL (0x0010) /* EndPoint TX STALLed */
#define EP_TX_NAK (0x0020) /* EndPoint TX NAKed */
#define EP_TX_VALID (0x0030) /* EndPoint TX VALID */
#define EPTX_DTOG1 (0x0010) /* EndPoint TX Data TOGgle bit1 */
#define EPTX_DTOG2 (0x0020) /* EndPoint TX Data TOGgle bit2 */
#define EPTX_DTOGMASK (EPTX_STAT|EPREG_MASK)
/* STAT_RX[1:0] STATus for RX transfer */
#define EP_RX_DIS (0x0000) /* EndPoint RX DISabled */
#define EP_RX_STALL (0x1000) /* EndPoint RX STALLed */
#define EP_RX_NAK (0x2000) /* EndPoint RX NAKed */
#define EP_RX_VALID (0x3000) /* EndPoint RX VALID */
#define EPRX_DTOG1 (0x1000) /* EndPoint RX Data TOGgle bit1 */
#define EPRX_DTOG2 (0x2000) /* EndPoint RX Data TOGgle bit1 */
#define EPRX_DTOGMASK (EPRX_STAT|EPREG_MASK)
/* Exported macro ------------------------------------------------------------*/
/* SetCNTR */
#define _SetCNTR(wRegValue) (*CNTR = (uint16_t)wRegValue)
/* SetISTR */
#define _SetISTR(wRegValue) (*ISTR = (uint16_t)wRegValue)
/* SetDADDR */
#define _SetDADDR(wRegValue) (*DADDR = (uint16_t)wRegValue)
/* SetBTABLE */
#define _SetBTABLE(wRegValue)(*BTABLE = (uint16_t)(wRegValue & 0xFFF8))
/* GetCNTR */
#define _GetCNTR() ((uint16_t) *CNTR)
/* GetISTR */
#define _GetISTR() ((uint16_t) *ISTR)
/* GetFNR */
#define _GetFNR() ((uint16_t) *FNR)
/* GetDADDR */
#define _GetDADDR() ((uint16_t) *DADDR)
/* GetBTABLE */
#define _GetBTABLE() ((uint16_t) *BTABLE)
/* SetENDPOINT */
#define _SetENDPOINT(bEpNum,wRegValue) (*(EP0REG + bEpNum)= \
(uint16_t)wRegValue)
/* GetENDPOINT */
#define _GetENDPOINT(bEpNum) ((uint16_t)(*(EP0REG + bEpNum)))
/*******************************************************************************
* Macro Name : SetEPType
* Description : sets the type in the endpoint register(bits EP_TYPE[1:0])
* Input : bEpNum: Endpoint Number.
* wType
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPType(bEpNum,wType) (_SetENDPOINT(bEpNum,\
((_GetENDPOINT(bEpNum) & EP_T_MASK) | wType )))
/*******************************************************************************
* Macro Name : GetEPType
* Description : gets the type in the endpoint register(bits EP_TYPE[1:0])
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint Type
*******************************************************************************/
#define _GetEPType(bEpNum) (_GetENDPOINT(bEpNum) & EP_T_FIELD)
/*******************************************************************************
* Macro Name : SetEPTxStatus
* Description : sets the status for tx transfer (bits STAT_TX[1:0]).
* Input : bEpNum: Endpoint Number.
* wState: new state
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPTxStatus(bEpNum,wState) {\
register uint16_t _wRegVal; \
_wRegVal = _GetENDPOINT(bEpNum) & EPTX_DTOGMASK;\
/* toggle first bit ? */ \
if((EPTX_DTOG1 & wState)!= 0) \
_wRegVal ^= EPTX_DTOG1; \
/* toggle second bit ? */ \
if((EPTX_DTOG2 & wState)!= 0) \
_wRegVal ^= EPTX_DTOG2; \
_SetENDPOINT(bEpNum, (_wRegVal | EP_CTR_RX|EP_CTR_TX)); \
} /* _SetEPTxStatus */
/*******************************************************************************
* Macro Name : SetEPRxStatus
* Description : sets the status for rx transfer (bits STAT_TX[1:0])
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPRxStatus(bEpNum,wState) {\
register uint16_t _wRegVal; \
\
_wRegVal = _GetENDPOINT(bEpNum) & EPRX_DTOGMASK;\
/* toggle first bit ? */ \
if((EPRX_DTOG1 & wState)!= 0) \
_wRegVal ^= EPRX_DTOG1; \
/* toggle second bit ? */ \
if((EPRX_DTOG2 & wState)!= 0) \
_wRegVal ^= EPRX_DTOG2; \
_SetENDPOINT(bEpNum, (_wRegVal | EP_CTR_RX|EP_CTR_TX)); \
} /* _SetEPRxStatus */
/*******************************************************************************
* Macro Name : SetEPRxTxStatus
* Description : sets the status for rx & tx (bits STAT_TX[1:0] & STAT_RX[1:0])
* Input : bEpNum: Endpoint Number.
* wStaterx: new state.
* wStatetx: new state.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPRxTxStatus(bEpNum,wStaterx,wStatetx) {\
register uint32_t _wRegVal; \
\
_wRegVal = _GetENDPOINT(bEpNum) & (EPRX_DTOGMASK |EPTX_STAT) ;\
/* toggle first bit ? */ \
if((EPRX_DTOG1 & wStaterx)!= 0) \
_wRegVal ^= EPRX_DTOG1; \
/* toggle second bit ? */ \
if((EPRX_DTOG2 & wStaterx)!= 0) \
_wRegVal ^= EPRX_DTOG2; \
/* toggle first bit ? */ \
if((EPTX_DTOG1 & wStatetx)!= 0) \
_wRegVal ^= EPTX_DTOG1; \
/* toggle second bit ? */ \
if((EPTX_DTOG2 & wStatetx)!= 0) \
_wRegVal ^= EPTX_DTOG2; \
_SetENDPOINT(bEpNum, _wRegVal | EP_CTR_RX|EP_CTR_TX); \
} /* _SetEPRxTxStatus */
/*******************************************************************************
* Macro Name : GetEPTxStatus / GetEPRxStatus
* Description : gets the status for tx/rx transfer (bits STAT_TX[1:0]
* /STAT_RX[1:0])
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : status .
*******************************************************************************/
#define _GetEPTxStatus(bEpNum) ((uint16_t)_GetENDPOINT(bEpNum) & EPTX_STAT)
#define _GetEPRxStatus(bEpNum) ((uint16_t)_GetENDPOINT(bEpNum) & EPRX_STAT)
/*******************************************************************************
* Macro Name : SetEPTxValid / SetEPRxValid
* Description : sets directly the VALID tx/rx-status into the enpoint register
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPTxValid(bEpNum) (_SetEPTxStatus(bEpNum, EP_TX_VALID))
#define _SetEPRxValid(bEpNum) (_SetEPRxStatus(bEpNum, EP_RX_VALID))
/*******************************************************************************
* Macro Name : GetTxStallStatus / GetRxStallStatus.
* Description : checks stall condition in an endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : TRUE = endpoint in stall condition.
*******************************************************************************/
#define _GetTxStallStatus(bEpNum) (_GetEPTxStatus(bEpNum) \
== EP_TX_STALL)
#define _GetRxStallStatus(bEpNum) (_GetEPRxStatus(bEpNum) \
== EP_RX_STALL)
/*******************************************************************************
* Macro Name : SetEP_KIND / ClearEP_KIND.
* Description : set & clear EP_KIND bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEP_KIND(bEpNum) (_SetENDPOINT(bEpNum, \
(EP_CTR_RX|EP_CTR_TX|((_GetENDPOINT(bEpNum) | EP_KIND) & EPREG_MASK))))
#define _ClearEP_KIND(bEpNum) (_SetENDPOINT(bEpNum, \
(EP_CTR_RX|EP_CTR_TX|(_GetENDPOINT(bEpNum) & EPKIND_MASK))))
/*******************************************************************************
* Macro Name : Set_Status_Out / Clear_Status_Out.
* Description : Sets/clears directly STATUS_OUT bit in the endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _Set_Status_Out(bEpNum) _SetEP_KIND(bEpNum)
#define _Clear_Status_Out(bEpNum) _ClearEP_KIND(bEpNum)
/*******************************************************************************
* Macro Name : SetEPDoubleBuff / ClearEPDoubleBuff.
* Description : Sets/clears directly EP_KIND bit in the endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPDoubleBuff(bEpNum) _SetEP_KIND(bEpNum)
#define _ClearEPDoubleBuff(bEpNum) _ClearEP_KIND(bEpNum)
/*******************************************************************************
* Macro Name : ClearEP_CTR_RX / ClearEP_CTR_TX.
* Description : Clears bit CTR_RX / CTR_TX in the endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _ClearEP_CTR_RX(bEpNum) (_SetENDPOINT(bEpNum,\
_GetENDPOINT(bEpNum) & 0x7FFF & EPREG_MASK))
#define _ClearEP_CTR_TX(bEpNum) (_SetENDPOINT(bEpNum,\
_GetENDPOINT(bEpNum) & 0xFF7F & EPREG_MASK))
/*******************************************************************************
* Macro Name : ToggleDTOG_RX / ToggleDTOG_TX .
* Description : Toggles DTOG_RX / DTOG_TX bit in the endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _ToggleDTOG_RX(bEpNum) (_SetENDPOINT(bEpNum, \
EP_CTR_RX|EP_CTR_TX|EP_DTOG_RX | (_GetENDPOINT(bEpNum) & EPREG_MASK)))
#define _ToggleDTOG_TX(bEpNum) (_SetENDPOINT(bEpNum, \
EP_CTR_RX|EP_CTR_TX|EP_DTOG_TX | (_GetENDPOINT(bEpNum) & EPREG_MASK)))
/*******************************************************************************
* Macro Name : ClearDTOG_RX / ClearDTOG_TX.
* Description : Clears DTOG_RX / DTOG_TX bit in the endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _ClearDTOG_RX(bEpNum) if((_GetENDPOINT(bEpNum) & EP_DTOG_RX) != 0)\
_ToggleDTOG_RX(bEpNum)
#define _ClearDTOG_TX(bEpNum) if((_GetENDPOINT(bEpNum) & EP_DTOG_TX) != 0)\
_ToggleDTOG_TX(bEpNum)
/*******************************************************************************
* Macro Name : SetEPAddress.
* Description : Sets address in an endpoint register.
* Input : bEpNum: Endpoint Number.
* bAddr: Address.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPAddress(bEpNum,bAddr) _SetENDPOINT(bEpNum,\
EP_CTR_RX|EP_CTR_TX|(_GetENDPOINT(bEpNum) & EPREG_MASK) | bAddr)
/*******************************************************************************
* Macro Name : GetEPAddress.
* Description : Gets address in an endpoint register.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _GetEPAddress(bEpNum) ((uint8_t)(_GetENDPOINT(bEpNum) & EPADDR_FIELD))
#define _pEPTxAddr(bEpNum) ((uint32_t *)((_GetBTABLE()+bEpNum*8 )*2 + PMAAddr))
#define _pEPTxCount(bEpNum) ((uint32_t *)((_GetBTABLE()+bEpNum*8+2)*2 + PMAAddr))
#define _pEPRxAddr(bEpNum) ((uint32_t *)((_GetBTABLE()+bEpNum*8+4)*2 + PMAAddr))
#define _pEPRxCount(bEpNum) ((uint32_t *)((_GetBTABLE()+bEpNum*8+6)*2 + PMAAddr))
/*******************************************************************************
* Macro Name : SetEPTxAddr / SetEPRxAddr.
* Description : sets address of the tx/rx buffer.
* Input : bEpNum: Endpoint Number.
* wAddr: address to be set (must be word aligned).
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPTxAddr(bEpNum,wAddr) (*_pEPTxAddr(bEpNum) = ((wAddr >> 1) << 1))
#define _SetEPRxAddr(bEpNum,wAddr) (*_pEPRxAddr(bEpNum) = ((wAddr >> 1) << 1))
/*******************************************************************************
* Macro Name : GetEPTxAddr / GetEPRxAddr.
* Description : Gets address of the tx/rx buffer.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : address of the buffer.
*******************************************************************************/
#define _GetEPTxAddr(bEpNum) ((uint16_t)*_pEPTxAddr(bEpNum))
#define _GetEPRxAddr(bEpNum) ((uint16_t)*_pEPRxAddr(bEpNum))
/*******************************************************************************
* Macro Name : SetEPCountRxReg.
* Description : Sets counter of rx buffer with no. of blocks.
* Input : pdwReg: pointer to counter.
* wCount: Counter.
* Output : None.
* Return : None.
*******************************************************************************/
#define _BlocksOf32(dwReg,wCount,wNBlocks) {\
wNBlocks = wCount >> 5;\
if((wCount & 0x1f) == 0)\
wNBlocks--;\
*pdwReg = (uint32_t)((wNBlocks << 10) | 0x8000);\
}/* _BlocksOf32 */
#define _BlocksOf2(dwReg,wCount,wNBlocks) {\
wNBlocks = wCount >> 1;\
if((wCount & 0x1) != 0)\
wNBlocks++;\
*pdwReg = (uint32_t)(wNBlocks << 10);\
}/* _BlocksOf2 */
#define _SetEPCountRxReg(dwReg,wCount) {\
uint16_t wNBlocks;\
if(wCount > 62){_BlocksOf32(dwReg,wCount,wNBlocks);}\
else {_BlocksOf2(dwReg,wCount,wNBlocks);}\
}/* _SetEPCountRxReg */
#define _SetEPRxDblBuf0Count(bEpNum,wCount) {\
uint32_t *pdwReg = _pEPTxCount(bEpNum); \
_SetEPCountRxReg(pdwReg, wCount);\
}
/*******************************************************************************
* Macro Name : SetEPTxCount / SetEPRxCount.
* Description : sets counter for the tx/rx buffer.
* Input : bEpNum: endpoint number.
* wCount: Counter value.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPTxCount(bEpNum,wCount) (*_pEPTxCount(bEpNum) = wCount)
#define _SetEPRxCount(bEpNum,wCount) {\
uint32_t *pdwReg = _pEPRxCount(bEpNum); \
_SetEPCountRxReg(pdwReg, wCount);\
}
/*******************************************************************************
* Macro Name : GetEPTxCount / GetEPRxCount.
* Description : gets counter of the tx buffer.
* Input : bEpNum: endpoint number.
* Output : None.
* Return : Counter value.
*******************************************************************************/
#define _GetEPTxCount(bEpNum)((uint16_t)(*_pEPTxCount(bEpNum)) & 0x3ff)
#define _GetEPRxCount(bEpNum)((uint16_t)(*_pEPRxCount(bEpNum)) & 0x3ff)
/*******************************************************************************
* Macro Name : SetEPDblBuf0Addr / SetEPDblBuf1Addr.
* Description : Sets buffer 0/1 address in a double buffer endpoint.
* Input : bEpNum: endpoint number.
* : wBuf0Addr: buffer 0 address.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPDblBuf0Addr(bEpNum,wBuf0Addr) {_SetEPTxAddr(bEpNum, wBuf0Addr);}
#define _SetEPDblBuf1Addr(bEpNum,wBuf1Addr) {_SetEPRxAddr(bEpNum, wBuf1Addr);}
/*******************************************************************************
* Macro Name : SetEPDblBuffAddr.
* Description : Sets addresses in a double buffer endpoint.
* Input : bEpNum: endpoint number.
* : wBuf0Addr: buffer 0 address.
* : wBuf1Addr = buffer 1 address.
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPDblBuffAddr(bEpNum,wBuf0Addr,wBuf1Addr) { \
_SetEPDblBuf0Addr(bEpNum, wBuf0Addr);\
_SetEPDblBuf1Addr(bEpNum, wBuf1Addr);\
} /* _SetEPDblBuffAddr */
/*******************************************************************************
* Macro Name : GetEPDblBuf0Addr / GetEPDblBuf1Addr.
* Description : Gets buffer 0/1 address of a double buffer endpoint.
* Input : bEpNum: endpoint number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _GetEPDblBuf0Addr(bEpNum) (_GetEPTxAddr(bEpNum))
#define _GetEPDblBuf1Addr(bEpNum) (_GetEPRxAddr(bEpNum))
/*******************************************************************************
* Macro Name : SetEPDblBuffCount / SetEPDblBuf0Count / SetEPDblBuf1Count.
* Description : Gets buffer 0/1 address of a double buffer endpoint.
* Input : bEpNum: endpoint number.
* : bDir: endpoint dir EP_DBUF_OUT = OUT
* EP_DBUF_IN = IN
* : wCount: Counter value
* Output : None.
* Return : None.
*******************************************************************************/
#define _SetEPDblBuf0Count(bEpNum, bDir, wCount) { \
if(bDir == EP_DBUF_OUT)\
/* OUT endpoint */ \
{_SetEPRxDblBuf0Count(bEpNum,wCount);} \
else if(bDir == EP_DBUF_IN)\
/* IN endpoint */ \
*_pEPTxCount(bEpNum) = (uint32_t)wCount; \
} /* SetEPDblBuf0Count*/
#define _SetEPDblBuf1Count(bEpNum, bDir, wCount) { \
if(bDir == EP_DBUF_OUT)\
/* OUT endpoint */ \
{_SetEPRxCount(bEpNum,wCount);}\
else if(bDir == EP_DBUF_IN)\
/* IN endpoint */\
*_pEPRxCount(bEpNum) = (uint32_t)wCount; \
} /* SetEPDblBuf1Count */
#define _SetEPDblBuffCount(bEpNum, bDir, wCount) {\
_SetEPDblBuf0Count(bEpNum, bDir, wCount); \
_SetEPDblBuf1Count(bEpNum, bDir, wCount); \
} /* _SetEPDblBuffCount */
/*******************************************************************************
* Macro Name : GetEPDblBuf0Count / GetEPDblBuf1Count.
* Description : Gets buffer 0/1 rx/tx counter for double buffering.
* Input : bEpNum: endpoint number.
* Output : None.
* Return : None.
*******************************************************************************/
#define _GetEPDblBuf0Count(bEpNum) (_GetEPTxCount(bEpNum))
#define _GetEPDblBuf1Count(bEpNum) (_GetEPRxCount(bEpNum))
/* External variables --------------------------------------------------------*/
extern __IO uint16_t wIstr; /* ISTR register last read value */
/* Exported functions ------------------------------------------------------- */
void SetCNTR(uint16_t /*wRegValue*/);
void SetISTR(uint16_t /*wRegValue*/);
void SetDADDR(uint16_t /*wRegValue*/);
void SetBTABLE(uint16_t /*wRegValue*/);
void SetBTABLE(uint16_t /*wRegValue*/);
uint16_t GetCNTR(void);
uint16_t GetISTR(void);
uint16_t GetFNR(void);
uint16_t GetDADDR(void);
uint16_t GetBTABLE(void);
void SetENDPOINT(uint8_t /*bEpNum*/, uint16_t /*wRegValue*/);
uint16_t GetENDPOINT(uint8_t /*bEpNum*/);
void SetEPType(uint8_t /*bEpNum*/, uint16_t /*wType*/);
uint16_t GetEPType(uint8_t /*bEpNum*/);
void SetEPTxStatus(uint8_t /*bEpNum*/, uint16_t /*wState*/);
void SetEPRxStatus(uint8_t /*bEpNum*/, uint16_t /*wState*/);
void SetDouBleBuffEPStall(uint8_t /*bEpNum*/, uint8_t bDir);
uint16_t GetEPTxStatus(uint8_t /*bEpNum*/);
uint16_t GetEPRxStatus(uint8_t /*bEpNum*/);
void SetEPTxValid(uint8_t /*bEpNum*/);
void SetEPRxValid(uint8_t /*bEpNum*/);
uint16_t GetTxStallStatus(uint8_t /*bEpNum*/);
uint16_t GetRxStallStatus(uint8_t /*bEpNum*/);
void SetEP_KIND(uint8_t /*bEpNum*/);
void ClearEP_KIND(uint8_t /*bEpNum*/);
void Set_Status_Out(uint8_t /*bEpNum*/);
void Clear_Status_Out(uint8_t /*bEpNum*/);
void SetEPDoubleBuff(uint8_t /*bEpNum*/);
void ClearEPDoubleBuff(uint8_t /*bEpNum*/);
void ClearEP_CTR_RX(uint8_t /*bEpNum*/);
void ClearEP_CTR_TX(uint8_t /*bEpNum*/);
void ToggleDTOG_RX(uint8_t /*bEpNum*/);
void ToggleDTOG_TX(uint8_t /*bEpNum*/);
void ClearDTOG_RX(uint8_t /*bEpNum*/);
void ClearDTOG_TX(uint8_t /*bEpNum*/);
void SetEPAddress(uint8_t /*bEpNum*/, uint8_t /*bAddr*/);
uint8_t GetEPAddress(uint8_t /*bEpNum*/);
void SetEPTxAddr(uint8_t /*bEpNum*/, uint16_t /*wAddr*/);
void SetEPRxAddr(uint8_t /*bEpNum*/, uint16_t /*wAddr*/);
uint16_t GetEPTxAddr(uint8_t /*bEpNum*/);
uint16_t GetEPRxAddr(uint8_t /*bEpNum*/);
void SetEPCountRxReg(uint32_t * /*pdwReg*/, uint16_t /*wCount*/);
void SetEPTxCount(uint8_t /*bEpNum*/, uint16_t /*wCount*/);
void SetEPRxCount(uint8_t /*bEpNum*/, uint16_t /*wCount*/);
uint16_t GetEPTxCount(uint8_t /*bEpNum*/);
uint16_t GetEPRxCount(uint8_t /*bEpNum*/);
void SetEPDblBuf0Addr(uint8_t /*bEpNum*/, uint16_t /*wBuf0Addr*/);
void SetEPDblBuf1Addr(uint8_t /*bEpNum*/, uint16_t /*wBuf1Addr*/);
void SetEPDblBuffAddr(uint8_t /*bEpNum*/, uint16_t /*wBuf0Addr*/, uint16_t /*wBuf1Addr*/);
uint16_t GetEPDblBuf0Addr(uint8_t /*bEpNum*/);
uint16_t GetEPDblBuf1Addr(uint8_t /*bEpNum*/);
void SetEPDblBuffCount(uint8_t /*bEpNum*/, uint8_t /*bDir*/, uint16_t /*wCount*/);
void SetEPDblBuf0Count(uint8_t /*bEpNum*/, uint8_t /*bDir*/, uint16_t /*wCount*/);
void SetEPDblBuf1Count(uint8_t /*bEpNum*/, uint8_t /*bDir*/, uint16_t /*wCount*/);
uint16_t GetEPDblBuf0Count(uint8_t /*bEpNum*/);
uint16_t GetEPDblBuf1Count(uint8_t /*bEpNum*/);
EP_DBUF_DIR GetEPDblBufDir(uint8_t /*bEpNum*/);
void FreeUserBuffer(uint8_t bEpNum/*bEpNum*/, uint8_t bDir);
uint16_t ToWord(uint8_t, uint8_t);
uint16_t ByteSwap(uint16_t);
#endif /* STM32F10X_CL */
#endif /* __USB_REGS_H */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/inc/usb_regs.h
|
C
|
asf20
| 31,081
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_sil.h
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Simplified Interface Layer function prototypes.
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_SIL_H
#define __USB_SIL_H
/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
uint32_t USB_SIL_Init(void);
uint32_t USB_SIL_Write(uint8_t bEpAddr, uint8_t* pBufferPointer, uint32_t wBufferSize);
uint32_t USB_SIL_Read(uint8_t bEpAddr, uint8_t* pBufferPointer);
/* External variables --------------------------------------------------------*/
#endif /* __USB_SIL_H */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/inc/usb_sil.h
|
C
|
asf20
| 1,846
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otg_dev.h
* Author : STMicroelectronics
* Version : V3.2.1
* Date : 07/05/2010
* Description : linking defines
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __OTG_DEV_H__
#define __OTG_DEV_H__
#ifdef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "usb_type.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Endpoint types */
#define OTG_DEV_EP_TYPE_CONTROL 0
#define OTG_DEV_EP_TYPE_ISOC 1
#define OTG_DEV_EP_TYPE_BULK 2
#define OTG_DEV_EP_TYPE_INT 3
/* Endpoint Addresses (w/direction) */
#define EP0_OUT 0x00
#define EP0_IN 0x80
#define EP1_OUT 0x01
#define EP1_IN 0x81
#define EP2_OUT 0x02
#define EP2_IN 0x82
#define EP3_OUT 0x03
#define EP3_IN 0x83
/*-*-*-*-*-*-*-*-*-* Replace the usb_regs.h defines -*-*-*-*-*-*-*-*-*-*-*-*-*/
/* endpoints enumeration */
#define ENDP0 ((uint8_t)0)
#define ENDP1 ((uint8_t)1)
#define ENDP2 ((uint8_t)2)
#define ENDP3 ((uint8_t)3)
#define ENDP4 ((uint8_t)4)
#define ENDP5 ((uint8_t)5)
#define ENDP6 ((uint8_t)6)
#define ENDP7 ((uint8_t)7)
/* EP Transmit status defines */
#define EP_TX_DIS DEV_EP_TX_DIS) /* EndPoint TX DISabled */
#define EP_TX_STALL DEV_EP_TX_STALL /* EndPoint TX STALLed */
#define EP_TX_NAK DEV_EP_TX_NAK /* EndPoint TX NAKed */
#define EP_TX_VALID DEV_EP_TX_VALID /* EndPoint TX VALID */
/* EP Transmit status defines */
#define EP_RX_DIS DEV_EP_RX_DIS /* EndPoint RX DISabled */
#define EP_RX_STALL DEV_EP_RX_STALL /* EndPoint RX STALLed */
#define EP_RX_NAK DEV_EP_RX_NAK /* EndPoint RX NAKed */
#define EP_RX_VALID DEV_EP_RX_VALID /* EndPoint RX VALID */
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
/* Exported macro ------------------------------------------------------------*/
#define _GetEPTxStatus(bEpNum) ((uint16_t)OTG_DEV_GetEPTxStatus(bEpNum))
#define _GetEPRxStatus(bEpNum) ((uint16_t)OTG_DEV_GetEPRxStatus(bEpNum))
#define _SetEPTxStatus(bEpNum,wState) (OTG_DEV_SetEPTxStatus(bEpNum, wState))
#define _SetEPRxStatus(bEpNum,wState) (OTG_DEV_SetEPRxStatus(bEpNum, wState))
#define _SetEPTxValid(bEpNum) (OTG_DEV_SetEPTxStatus(bEpNum, EP_TX_VALID))
#define _SetEPRxValid(bEpNum) (OTG_DEV_SetEPRxStatus(bEpNum, EP_RX_VALID))
#define _GetTxStallStatus(bEpNum) (OTG_DEV_GetEPTxStatus(bEpNum) == EP_TX_STALL)
#define _GetRxStallStatus(bEpNum) (OTG_DEV_GetEPRxStatus(bEpNum) == EP_RX_STALL)
/* Define the callbacks for updating the USB state machine */
#define OTGD_FS_DEVICE_RESET Device_Property.Reset()
/* Exported define -----------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void OTG_DEV_Init(void);
void OTG_DEV_EP_Init(uint8_t bEpAdd, uint8_t bEpType, uint16_t wEpMaxPackSize);
void OTG_DEV_SetEPRxStatus(uint8_t bEpnum, uint32_t status);
void OTG_DEV_SetEPTxStatus(uint8_t bEpnum, uint32_t status);
uint32_t OTG_DEV_GetEPRxStatus(uint8_t bEpnum);
uint32_t OTG_DEV_GetEPTxStatus(uint8_t bEpnum);
void USB_DevDisconnect(void);
void USB_DevConnect(void);
/*-*-*-*-*-*-*-*-*-* Replace the usb_regs.h prototypes *-*-*-*-*-*-*-*-*-*-*-*/
void SetEPTxStatus(uint8_t bEpNum, uint16_t wState);
void SetEPRxStatus(uint8_t bEpNum, uint16_t wState);
uint16_t GetEPTxStatus(uint8_t bEpNum);
uint16_t GetEPRxStatus(uint8_t bEpNum);
void SetEPTxValid(uint8_t bEpNum);
void SetEPRxValid(uint8_t bEpNum);
uint16_t GetTxStallStatus(uint8_t bEpNum);
uint16_t GetRxStallStatus(uint8_t bEpNum);
void SetEPTxCount(uint8_t bEpNum, uint16_t wCount);
void SetEPRxCount(uint8_t bEpNum, uint16_t wCount);
uint16_t ToWord(uint8_t, uint8_t);
uint16_t ByteSwap(uint16_t);
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
#endif /* STM32F10X_CL */
#endif /* __OTG_DEV_H__ */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/inc/otgd_fs_dev.h
|
C
|
asf20
| 5,287
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otgd_fs_pcd.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Peripheral Device Interface low layer.
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifdef STM32F10X_CL
#include "usb_lib.h"
#include "otgd_fs_cal.h"
#include "otgd_fs_pcd.h"
USB_OTG_PCD_DEV USB_OTG_PCD_dev;
extern USB_OTG_CORE_REGS USB_OTG_FS_regs;
/*******************************************************************************
* Function Name : PCD_Init
* Description : Initialize the USB Device portion of the driver.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PCD_Init(void)
{
uint32_t i = 0;
USB_OTG_EP *ep;
/**** SOFTWARE INIT *****/
ep = &USB_OTG_PCD_dev.ep0;
/* Init ep structure */
ep->num = 0;
ep->tx_fifo_num = 0;
/* Control until ep is actvated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
for (i = 1; i < NUM_TX_FIFOS ; i++)
{
ep = &USB_OTG_PCD_dev.in_ep[i-1];
/* Init ep structure */
ep->is_in = 1;
ep->num = i;
ep->tx_fifo_num = i;
/* Control until ep is actvated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
}
for (i = 1; i < NUM_TX_FIFOS; i++)
{
ep = &USB_OTG_PCD_dev.out_ep[i-1];
/* Init ep structure */
ep->is_in = 0;
ep->num = i;
ep->tx_fifo_num = i;
/* Control until ep is activated */
ep->type = EP_TYPE_CTRL;
ep->maxpacket = MAX_PACKET_SIZE;
ep->xfer_buff = 0;
ep->xfer_len = 0;
}
USB_OTG_PCD_dev.ep0.maxpacket = MAX_EP0_SIZE;
USB_OTG_PCD_dev.ep0.type = EP_TYPE_CTRL;
/**** HARDWARE INIT *****/
/* Set the OTG_USB base registers address */
OTGD_FS_SetAddress(USB_OTG_FS_BASE_ADDR);
/* Disable all global interrupts */
OTGD_FS_DisableGlobalInt();
/*Init the Core */
OTGD_FS_CoreInit();
/* Init Device mode*/
OTGD_FS_CoreInitDev();
}
/*******************************************************************************
* Function Name : PCD_EP_Open
* Description : Configure an Endpoint
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Open(EP_DESCRIPTOR *epdesc)
{
USB_OTG_EP *ep;
if ((0x80 & epdesc->bEndpointAddress) != 0)
{
ep = PCD_GetInEP(epdesc->bEndpointAddress & 0x7F);
ep->is_in = 1;
}
else
{
ep = PCD_GetOutEP(epdesc->bEndpointAddress & 0x7F);
ep->is_in = 0;
}
ep->num = epdesc->bEndpointAddress & 0x7F;
ep->maxpacket = epdesc->wMaxPacketSize;
ep->type = epdesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
if (ep->is_in)
{
/* Assign a Tx FIFO */
ep->tx_fifo_num = ep->num;
}
OTGD_FS_EPActivate(ep );
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Close
* Description : Called when an EP is disabled
* Input : Endpoint address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Close(uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = (0x80 & ep_addr) != 0;
OTGD_FS_EPDeactivate(ep );
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Read
* Description : Read data from Fifo
* Input : Endpoint address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Read (uint8_t ep_addr, uint8_t *pbuf, uint32_t buf_len)
{
USB_OTG_EP *ep;
uint32_t i = 0;
ep = PCD_GetOutEP(ep_addr & 0x7F);
/* copy received data into application buffer */
for (i = 0 ; i < buf_len ; i++)
{
pbuf[i] = ep->xfer_buff[i];
}
/*setup and start the Xfer */
ep->xfer_buff = pbuf;
ep->xfer_len = buf_len;
ep->xfer_count = 0;
ep->is_in = 0;
ep->num = ep_addr & 0x7F;
if ( ep->num == 0 )
{
OTGD_FS_EP0StartXfer(ep);
}
else
{
OTGD_FS_EPStartXfer( ep );
}
return 0;
}
/*******************************************************************************
* Function Name : USBF_EP_Write
* Description : Read data from Fifo
* Input : ep
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Write (uint8_t ep_addr, uint8_t *pbuf, uint32_t buf_len)
{
USB_OTG_EP *ep;
ep = PCD_GetInEP(ep_addr & 0x7f);
/* assign data to EP structure buffer */
ep->xfer_buff = pbuf;
/* Setup and start the Transfer */
ep->xfer_count = 0;
ep->xfer_len = buf_len;
ep->is_in = 1;
ep->num = ep_addr & 0x7F;
if ( ep->num == 0 )
{
OTGD_FS_EP0StartXfer(ep);
}
else
{
OTGD_FS_EPStartXfer( ep );
}
return 0;
}
/*******************************************************************************
* Function Name : PCD_EP_Stall
* Description : Stall an endpoint.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Stall (uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = ((ep_addr & 0x80) == 0x80) ? 1 : 0;
OTGD_FS_EPSetStall(ep);
return (0);
}
/*******************************************************************************
* Function Name : PCD_EP_ClrStall
* Description : Clear stall condition on endpoints.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_ClrStall (uint8_t ep_addr)
{
USB_OTG_EP *ep;
if ((0x80 & ep_addr) != 0)
{
ep = PCD_GetInEP(ep_addr & 0x7F);
}
else
{
ep = PCD_GetOutEP(ep_addr & 0x7F);
}
ep->num = ep_addr & 0x7F;
ep->is_in = ((ep_addr & 0x80) == 0x80) ? 1 : 0;
OTGD_FS_EPClearStall(ep);
return (0);
}
/*******************************************************************************
* Function Name : USBF_FCD_EP_Flush()
* Description : This Function flushes the buffer.
* Input : Endpoint Address.
* Output : None
* Return : status
*******************************************************************************/
uint32_t PCD_EP_Flush (uint8_t ep_addr)
{
uint8_t is_out = 0;
uint8_t ep_nbr = 0;
ep_nbr = ep_addr & 0x7F;
is_out = ((ep_addr & 0x80) == 0x80) ? 0 : 1;
if (is_out == 0)
{
OTGD_FS_FlushTxFifo(ep_nbr);
}
else
{
OTGD_FS_FlushRxFifo();
}
PCD_EP_ClrStall(ep_addr);
return (0);
}
/*******************************************************************************
* Function Name : PCD_EP_SetAddress
* Description : This Function set USB device address
* Input : The new device Address to be set.
* Output : None
* Return : status
*******************************************************************************/
void PCD_EP_SetAddress (uint8_t address)
{
USB_OTG_DCFG_TypeDef dcfg;
dcfg.d32 = 0;
dcfg.b.devaddr = address;
USB_OTG_MODIFY_REG32( &USB_OTG_FS_regs.DEV->DCFG, 0, dcfg.d32);
}
/*******************************************************************************
* Function Name : PCD_GetInEP
* Description : This function returns pointer to IN EP struct with number ep_num
* Input : Endpoint Number.
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_EP* PCD_GetInEP(uint32_t ep_num)
{
if (ep_num == 0)
{
return &USB_OTG_PCD_dev.ep0;
}
else
{
return &USB_OTG_PCD_dev.in_ep[ep_num - 1];
}
}
/*******************************************************************************
* Function Name : PCD_GetOutEP
* Description : returns pointer to OUT EP struct with number ep_num
* Input : Endpoint Number.
* Output : None
* Return : USBF_EP
*******************************************************************************/
USB_OTG_EP* PCD_GetOutEP(uint32_t ep_num)
{
if (ep_num == 0)
{
return &USB_OTG_PCD_dev.ep0;
}
else
{
return &USB_OTG_PCD_dev.out_ep[ep_num - 1];
}
}
/*******************************************************************************
* Function Name : PCD_DevConnect
* Description : Connect device
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void PCD_DevConnect(void)
{
USB_OTG_DCTL_TypeDef dctl;
dctl.d32 = 0;
dctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Connect device */
dctl.b.sftdiscon = 0;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32);
mDELAY(25);
}
/*******************************************************************************
* Function Name : PCD_DevDisconnect
* Description : Disconnect device
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void PCD_DevDisconnect (void)
{
USB_OTG_DCTL_TypeDef dctl;
dctl.d32 = 0;
dctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Disconnect device for 20ms */
dctl.b.sftdiscon = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32);
mDELAY(25);
}
/*******************************************************************************
* Function Name : PCD_EP0_OutStart
* Description : Configures EPO to receive SETUP packets.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PCD_EP0_OutStart(void)
{
USB_OTG_DOEPTSIZ0_TypeDef doeptsize0;
doeptsize0.d32 = 0;
doeptsize0.b.supcnt = 3;
doeptsize0.b.pktcnt = 1;
doeptsize0.b.xfersize = 8 * 3;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DOUTEPS[0]->DOEPTSIZx, doeptsize0.d32 );
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/otgd_fs_pcd.c
|
C
|
asf20
| 11,786
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otgd_fs_dev.c
* Author : STMicroelectronics
* Version : V3.2.1
* Date : 07/05/2010
* Description : High Layer device mode interface and wrapping layer.
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifdef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "otgd_fs_dev.h"
#include "usb_regs.h"
#include "otgd_fs_cal.h"
#include "otgd_fs_pcd.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : OTG_DEV_Init
* Description : Initialize the OTG Device IP and EP0.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void OTG_DEV_Init(void)
{
EP_DESCRIPTOR ep_descriptor;
/* Init peripheral driver */
PCD_Init();
/* Configure and open the IN control EP0 */
ep_descriptor.bEndpointAddress = 0x80;
ep_descriptor.wMaxPacketSize = 64;
ep_descriptor.bmAttributes = USB_ENDPOINT_XFER_CONTROL;
PCD_EP_Open(&ep_descriptor);
/* Configure and open the OUT control EP0 */
ep_descriptor.bEndpointAddress = 0x00;
PCD_EP_Open(&ep_descriptor);
OTGD_FS_EPStartXfer(PCD_GetOutEP(0));
/* Enable EP0 to start receiving setup packets */
PCD_EP0_OutStart();
/* Enable USB Global interrupt */
OTGD_FS_EnableGlobalInt();
}
/*******************************************************************************
* Function Name : OTG_DEV_EP_Init
* Description : Initialize the selected endpoint parameters
* Input : - bEpAdd: address of the endpoint (epnum|epdir)
* expample: EP1 OUT -> 0x01 and EP1 IN 0x81.
* - bEpType: OTG_DEV_EP_TYPE_CONTROL, OTG_DEV_EP_TYPE_ISOC,
* OTG_DEV_EP_TYPE_BULK, OTG_DEV_EP_TYPE_INT
* - wEpMaxPackSize: The EP max packet size.
* Output : None.
* Return : Status: New status to be set for the endpoint:
*******************************************************************************/
void OTG_DEV_EP_Init(uint8_t bEpAdd, uint8_t bEpType, uint16_t wEpMaxPackSize)
{
EP_DESCRIPTOR ep_descriptor;
USB_OTG_EP *ep;
/* Set the EP parameters in a structure */
ep_descriptor.bEndpointAddress = bEpAdd;
ep_descriptor.bmAttributes = bEpType;
ep_descriptor.wMaxPacketSize = wEpMaxPackSize;
PCD_EP_Flush(bEpAdd);
/* Open the EP with entered parameters */
PCD_EP_Open(&ep_descriptor);
/* Activate the EP if it is an OUT EP */
if ((bEpAdd & 0x80) == 0)
{
ep = PCD_GetOutEP(bEpAdd & 0x7F);
OTGD_FS_EPStartXfer(ep);
}
else
{
ep = PCD_GetInEP(bEpAdd & 0x7F);
ep->even_odd_frame = 0;
OTG_DEV_SetEPTxStatus(bEpAdd, DEV_EP_TX_NAK);
}
}
/*******************************************************************************
* Function Name : OTG_DEV_GetEPTxStatus
* Description : Set the related endpoint status.
* Input : Number of the endpoint.
* Output : None.
* Return : Status: New status to be set for the endpoint:
*******************************************************************************/
uint32_t OTG_DEV_GetEPTxStatus(uint8_t bEpnum)
{
USB_OTG_EP *ep;
uint32_t status = 0;
ep = PCD_GetInEP(bEpnum & 0x7F);
status = OTGD_FS_GetEPStatus(ep);
return status;
}
/*******************************************************************************
* Function Name : OTG_DEV_GetEPRxStatus
* Description : returns the related endpoint status.
* Input : Number of the endpoint.
* Output : None.
* Return : Status: New status to be set for the endpoint:
*******************************************************************************/
uint32_t OTG_DEV_GetEPRxStatus(uint8_t bEpnum)
{
USB_OTG_EP *ep;
uint32_t status = 0;
ep = PCD_GetOutEP(bEpnum & 0x7F);
status = OTGD_FS_GetEPStatus(ep);
return status;
}
/*******************************************************************************
* Function Name : OTG_DEV_SetEPTxStatus
* Description : Sets the related endpoint status.
* Input : - bEpnum: Number of the endpoint.
* - Status: New status to be set for the endpoint. It can be
* DEV_EP_TX_VALID, DEV_EP_TX_STALL, DEV_EP_TX_NAK or
* DEV_EP_TX_DISABLE.
* Output : None.
* Return : None.
*******************************************************************************/
void OTG_DEV_SetEPTxStatus(uint8_t bEpnum, uint32_t Status)
{
USB_OTG_EP *ep;
ep = PCD_GetInEP(bEpnum & 0x7F);
if ((bEpnum == 0x80) && (Status == DEV_EP_TX_STALL))
{
ep->is_in = 1;
}
OTGD_FS_SetEPStatus(ep, Status);
}
/*******************************************************************************
* Function Name : OTG_DEV_SetEPRxStatus
* Description : Sets the related endpoint status.
* Input : - bEpnum: Number of the endpoint.
* - Status: New status to be set for the endpoint. It can be
* DEV_EP_RX_VALID, DEV_EP_RX_STALL, DEV_EP_RX_NAK or
* DEV_EP_RX_DISABLE.
* Output : None.
* Return : None.
*******************************************************************************/
void OTG_DEV_SetEPRxStatus(uint8_t bEpnum, uint32_t Status)
{
USB_OTG_EP *ep;
ep = PCD_GetOutEP(bEpnum & 0x7F);
OTGD_FS_SetEPStatus(ep, Status);
}
/*******************************************************************************
* Function Name : USB_DevDisconnect
* Description : Disconnect the Pullup resist.
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void USB_DevDisconnect(void)
{
PCD_DevDisconnect();
}
/*******************************************************************************
* Function Name : USB_DevConnect
* Description : Disconnect the .
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void USB_DevConnect(void)
{
PCD_DevConnect();
}
/*-*-*-*-*-*-*-*-*-* Replace the usb_regs.h defines -*-*-*-*-*-*-*-*-*-*-*-*-*/
/*******************************************************************************
* Function Name : SetEPTxStatus
* Description : Set the status of Tx endpoint.
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxStatus(uint8_t bEpNum, uint16_t wState)
{
_SetEPTxStatus(bEpNum, wState);
}
/*******************************************************************************
* Function Name : SetEPRxStatus
* Description : Set the status of Rx endpoint.
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxStatus(uint8_t bEpNum, uint16_t wState)
{
_SetEPRxStatus(bEpNum, wState);
}
/*******************************************************************************
* Function Name : GetEPTxStatus
* Description : Returns the endpoint Tx status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint TX Status
*******************************************************************************/
uint16_t GetEPTxStatus(uint8_t bEpNum)
{
return(_GetEPTxStatus(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPRxStatus
* Description : Returns the endpoint Rx status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint RX Status
*******************************************************************************/
uint16_t GetEPRxStatus(uint8_t bEpNum)
{
return(_GetEPRxStatus(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxValid
* Description : Valid the endpoint Tx Status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxValid(uint8_t bEpNum)
{
_SetEPTxStatus(bEpNum, EP_TX_VALID);
}
/*******************************************************************************
* Function Name : SetEPRxValid
* Description : Valid the endpoint Rx Status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxValid(uint8_t bEpNum)
{
_SetEPRxStatus(bEpNum, EP_RX_VALID);
}
/*******************************************************************************
* Function Name : GetTxStallStatus
* Description : Returns the Stall status of the Tx endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Tx Stall status.
*******************************************************************************/
uint16_t GetTxStallStatus(uint8_t bEpNum)
{
return(_GetTxStallStatus(bEpNum));
}
/*******************************************************************************
* Function Name : GetRxStallStatus
* Description : Returns the Stall status of the Rx endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Rx Stall status.
*******************************************************************************/
uint16_t GetRxStallStatus(uint8_t bEpNum)
{
return(_GetRxStallStatus(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxCount.
* Description : Set the Tx count.
* Input : bEpNum: Endpoint Number.
* wCount: new count value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxCount(uint8_t bEpNum, uint16_t wCount)
{
}
/*******************************************************************************
* Function Name : SetEPRxCount
* Description : Set the Rx count.
* Input : bEpNum: Endpoint Number.
* wCount: the new count value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxCount(uint8_t bEpNum, uint16_t wCount)
{
}
/*******************************************************************************
* Function Name : ToWord
* Description : merge two byte in a word.
* Input : bh: byte high, bl: bytes low.
* Output : None.
* Return : resulted word.
*******************************************************************************/
uint16_t ToWord(uint8_t bh, uint8_t bl)
{
uint16_t wRet = 0;
wRet = (uint16_t)bl | ((uint16_t)bh << 8);
return(wRet);
}
/*******************************************************************************
* Function Name : ByteSwap
* Description : Swap two byte in a word.
* Input : wSwW: word to Swap.
* Output : None.
* Return : resulted word.
*******************************************************************************/
uint16_t ByteSwap(uint16_t wSwW)
{
uint8_t bTemp = 0;
uint16_t wRet = 0;
bTemp = (uint8_t)(wSwW & 0xff);
wRet = (wSwW >> 8) | ((uint16_t)bTemp << 8);
return(wRet);
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/otgd_fs_dev.c
|
C
|
asf20
| 13,562
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_regs.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Interface functions to USB cell registers
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifndef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : SetCNTR.
* Description : Set the CNTR register value.
* Input : wRegValue: new register value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetCNTR(uint16_t wRegValue)
{
_SetCNTR(wRegValue);
}
/*******************************************************************************
* Function Name : GetCNTR.
* Description : returns the CNTR register value.
* Input : None.
* Output : None.
* Return : CNTR register Value.
*******************************************************************************/
uint16_t GetCNTR(void)
{
return(_GetCNTR());
}
/*******************************************************************************
* Function Name : SetISTR.
* Description : Set the ISTR register value.
* Input : wRegValue: new register value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetISTR(uint16_t wRegValue)
{
_SetISTR(wRegValue);
}
/*******************************************************************************
* Function Name : GetISTR
* Description : Returns the ISTR register value.
* Input : None.
* Output : None.
* Return : ISTR register Value
*******************************************************************************/
uint16_t GetISTR(void)
{
return(_GetISTR());
}
/*******************************************************************************
* Function Name : GetFNR
* Description : Returns the FNR register value.
* Input : None.
* Output : None.
* Return : FNR register Value
*******************************************************************************/
uint16_t GetFNR(void)
{
return(_GetFNR());
}
/*******************************************************************************
* Function Name : SetDADDR
* Description : Set the DADDR register value.
* Input : wRegValue: new register value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetDADDR(uint16_t wRegValue)
{
_SetDADDR(wRegValue);
}
/*******************************************************************************
* Function Name : GetDADDR
* Description : Returns the DADDR register value.
* Input : None.
* Output : None.
* Return : DADDR register Value
*******************************************************************************/
uint16_t GetDADDR(void)
{
return(_GetDADDR());
}
/*******************************************************************************
* Function Name : SetBTABLE
* Description : Set the BTABLE.
* Input : wRegValue: New register value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetBTABLE(uint16_t wRegValue)
{
_SetBTABLE(wRegValue);
}
/*******************************************************************************
* Function Name : GetBTABLE.
* Description : Returns the BTABLE register value.
* Input : None.
* Output : None.
* Return : BTABLE address.
*******************************************************************************/
uint16_t GetBTABLE(void)
{
return(_GetBTABLE());
}
/*******************************************************************************
* Function Name : SetENDPOINT
* Description : Setthe Endpoint register value.
* Input : bEpNum: Endpoint Number.
* wRegValue.
* Output : None.
* Return : None.
*******************************************************************************/
void SetENDPOINT(uint8_t bEpNum, uint16_t wRegValue)
{
_SetENDPOINT(bEpNum, wRegValue);
}
/*******************************************************************************
* Function Name : GetENDPOINT
* Description : Return the Endpoint register value.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint register value.
*******************************************************************************/
uint16_t GetENDPOINT(uint8_t bEpNum)
{
return(_GetENDPOINT(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPType
* Description : sets the type in the endpoint register.
* Input : bEpNum: Endpoint Number.
* wType: type definition.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPType(uint8_t bEpNum, uint16_t wType)
{
_SetEPType(bEpNum, wType);
}
/*******************************************************************************
* Function Name : GetEPType
* Description : Returns the endpoint type.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint Type
*******************************************************************************/
uint16_t GetEPType(uint8_t bEpNum)
{
return(_GetEPType(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxStatus
* Description : Set the status of Tx endpoint.
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxStatus(uint8_t bEpNum, uint16_t wState)
{
_SetEPTxStatus(bEpNum, wState);
}
/*******************************************************************************
* Function Name : SetEPRxStatus
* Description : Set the status of Rx endpoint.
* Input : bEpNum: Endpoint Number.
* wState: new state.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxStatus(uint8_t bEpNum, uint16_t wState)
{
_SetEPRxStatus(bEpNum, wState);
}
/*******************************************************************************
* Function Name : SetDouBleBuffEPStall
* Description : sets the status for Double Buffer Endpoint to STALL
* Input : bEpNum: Endpoint Number.
* bDir: Endpoint direction.
* Output : None.
* Return : None.
*******************************************************************************/
void SetDouBleBuffEPStall(uint8_t bEpNum, uint8_t bDir)
{
uint16_t Endpoint_DTOG_Status;
Endpoint_DTOG_Status = GetENDPOINT(bEpNum);
if (bDir == EP_DBUF_OUT)
{ /* OUT double buffered endpoint */
_SetENDPOINT(bEpNum, Endpoint_DTOG_Status & ~EPRX_DTOG1);
}
else if (bDir == EP_DBUF_IN)
{ /* IN double buffered endpoint */
_SetENDPOINT(bEpNum, Endpoint_DTOG_Status & ~EPTX_DTOG1);
}
}
/*******************************************************************************
* Function Name : GetEPTxStatus
* Description : Returns the endpoint Tx status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint TX Status
*******************************************************************************/
uint16_t GetEPTxStatus(uint8_t bEpNum)
{
return(_GetEPTxStatus(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPRxStatus
* Description : Returns the endpoint Rx status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint RX Status
*******************************************************************************/
uint16_t GetEPRxStatus(uint8_t bEpNum)
{
return(_GetEPRxStatus(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxValid
* Description : Valid the endpoint Tx Status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxValid(uint8_t bEpNum)
{
_SetEPTxStatus(bEpNum, EP_TX_VALID);
}
/*******************************************************************************
* Function Name : SetEPRxValid
* Description : Valid the endpoint Rx Status.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxValid(uint8_t bEpNum)
{
_SetEPRxStatus(bEpNum, EP_RX_VALID);
}
/*******************************************************************************
* Function Name : SetEP_KIND
* Description : Clear the EP_KIND bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEP_KIND(uint8_t bEpNum)
{
_SetEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : ClearEP_KIND
* Description : set the EP_KIND bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearEP_KIND(uint8_t bEpNum)
{
_ClearEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : Clear_Status_Out
* Description : Clear the Status Out of the related Endpoint
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void Clear_Status_Out(uint8_t bEpNum)
{
_ClearEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : Set_Status_Out
* Description : Set the Status Out of the related Endpoint
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void Set_Status_Out(uint8_t bEpNum)
{
_SetEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : SetEPDoubleBuff
* Description : Enable the double buffer feature for the endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDoubleBuff(uint8_t bEpNum)
{
_SetEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : ClearEPDoubleBuff
* Description : Disable the double buffer feature for the endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearEPDoubleBuff(uint8_t bEpNum)
{
_ClearEP_KIND(bEpNum);
}
/*******************************************************************************
* Function Name : GetTxStallStatus
* Description : Returns the Stall status of the Tx endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Tx Stall status.
*******************************************************************************/
uint16_t GetTxStallStatus(uint8_t bEpNum)
{
return(_GetTxStallStatus(bEpNum));
}
/*******************************************************************************
* Function Name : GetRxStallStatus
* Description : Returns the Stall status of the Rx endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Rx Stall status.
*******************************************************************************/
uint16_t GetRxStallStatus(uint8_t bEpNum)
{
return(_GetRxStallStatus(bEpNum));
}
/*******************************************************************************
* Function Name : ClearEP_CTR_RX
* Description : Clear the CTR_RX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearEP_CTR_RX(uint8_t bEpNum)
{
_ClearEP_CTR_RX(bEpNum);
}
/*******************************************************************************
* Function Name : ClearEP_CTR_TX
* Description : Clear the CTR_TX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearEP_CTR_TX(uint8_t bEpNum)
{
_ClearEP_CTR_TX(bEpNum);
}
/*******************************************************************************
* Function Name : ToggleDTOG_RX
* Description : Toggle the DTOG_RX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ToggleDTOG_RX(uint8_t bEpNum)
{
_ToggleDTOG_RX(bEpNum);
}
/*******************************************************************************
* Function Name : ToggleDTOG_TX
* Description : Toggle the DTOG_TX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ToggleDTOG_TX(uint8_t bEpNum)
{
_ToggleDTOG_TX(bEpNum);
}
/*******************************************************************************
* Function Name : ClearDTOG_RX.
* Description : Clear the DTOG_RX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearDTOG_RX(uint8_t bEpNum)
{
_ClearDTOG_RX(bEpNum);
}
/*******************************************************************************
* Function Name : ClearDTOG_TX.
* Description : Clear the DTOG_TX bit.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
void ClearDTOG_TX(uint8_t bEpNum)
{
_ClearDTOG_TX(bEpNum);
}
/*******************************************************************************
* Function Name : SetEPAddress
* Description : Set the endpoint address.
* Input : bEpNum: Endpoint Number.
* bAddr: New endpoint address.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPAddress(uint8_t bEpNum, uint8_t bAddr)
{
_SetEPAddress(bEpNum, bAddr);
}
/*******************************************************************************
* Function Name : GetEPAddress
* Description : Get the endpoint address.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint address.
*******************************************************************************/
uint8_t GetEPAddress(uint8_t bEpNum)
{
return(_GetEPAddress(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxAddr
* Description : Set the endpoint Tx buffer address.
* Input : bEpNum: Endpoint Number.
* wAddr: new address.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxAddr(uint8_t bEpNum, uint16_t wAddr)
{
_SetEPTxAddr(bEpNum, wAddr);
}
/*******************************************************************************
* Function Name : SetEPRxAddr
* Description : Set the endpoint Rx buffer address.
* Input : bEpNum: Endpoint Number.
* wAddr: new address.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxAddr(uint8_t bEpNum, uint16_t wAddr)
{
_SetEPRxAddr(bEpNum, wAddr);
}
/*******************************************************************************
* Function Name : GetEPTxAddr
* Description : Returns the endpoint Tx buffer address.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Rx buffer address.
*******************************************************************************/
uint16_t GetEPTxAddr(uint8_t bEpNum)
{
return(_GetEPTxAddr(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPRxAddr.
* Description : Returns the endpoint Rx buffer address.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Rx buffer address.
*******************************************************************************/
uint16_t GetEPRxAddr(uint8_t bEpNum)
{
return(_GetEPRxAddr(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPTxCount.
* Description : Set the Tx count.
* Input : bEpNum: Endpoint Number.
* wCount: new count value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPTxCount(uint8_t bEpNum, uint16_t wCount)
{
_SetEPTxCount(bEpNum, wCount);
}
/*******************************************************************************
* Function Name : SetEPCountRxReg.
* Description : Set the Count Rx Register value.
* Input : *pdwReg: point to the register.
* wCount: the new register value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPCountRxReg(uint32_t *pdwReg, uint16_t wCount)
{
_SetEPCountRxReg(dwReg, wCount);
}
/*******************************************************************************
* Function Name : SetEPRxCount
* Description : Set the Rx count.
* Input : bEpNum: Endpoint Number.
* wCount: the new count value.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPRxCount(uint8_t bEpNum, uint16_t wCount)
{
_SetEPRxCount(bEpNum, wCount);
}
/*******************************************************************************
* Function Name : GetEPTxCount
* Description : Get the Tx count.
* Input : bEpNum: Endpoint Number.
* Output : None
* Return : Tx count value.
*******************************************************************************/
uint16_t GetEPTxCount(uint8_t bEpNum)
{
return(_GetEPTxCount(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPRxCount
* Description : Get the Rx count.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Rx count value.
*******************************************************************************/
uint16_t GetEPRxCount(uint8_t bEpNum)
{
return(_GetEPRxCount(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPDblBuffAddr
* Description : Set the addresses of the buffer 0 and 1.
* Input : bEpNum: Endpoint Number.
* wBuf0Addr: new address of buffer 0.
* wBuf1Addr: new address of buffer 1.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuffAddr(uint8_t bEpNum, uint16_t wBuf0Addr, uint16_t wBuf1Addr)
{
_SetEPDblBuffAddr(bEpNum, wBuf0Addr, wBuf1Addr);
}
/*******************************************************************************
* Function Name : SetEPDblBuf0Addr
* Description : Set the Buffer 1 address.
* Input : bEpNum: Endpoint Number
* wBuf0Addr: new address.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuf0Addr(uint8_t bEpNum, uint16_t wBuf0Addr)
{
_SetEPDblBuf0Addr(bEpNum, wBuf0Addr);
}
/*******************************************************************************
* Function Name : SetEPDblBuf1Addr
* Description : Set the Buffer 1 address.
* Input : bEpNum: Endpoint Number
* wBuf1Addr: new address.
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuf1Addr(uint8_t bEpNum, uint16_t wBuf1Addr)
{
_SetEPDblBuf1Addr(bEpNum, wBuf1Addr);
}
/*******************************************************************************
* Function Name : GetEPDblBuf0Addr
* Description : Returns the address of the Buffer 0.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : None.
*******************************************************************************/
uint16_t GetEPDblBuf0Addr(uint8_t bEpNum)
{
return(_GetEPDblBuf0Addr(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPDblBuf1Addr
* Description : Returns the address of the Buffer 1.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Address of the Buffer 1.
*******************************************************************************/
uint16_t GetEPDblBuf1Addr(uint8_t bEpNum)
{
return(_GetEPDblBuf1Addr(bEpNum));
}
/*******************************************************************************
* Function Name : SetEPDblBuffCount
* Description : Set the number of bytes for a double Buffer
* endpoint.
* Input : bEpNum,bDir, wCount
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuffCount(uint8_t bEpNum, uint8_t bDir, uint16_t wCount)
{
_SetEPDblBuffCount(bEpNum, bDir, wCount);
}
/*******************************************************************************
* Function Name : SetEPDblBuf0Count
* Description : Set the number of bytes in the buffer 0 of a double Buffer
* endpoint.
* Input : bEpNum, bDir, wCount
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuf0Count(uint8_t bEpNum, uint8_t bDir, uint16_t wCount)
{
_SetEPDblBuf0Count(bEpNum, bDir, wCount);
}
/*******************************************************************************
* Function Name : SetEPDblBuf1Count
* Description : Set the number of bytes in the buffer 0 of a double Buffer
* endpoint.
* Input : bEpNum, bDir, wCount
* Output : None.
* Return : None.
*******************************************************************************/
void SetEPDblBuf1Count(uint8_t bEpNum, uint8_t bDir, uint16_t wCount)
{
_SetEPDblBuf1Count(bEpNum, bDir, wCount);
}
/*******************************************************************************
* Function Name : GetEPDblBuf0Count
* Description : Returns the number of byte received in the buffer 0 of a double
* Buffer endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint Buffer 0 count
*******************************************************************************/
uint16_t GetEPDblBuf0Count(uint8_t bEpNum)
{
return(_GetEPDblBuf0Count(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPDblBuf1Count
* Description : Returns the number of data received in the buffer 1 of a double
* Buffer endpoint.
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : Endpoint Buffer 1 count.
*******************************************************************************/
uint16_t GetEPDblBuf1Count(uint8_t bEpNum)
{
return(_GetEPDblBuf1Count(bEpNum));
}
/*******************************************************************************
* Function Name : GetEPDblBufDir
* Description : gets direction of the double buffered endpoint
* Input : bEpNum: Endpoint Number.
* Output : None.
* Return : EP_DBUF_OUT, EP_DBUF_IN,
* EP_DBUF_ERR if the endpoint counter not yet programmed.
*******************************************************************************/
EP_DBUF_DIR GetEPDblBufDir(uint8_t bEpNum)
{
if ((uint16_t)(*_pEPRxCount(bEpNum) & 0xFC00) != 0)
return(EP_DBUF_OUT);
else if (((uint16_t)(*_pEPTxCount(bEpNum)) & 0x03FF) != 0)
return(EP_DBUF_IN);
else
return(EP_DBUF_ERR);
}
/*******************************************************************************
* Function Name : FreeUserBuffer
* Description : free buffer used from the application realizing it to the line
toggles bit SW_BUF in the double buffered endpoint register
* Input : bEpNum, bDir
* Output : None.
* Return : None.
*******************************************************************************/
void FreeUserBuffer(uint8_t bEpNum, uint8_t bDir)
{
if (bDir == EP_DBUF_OUT)
{ /* OUT double buffered endpoint */
_ToggleDTOG_TX(bEpNum);
}
else if (bDir == EP_DBUF_IN)
{ /* IN double buffered endpoint */
_ToggleDTOG_RX(bEpNum);
}
}
/*******************************************************************************
* Function Name : ToWord
* Description : merge two byte in a word.
* Input : bh: byte high, bl: bytes low.
* Output : None.
* Return : resulted word.
*******************************************************************************/
uint16_t ToWord(uint8_t bh, uint8_t bl)
{
uint16_t wRet;
wRet = (uint16_t)bl | ((uint16_t)bh << 8);
return(wRet);
}
/*******************************************************************************
* Function Name : ByteSwap
* Description : Swap two byte in a word.
* Input : wSwW: word to Swap.
* Output : None.
* Return : resulted word.
*******************************************************************************/
uint16_t ByteSwap(uint16_t wSwW)
{
uint8_t bTemp;
uint16_t wRet;
bTemp = (uint8_t)(wSwW & 0xff);
wRet = (wSwW >> 8) | ((uint16_t)bTemp << 8);
return(wRet);
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_regs.c
|
C
|
asf20
| 29,236
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_core.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Standard protocol processing (USB v2.0)
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define ValBit(VAR,Place) (VAR & (1 << Place))
#define SetBit(VAR,Place) (VAR |= (1 << Place))
#define ClrBit(VAR,Place) (VAR &= ((1 << Place) ^ 255))
#ifdef STM32F10X_CL
#define Send0LengthData() {PCD_EP_Write (0, 0, 0) ; vSetEPTxStatus(EP_TX_VALID);}
#else
#define Send0LengthData() { _SetEPTxCount(ENDP0, 0); \
vSetEPTxStatus(EP_TX_VALID); \
}
#endif /* STM32F10X_CL */
#define vSetEPRxStatus(st) (SaveRState = st)
#define vSetEPTxStatus(st) (SaveTState = st)
#define USB_StatusIn() Send0LengthData()
#define USB_StatusOut() vSetEPRxStatus(EP_RX_VALID)
#define StatusInfo0 StatusInfo.bw.bb1 /* Reverse bb0 & bb1 */
#define StatusInfo1 StatusInfo.bw.bb0
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint16_t_uint8_t StatusInfo;
bool Data_Mul_MaxPacketSize = FALSE;
/* Private function prototypes -----------------------------------------------*/
static void DataStageOut(void);
static void DataStageIn(void);
static void NoData_Setup0(void);
static void Data_Setup0(void);
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : Standard_GetConfiguration.
* Description : Return the current configuration variable address.
* Input : Length - How many bytes are needed.
* Output : None.
* Return : Return 1 , if the request is invalid when "Length" is 0.
* Return "Buffer" if the "Length" is not 0.
*******************************************************************************/
uint8_t *Standard_GetConfiguration(uint16_t Length)
{
if (Length == 0)
{
pInformation->Ctrl_Info.Usb_wLength =
sizeof(pInformation->Current_Configuration);
return 0;
}
pUser_Standard_Requests->User_GetConfiguration();
return (uint8_t *)&pInformation->Current_Configuration;
}
/*******************************************************************************
* Function Name : Standard_SetConfiguration.
* Description : This routine is called to set the configuration value
* Then each class should configure device themself.
* Input : None.
* Output : None.
* Return : Return USB_SUCCESS, if the request is performed.
* Return USB_UNSUPPORT, if the request is invalid.
*******************************************************************************/
RESULT Standard_SetConfiguration(void)
{
if ((pInformation->USBwValue0 <=
Device_Table.Total_Configuration) && (pInformation->USBwValue1 == 0)
&& (pInformation->USBwIndex == 0)) /*call Back usb spec 2.0*/
{
pInformation->Current_Configuration = pInformation->USBwValue0;
pUser_Standard_Requests->User_SetConfiguration();
return USB_SUCCESS;
}
else
{
return USB_UNSUPPORT;
}
}
/*******************************************************************************
* Function Name : Standard_GetInterface.
* Description : Return the Alternate Setting of the current interface.
* Input : Length - How many bytes are needed.
* Output : None.
* Return : Return 0, if the request is invalid when "Length" is 0.
* Return "Buffer" if the "Length" is not 0.
*******************************************************************************/
uint8_t *Standard_GetInterface(uint16_t Length)
{
if (Length == 0)
{
pInformation->Ctrl_Info.Usb_wLength =
sizeof(pInformation->Current_AlternateSetting);
return 0;
}
pUser_Standard_Requests->User_GetInterface();
return (uint8_t *)&pInformation->Current_AlternateSetting;
}
/*******************************************************************************
* Function Name : Standard_SetInterface.
* Description : This routine is called to set the interface.
* Then each class should configure the interface them self.
* Input : None.
* Output : None.
* Return : - Return USB_SUCCESS, if the request is performed.
* - Return USB_UNSUPPORT, if the request is invalid.
*******************************************************************************/
RESULT Standard_SetInterface(void)
{
RESULT Re;
/*Test if the specified Interface and Alternate Setting are supported by
the application Firmware*/
Re = (*pProperty->Class_Get_Interface_Setting)(pInformation->USBwIndex0, pInformation->USBwValue0);
if (pInformation->Current_Configuration != 0)
{
if ((Re != USB_SUCCESS) || (pInformation->USBwIndex1 != 0)
|| (pInformation->USBwValue1 != 0))
{
return USB_UNSUPPORT;
}
else if (Re == USB_SUCCESS)
{
pUser_Standard_Requests->User_SetInterface();
pInformation->Current_Interface = pInformation->USBwIndex0;
pInformation->Current_AlternateSetting = pInformation->USBwValue0;
return USB_SUCCESS;
}
}
return USB_UNSUPPORT;
}
/*******************************************************************************
* Function Name : Standard_GetStatus.
* Description : Copy the device request data to "StatusInfo buffer".
* Input : - Length - How many bytes are needed.
* Output : None.
* Return : Return 0, if the request is at end of data block,
* or is invalid when "Length" is 0.
*******************************************************************************/
uint8_t *Standard_GetStatus(uint16_t Length)
{
if (Length == 0)
{
pInformation->Ctrl_Info.Usb_wLength = 2;
return 0;
}
/* Reset Status Information */
StatusInfo.w = 0;
if (Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT))
{
/*Get Device Status */
uint8_t Feature = pInformation->Current_Feature;
/* Remote Wakeup enabled */
if (ValBit(Feature, 5))
{
SetBit(StatusInfo0, 1);
}
else
{
ClrBit(StatusInfo0, 1);
}
/* Bus-powered */
if (ValBit(Feature, 6))
{
SetBit(StatusInfo0, 0);
}
else /* Self-powered */
{
ClrBit(StatusInfo0, 0);
}
}
/*Interface Status*/
else if (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT))
{
return (uint8_t *)&StatusInfo;
}
/*Get EndPoint Status*/
else if (Type_Recipient == (STANDARD_REQUEST | ENDPOINT_RECIPIENT))
{
uint8_t Related_Endpoint;
uint8_t wIndex0 = pInformation->USBwIndex0;
Related_Endpoint = (wIndex0 & 0x0f);
if (ValBit(wIndex0, 7))
{
/* IN endpoint */
if (_GetTxStallStatus(Related_Endpoint))
{
SetBit(StatusInfo0, 0); /* IN Endpoint stalled */
}
}
else
{
/* OUT endpoint */
if (_GetRxStallStatus(Related_Endpoint))
{
SetBit(StatusInfo0, 0); /* OUT Endpoint stalled */
}
}
}
else
{
return NULL;
}
pUser_Standard_Requests->User_GetStatus();
return (uint8_t *)&StatusInfo;
}
/*******************************************************************************
* Function Name : Standard_ClearFeature.
* Description : Clear or disable a specific feature.
* Input : None.
* Output : None.
* Return : - Return USB_SUCCESS, if the request is performed.
* - Return USB_UNSUPPORT, if the request is invalid.
*******************************************************************************/
RESULT Standard_ClearFeature(void)
{
uint32_t Type_Rec = Type_Recipient;
uint32_t Status;
if (Type_Rec == (STANDARD_REQUEST | DEVICE_RECIPIENT))
{/*Device Clear Feature*/
ClrBit(pInformation->Current_Feature, 5);
return USB_SUCCESS;
}
else if (Type_Rec == (STANDARD_REQUEST | ENDPOINT_RECIPIENT))
{/*EndPoint Clear Feature*/
DEVICE* pDev;
uint32_t Related_Endpoint;
uint32_t wIndex0;
uint32_t rEP;
if ((pInformation->USBwValue != ENDPOINT_STALL)
|| (pInformation->USBwIndex1 != 0))
{
return USB_UNSUPPORT;
}
pDev = &Device_Table;
wIndex0 = pInformation->USBwIndex0;
rEP = wIndex0 & ~0x80;
Related_Endpoint = ENDP0 + rEP;
if (ValBit(pInformation->USBwIndex0, 7))
{
/*Get Status of endpoint & stall the request if the related_ENdpoint
is Disabled*/
Status = _GetEPTxStatus(Related_Endpoint);
}
else
{
Status = _GetEPRxStatus(Related_Endpoint);
}
if ((rEP >= pDev->Total_Endpoint) || (Status == 0)
|| (pInformation->Current_Configuration == 0))
{
return USB_UNSUPPORT;
}
if (wIndex0 & 0x80)
{
/* IN endpoint */
if (_GetTxStallStatus(Related_Endpoint ))
{
#ifndef STM32F10X_CL
ClearDTOG_TX(Related_Endpoint);
#endif /* STM32F10X_CL */
SetEPTxStatus(Related_Endpoint, EP_TX_VALID);
}
}
else
{
/* OUT endpoint */
if (_GetRxStallStatus(Related_Endpoint))
{
if (Related_Endpoint == ENDP0)
{
/* After clear the STALL, enable the default endpoint receiver */
SetEPRxCount(Related_Endpoint, Device_Property.MaxPacketSize);
_SetEPRxStatus(Related_Endpoint, EP_RX_VALID);
}
else
{
#ifndef STM32F10X_CL
ClearDTOG_RX(Related_Endpoint);
#endif /* STM32F10X_CL */
_SetEPRxStatus(Related_Endpoint, EP_RX_VALID);
}
}
}
pUser_Standard_Requests->User_ClearFeature();
return USB_SUCCESS;
}
return USB_UNSUPPORT;
}
/*******************************************************************************
* Function Name : Standard_SetEndPointFeature
* Description : Set or enable a specific feature of EndPoint
* Input : None.
* Output : None.
* Return : - Return USB_SUCCESS, if the request is performed.
* - Return USB_UNSUPPORT, if the request is invalid.
*******************************************************************************/
RESULT Standard_SetEndPointFeature(void)
{
uint32_t wIndex0;
uint32_t Related_Endpoint;
uint32_t rEP;
uint32_t Status;
wIndex0 = pInformation->USBwIndex0;
rEP = wIndex0 & ~0x80;
Related_Endpoint = ENDP0 + rEP;
if (ValBit(pInformation->USBwIndex0, 7))
{
/* get Status of endpoint & stall the request if the related_ENdpoint
is Disabled*/
Status = _GetEPTxStatus(Related_Endpoint);
}
else
{
Status = _GetEPRxStatus(Related_Endpoint);
}
if (Related_Endpoint >= Device_Table.Total_Endpoint
|| pInformation->USBwValue != 0 || Status == 0
|| pInformation->Current_Configuration == 0)
{
return USB_UNSUPPORT;
}
else
{
if (wIndex0 & 0x80)
{
/* IN endpoint */
_SetEPTxStatus(Related_Endpoint, EP_TX_STALL);
}
else
{
/* OUT endpoint */
_SetEPRxStatus(Related_Endpoint, EP_RX_STALL);
}
}
pUser_Standard_Requests->User_SetEndPointFeature();
return USB_SUCCESS;
}
/*******************************************************************************
* Function Name : Standard_SetDeviceFeature.
* Description : Set or enable a specific feature of Device.
* Input : None.
* Output : None.
* Return : - Return USB_SUCCESS, if the request is performed.
* - Return USB_UNSUPPORT, if the request is invalid.
*******************************************************************************/
RESULT Standard_SetDeviceFeature(void)
{
SetBit(pInformation->Current_Feature, 5);
pUser_Standard_Requests->User_SetDeviceFeature();
return USB_SUCCESS;
}
/*******************************************************************************
* Function Name : Standard_GetDescriptorData.
* Description : Standard_GetDescriptorData is used for descriptors transfer.
* : This routine is used for the descriptors resident in Flash
* or RAM
* pDesc can be in either Flash or RAM
* The purpose of this routine is to have a versatile way to
* response descriptors request. It allows user to generate
* certain descriptors with software or read descriptors from
* external storage part by part.
* Input : - Length - Length of the data in this transfer.
* - pDesc - A pointer points to descriptor struct.
* The structure gives the initial address of the descriptor and
* its original size.
* Output : None.
* Return : Address of a part of the descriptor pointed by the Usb_
* wOffset The buffer pointed by this address contains at least
* Length bytes.
*******************************************************************************/
uint8_t *Standard_GetDescriptorData(uint16_t Length, ONE_DESCRIPTOR *pDesc)
{
uint32_t wOffset;
wOffset = pInformation->Ctrl_Info.Usb_wOffset;
if (Length == 0)
{
pInformation->Ctrl_Info.Usb_wLength = pDesc->Descriptor_Size - wOffset;
return 0;
}
return pDesc->Descriptor + wOffset;
}
/*******************************************************************************
* Function Name : DataStageOut.
* Description : Data stage of a Control Write Transfer.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void DataStageOut(void)
{
ENDPOINT_INFO *pEPinfo = &pInformation->Ctrl_Info;
uint32_t save_rLength;
save_rLength = pEPinfo->Usb_rLength;
if (pEPinfo->CopyData && save_rLength)
{
uint8_t *Buffer;
uint32_t Length;
Length = pEPinfo->PacketSize;
if (Length > save_rLength)
{
Length = save_rLength;
}
Buffer = (*pEPinfo->CopyData)(Length);
pEPinfo->Usb_rLength -= Length;
pEPinfo->Usb_rOffset += Length;
#ifdef STM32F10X_CL
PCD_EP_Read(ENDP0, Buffer, Length);
#else
PMAToUserBufferCopy(Buffer, GetEPRxAddr(ENDP0), Length);
#endif /* STM32F10X_CL */
}
if (pEPinfo->Usb_rLength != 0)
{
vSetEPRxStatus(EP_RX_VALID);/* re-enable for next data reception */
SetEPTxCount(ENDP0, 0);
vSetEPTxStatus(EP_TX_VALID);/* Expect the host to abort the data OUT stage */
}
/* Set the next State*/
if (pEPinfo->Usb_rLength >= pEPinfo->PacketSize)
{
pInformation->ControlState = OUT_DATA;
}
else
{
if (pEPinfo->Usb_rLength > 0)
{
pInformation->ControlState = LAST_OUT_DATA;
}
else if (pEPinfo->Usb_rLength == 0)
{
pInformation->ControlState = WAIT_STATUS_IN;
USB_StatusIn();
}
}
}
/*******************************************************************************
* Function Name : DataStageIn.
* Description : Data stage of a Control Read Transfer.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void DataStageIn(void)
{
ENDPOINT_INFO *pEPinfo = &pInformation->Ctrl_Info;
uint32_t save_wLength = pEPinfo->Usb_wLength;
uint32_t ControlState = pInformation->ControlState;
uint8_t *DataBuffer;
uint32_t Length;
if ((save_wLength == 0) && (ControlState == LAST_IN_DATA))
{
if(Data_Mul_MaxPacketSize == TRUE)
{
/* No more data to send and empty packet */
Send0LengthData();
ControlState = LAST_IN_DATA;
Data_Mul_MaxPacketSize = FALSE;
}
else
{
/* No more data to send so STALL the TX Status*/
ControlState = WAIT_STATUS_OUT;
#ifdef STM32F10X_CL
PCD_EP_Read (ENDP0, 0, 0);
#endif /* STM32F10X_CL */
#ifndef STM32F10X_CL
vSetEPTxStatus(EP_TX_STALL);
#endif /* STM32F10X_CL */
}
goto Expect_Status_Out;
}
Length = pEPinfo->PacketSize;
ControlState = (save_wLength <= Length) ? LAST_IN_DATA : IN_DATA;
if (Length > save_wLength)
{
Length = save_wLength;
}
DataBuffer = (*pEPinfo->CopyData)(Length);
#ifdef STM32F10X_CL
PCD_EP_Write (ENDP0, DataBuffer, Length);
#else
UserToPMABufferCopy(DataBuffer, GetEPTxAddr(ENDP0), Length);
#endif /* STM32F10X_CL */
SetEPTxCount(ENDP0, Length);
pEPinfo->Usb_wLength -= Length;
pEPinfo->Usb_wOffset += Length;
vSetEPTxStatus(EP_TX_VALID);
USB_StatusOut();/* Expect the host to abort the data IN stage */
Expect_Status_Out:
pInformation->ControlState = ControlState;
}
/*******************************************************************************
* Function Name : NoData_Setup0.
* Description : Proceed the processing of setup request without data stage.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void NoData_Setup0(void)
{
RESULT Result = USB_UNSUPPORT;
uint32_t RequestNo = pInformation->USBbRequest;
uint32_t ControlState;
if (Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT))
{
/* Device Request*/
/* SET_CONFIGURATION*/
if (RequestNo == SET_CONFIGURATION)
{
Result = Standard_SetConfiguration();
}
/*SET ADDRESS*/
else if (RequestNo == SET_ADDRESS)
{
if ((pInformation->USBwValue0 > 127) || (pInformation->USBwValue1 != 0)
|| (pInformation->USBwIndex != 0)
|| (pInformation->Current_Configuration != 0))
/* Device Address should be 127 or less*/
{
ControlState = STALLED;
goto exit_NoData_Setup0;
}
else
{
Result = USB_SUCCESS;
#ifdef STM32F10X_CL
SetDeviceAddress(pInformation->USBwValue0);
#endif /* STM32F10X_CL */
}
}
/*SET FEATURE for Device*/
else if (RequestNo == SET_FEATURE)
{
if ((pInformation->USBwValue0 == DEVICE_REMOTE_WAKEUP)
&& (pInformation->USBwIndex == 0)
&& (ValBit(pInformation->Current_Feature, 5)))
{
Result = Standard_SetDeviceFeature();
}
else
{
Result = USB_UNSUPPORT;
}
}
/*Clear FEATURE for Device */
else if (RequestNo == CLEAR_FEATURE)
{
if (pInformation->USBwValue0 == DEVICE_REMOTE_WAKEUP
&& pInformation->USBwIndex == 0
&& ValBit(pInformation->Current_Feature, 5))
{
Result = Standard_ClearFeature();
}
else
{
Result = USB_UNSUPPORT;
}
}
}
/* Interface Request*/
else if (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT))
{
/*SET INTERFACE*/
if (RequestNo == SET_INTERFACE)
{
Result = Standard_SetInterface();
}
}
/* EndPoint Request*/
else if (Type_Recipient == (STANDARD_REQUEST | ENDPOINT_RECIPIENT))
{
/*CLEAR FEATURE for EndPoint*/
if (RequestNo == CLEAR_FEATURE)
{
Result = Standard_ClearFeature();
}
/* SET FEATURE for EndPoint*/
else if (RequestNo == SET_FEATURE)
{
Result = Standard_SetEndPointFeature();
}
}
else
{
Result = USB_UNSUPPORT;
}
if (Result != USB_SUCCESS)
{
Result = (*pProperty->Class_NoData_Setup)(RequestNo);
if (Result == USB_NOT_READY)
{
ControlState = PAUSE;
goto exit_NoData_Setup0;
}
}
if (Result != USB_SUCCESS)
{
ControlState = STALLED;
goto exit_NoData_Setup0;
}
ControlState = WAIT_STATUS_IN;/* After no data stage SETUP */
USB_StatusIn();
exit_NoData_Setup0:
pInformation->ControlState = ControlState;
return;
}
/*******************************************************************************
* Function Name : Data_Setup0.
* Description : Proceed the processing of setup request with data stage.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void Data_Setup0(void)
{
uint8_t *(*CopyRoutine)(uint16_t);
RESULT Result;
uint32_t Request_No = pInformation->USBbRequest;
uint32_t Related_Endpoint, Reserved;
uint32_t wOffset, Status;
CopyRoutine = NULL;
wOffset = 0;
/*GET DESCRIPTOR*/
if (Request_No == GET_DESCRIPTOR)
{
if (Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT))
{
uint8_t wValue1 = pInformation->USBwValue1;
if (wValue1 == DEVICE_DESCRIPTOR)
{
CopyRoutine = pProperty->GetDeviceDescriptor;
}
else if (wValue1 == CONFIG_DESCRIPTOR)
{
CopyRoutine = pProperty->GetConfigDescriptor;
}
else if (wValue1 == STRING_DESCRIPTOR)
{
CopyRoutine = pProperty->GetStringDescriptor;
} /* End of GET_DESCRIPTOR */
}
}
/*GET STATUS*/
else if ((Request_No == GET_STATUS) && (pInformation->USBwValue == 0)
&& (pInformation->USBwLength == 0x0002)
&& (pInformation->USBwIndex1 == 0))
{
/* GET STATUS for Device*/
if ((Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT))
&& (pInformation->USBwIndex == 0))
{
CopyRoutine = Standard_GetStatus;
}
/* GET STATUS for Interface*/
else if (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT))
{
if (((*pProperty->Class_Get_Interface_Setting)(pInformation->USBwIndex0, 0) == USB_SUCCESS)
&& (pInformation->Current_Configuration != 0))
{
CopyRoutine = Standard_GetStatus;
}
}
/* GET STATUS for EndPoint*/
else if (Type_Recipient == (STANDARD_REQUEST | ENDPOINT_RECIPIENT))
{
Related_Endpoint = (pInformation->USBwIndex0 & 0x0f);
Reserved = pInformation->USBwIndex0 & 0x70;
if (ValBit(pInformation->USBwIndex0, 7))
{
/*Get Status of endpoint & stall the request if the related_ENdpoint
is Disabled*/
Status = _GetEPTxStatus(Related_Endpoint);
}
else
{
Status = _GetEPRxStatus(Related_Endpoint);
}
if ((Related_Endpoint < Device_Table.Total_Endpoint) && (Reserved == 0)
&& (Status != 0))
{
CopyRoutine = Standard_GetStatus;
}
}
}
/*GET CONFIGURATION*/
else if (Request_No == GET_CONFIGURATION)
{
if (Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT))
{
CopyRoutine = Standard_GetConfiguration;
}
}
/*GET INTERFACE*/
else if (Request_No == GET_INTERFACE)
{
if ((Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT))
&& (pInformation->Current_Configuration != 0) && (pInformation->USBwValue == 0)
&& (pInformation->USBwIndex1 == 0) && (pInformation->USBwLength == 0x0001)
&& ((*pProperty->Class_Get_Interface_Setting)(pInformation->USBwIndex0, 0) == USB_SUCCESS))
{
CopyRoutine = Standard_GetInterface;
}
}
if (CopyRoutine)
{
pInformation->Ctrl_Info.Usb_wOffset = wOffset;
pInformation->Ctrl_Info.CopyData = CopyRoutine;
/* sb in the original the cast to word was directly */
/* now the cast is made step by step */
(*CopyRoutine)(0);
Result = USB_SUCCESS;
}
else
{
Result = (*pProperty->Class_Data_Setup)(pInformation->USBbRequest);
if (Result == USB_NOT_READY)
{
pInformation->ControlState = PAUSE;
return;
}
}
if (pInformation->Ctrl_Info.Usb_wLength == 0xFFFF)
{
/* Data is not ready, wait it */
pInformation->ControlState = PAUSE;
return;
}
if ((Result == USB_UNSUPPORT) || (pInformation->Ctrl_Info.Usb_wLength == 0))
{
/* Unsupported request */
pInformation->ControlState = STALLED;
return;
}
if (ValBit(pInformation->USBbmRequestType, 7))
{
/* Device ==> Host */
__IO uint32_t wLength = pInformation->USBwLength;
/* Restrict the data length to be the one host asks for */
if (pInformation->Ctrl_Info.Usb_wLength > wLength)
{
pInformation->Ctrl_Info.Usb_wLength = wLength;
}
else if (pInformation->Ctrl_Info.Usb_wLength < pInformation->USBwLength)
{
if (pInformation->Ctrl_Info.Usb_wLength < pProperty->MaxPacketSize)
{
Data_Mul_MaxPacketSize = FALSE;
}
else if ((pInformation->Ctrl_Info.Usb_wLength % pProperty->MaxPacketSize) == 0)
{
Data_Mul_MaxPacketSize = TRUE;
}
}
pInformation->Ctrl_Info.PacketSize = pProperty->MaxPacketSize;
DataStageIn();
}
else
{
pInformation->ControlState = OUT_DATA;
vSetEPRxStatus(EP_RX_VALID); /* enable for next data reception */
}
return;
}
/*******************************************************************************
* Function Name : Setup0_Process
* Description : Get the device request data and dispatch to individual process.
* Input : None.
* Output : None.
* Return : Post0_Process.
*******************************************************************************/
uint8_t Setup0_Process(void)
{
union
{
uint8_t* b;
uint16_t* w;
} pBuf;
#ifdef STM32F10X_CL
USB_OTG_EP *ep;
uint16_t offset = 0;
ep = PCD_GetOutEP(ENDP0);
pBuf.b = ep->xfer_buff;
#else
uint16_t offset = 1;
pBuf.b = PMAAddr + (uint8_t *)(_GetEPRxAddr(ENDP0) * 2); /* *2 for 32 bits addr */
#endif /* STM32F10X_CL */
if (pInformation->ControlState != PAUSE)
{
pInformation->USBbmRequestType = *pBuf.b++; /* bmRequestType */
pInformation->USBbRequest = *pBuf.b++; /* bRequest */
pBuf.w += offset; /* word not accessed because of 32 bits addressing */
pInformation->USBwValue = ByteSwap(*pBuf.w++); /* wValue */
pBuf.w += offset; /* word not accessed because of 32 bits addressing */
pInformation->USBwIndex = ByteSwap(*pBuf.w++); /* wIndex */
pBuf.w += offset; /* word not accessed because of 32 bits addressing */
pInformation->USBwLength = *pBuf.w; /* wLength */
}
pInformation->ControlState = SETTING_UP;
if (pInformation->USBwLength == 0)
{
/* Setup with no data stage */
NoData_Setup0();
}
else
{
/* Setup with data stage */
Data_Setup0();
}
return Post0_Process();
}
/*******************************************************************************
* Function Name : In0_Process
* Description : Process the IN token on all default endpoint.
* Input : None.
* Output : None.
* Return : Post0_Process.
*******************************************************************************/
uint8_t In0_Process(void)
{
uint32_t ControlState = pInformation->ControlState;
if ((ControlState == IN_DATA) || (ControlState == LAST_IN_DATA))
{
DataStageIn();
/* ControlState may be changed outside the function */
ControlState = pInformation->ControlState;
}
else if (ControlState == WAIT_STATUS_IN)
{
if ((pInformation->USBbRequest == SET_ADDRESS) &&
(Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT)))
{
SetDeviceAddress(pInformation->USBwValue0);
pUser_Standard_Requests->User_SetDeviceAddress();
}
(*pProperty->Process_Status_IN)();
ControlState = STALLED;
}
else
{
ControlState = STALLED;
}
pInformation->ControlState = ControlState;
return Post0_Process();
}
/*******************************************************************************
* Function Name : Out0_Process
* Description : Process the OUT token on all default endpoint.
* Input : None.
* Output : None.
* Return : Post0_Process.
*******************************************************************************/
uint8_t Out0_Process(void)
{
uint32_t ControlState = pInformation->ControlState;
if ((ControlState == IN_DATA) || (ControlState == LAST_IN_DATA))
{
/* host aborts the transfer before finish */
ControlState = STALLED;
}
else if ((ControlState == OUT_DATA) || (ControlState == LAST_OUT_DATA))
{
DataStageOut();
ControlState = pInformation->ControlState; /* may be changed outside the function */
}
else if (ControlState == WAIT_STATUS_OUT)
{
(*pProperty->Process_Status_OUT)();
#ifndef STM32F10X_CL
ControlState = STALLED;
#endif /* STM32F10X_CL */
}
/* Unexpect state, STALL the endpoint */
else
{
ControlState = STALLED;
}
pInformation->ControlState = ControlState;
return Post0_Process();
}
/*******************************************************************************
* Function Name : Post0_Process
* Description : Stall the Endpoint 0 in case of error.
* Input : None.
* Output : None.
* Return : - 0 if the control State is in PAUSE
* - 1 if not.
*******************************************************************************/
uint8_t Post0_Process(void)
{
#ifdef STM32F10X_CL
USB_OTG_EP *ep;
#endif /* STM32F10X_CL */
SetEPRxCount(ENDP0, Device_Property.MaxPacketSize);
if (pInformation->ControlState == STALLED)
{
vSetEPRxStatus(EP_RX_STALL);
vSetEPTxStatus(EP_TX_STALL);
}
#ifdef STM32F10X_CL
else if ((pInformation->ControlState == OUT_DATA) ||
(pInformation->ControlState == WAIT_STATUS_OUT))
{
ep = PCD_GetInEP(0);
ep->is_in = 0;
OTGD_FS_EP0StartXfer(ep);
vSetEPTxStatus(EP_TX_VALID);
}
else if ((pInformation->ControlState == IN_DATA) ||
(pInformation->ControlState == WAIT_STATUS_IN))
{
ep = PCD_GetInEP(0);
ep->is_in = 1;
OTGD_FS_EP0StartXfer(ep);
}
#endif /* STM32F10X_CL */
return (pInformation->ControlState == PAUSE);
}
/*******************************************************************************
* Function Name : SetDeviceAddress.
* Description : Set the device and all the used Endpoints addresses.
* Input : - Val: device adress.
* Output : None.
* Return : None.
*******************************************************************************/
void SetDeviceAddress(uint8_t Val)
{
#ifdef STM32F10X_CL
PCD_EP_SetAddress ((uint8_t)Val);
#else
uint32_t i;
uint32_t nEP = Device_Table.Total_Endpoint;
/* set address in every used endpoint */
for (i = 0; i < nEP; i++)
{
_SetEPAddress((uint8_t)i, (uint8_t)i);
} /* for */
_SetDADDR(Val | DADDR_EF); /* set device address and enable function */
#endif /* STM32F10X_CL */
}
/*******************************************************************************
* Function Name : NOP_Process
* Description : No operation function.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void NOP_Process(void)
{
}
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_core.c
|
C
|
asf20
| 32,845
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_mem.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Utility functions for memory transfers to/from PMA
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifndef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : UserToPMABufferCopy
* Description : Copy a buffer from user memory area to packet memory area (PMA)
* Input : - pbUsrBuf: pointer to user memory area.
* - wPMABufAddr: address into PMA.
* - wNBytes: no. of bytes to be copied.
* Output : None.
* Return : None .
*******************************************************************************/
void UserToPMABufferCopy(uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = (wNBytes + 1) >> 1; /* n = (wNBytes + 1) / 2 */
uint32_t i, temp1, temp2;
uint16_t *pdwVal;
pdwVal = (uint16_t *)(wPMABufAddr * 2 + PMAAddr);
for (i = n; i != 0; i--)
{
temp1 = (uint16_t) * pbUsrBuf;
pbUsrBuf++;
temp2 = temp1 | (uint16_t) * pbUsrBuf << 8;
*pdwVal++ = temp2;
pdwVal++;
pbUsrBuf++;
}
}
/*******************************************************************************
* Function Name : PMAToUserBufferCopy
* Description : Copy a buffer from user memory area to packet memory area (PMA)
* Input : - pbUsrBuf = pointer to user memory area.
* - wPMABufAddr = address into PMA.
* - wNBytes = no. of bytes to be copied.
* Output : None.
* Return : None.
*******************************************************************************/
void PMAToUserBufferCopy(uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes)
{
uint32_t n = (wNBytes + 1) >> 1;/* /2*/
uint32_t i;
uint32_t *pdwVal;
pdwVal = (uint32_t *)(wPMABufAddr * 2 + PMAAddr);
for (i = n; i != 0; i--)
{
*(uint16_t*)pbUsrBuf++ = *pdwVal++;
pbUsrBuf++;
}
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_mem.c
|
C
|
asf20
| 3,553
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_int.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Endpoint CTR (Low and High) interrupt's service routines
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifndef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
__IO uint16_t SaveRState;
__IO uint16_t SaveTState;
/* Extern variables ----------------------------------------------------------*/
extern void (*pEpInt_IN[7])(void); /* Handles IN interrupts */
extern void (*pEpInt_OUT[7])(void); /* Handles OUT interrupts */
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : CTR_LP.
* Description : Low priority Endpoint Correct Transfer interrupt's service
* routine.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void CTR_LP(void)
{
__IO uint16_t wEPVal = 0;
/* stay in loop while pending ints */
while (((wIstr = _GetISTR()) & ISTR_CTR) != 0)
{
/* extract highest priority endpoint number */
EPindex = (uint8_t)(wIstr & ISTR_EP_ID);
if (EPindex == 0)
{
/* Decode and service control endpoint interrupt */
/* calling related service routine */
/* (Setup0_Process, In0_Process, Out0_Process) */
/* save RX & TX status */
/* and set both to NAK */
SaveRState = _GetENDPOINT(ENDP0);
SaveTState = SaveRState & EPTX_STAT;
SaveRState &= EPRX_STAT;
_SetEPRxTxStatus(ENDP0,EP_RX_NAK,EP_TX_NAK);
/* DIR bit = origin of the interrupt */
if ((wIstr & ISTR_DIR) == 0)
{
/* DIR = 0 */
/* DIR = 0 => IN int */
/* DIR = 0 implies that (EP_CTR_TX = 1) always */
_ClearEP_CTR_TX(ENDP0);
In0_Process();
/* before terminate set Tx & Rx status */
_SetEPRxTxStatus(ENDP0,SaveRState,SaveTState);
return;
}
else
{
/* DIR = 1 */
/* DIR = 1 & CTR_RX => SETUP or OUT int */
/* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */
wEPVal = _GetENDPOINT(ENDP0);
if ((wEPVal &EP_SETUP) != 0)
{
_ClearEP_CTR_RX(ENDP0); /* SETUP bit kept frozen while CTR_RX = 1 */
Setup0_Process();
/* before terminate set Tx & Rx status */
_SetEPRxTxStatus(ENDP0,SaveRState,SaveTState);
return;
}
else if ((wEPVal & EP_CTR_RX) != 0)
{
_ClearEP_CTR_RX(ENDP0);
Out0_Process();
/* before terminate set Tx & Rx status */
_SetEPRxTxStatus(ENDP0,SaveRState,SaveTState);
return;
}
}
}/* if(EPindex == 0) */
else
{
/* Decode and service non control endpoints interrupt */
/* process related endpoint register */
wEPVal = _GetENDPOINT(EPindex);
if ((wEPVal & EP_CTR_RX) != 0)
{
/* clear int flag */
_ClearEP_CTR_RX(EPindex);
/* call OUT service function */
(*pEpInt_OUT[EPindex-1])();
} /* if((wEPVal & EP_CTR_RX) */
if ((wEPVal & EP_CTR_TX) != 0)
{
/* clear int flag */
_ClearEP_CTR_TX(EPindex);
/* call IN service function */
(*pEpInt_IN[EPindex-1])();
} /* if((wEPVal & EP_CTR_TX) != 0) */
}/* if(EPindex == 0) else */
}/* while(...) */
}
/*******************************************************************************
* Function Name : CTR_HP.
* Description : High Priority Endpoint Correct Transfer interrupt's service
* routine.
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void CTR_HP(void)
{
uint32_t wEPVal = 0;
while (((wIstr = _GetISTR()) & ISTR_CTR) != 0)
{
_SetISTR((uint16_t)CLR_CTR); /* clear CTR flag */
/* extract highest priority endpoint number */
EPindex = (uint8_t)(wIstr & ISTR_EP_ID);
/* process related endpoint register */
wEPVal = _GetENDPOINT(EPindex);
if ((wEPVal & EP_CTR_RX) != 0)
{
/* clear int flag */
_ClearEP_CTR_RX(EPindex);
/* call OUT service function */
(*pEpInt_OUT[EPindex-1])();
} /* if((wEPVal & EP_CTR_RX) */
else if ((wEPVal & EP_CTR_TX) != 0)
{
/* clear int flag */
_ClearEP_CTR_TX(EPindex);
/* call IN service function */
(*pEpInt_IN[EPindex-1])();
} /* if((wEPVal & EP_CTR_TX) != 0) */
}/* while(...) */
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_int.c
|
C
|
asf20
| 6,144
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_init.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Initialization routines & global variables
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* The number of current endpoint, it will be used to specify an endpoint */
uint8_t EPindex;
/* The number of current device, it is an index to the Device_Table */
/* uint8_t Device_no; */
/* Points to the DEVICE_INFO structure of current device */
/* The purpose of this register is to speed up the execution */
DEVICE_INFO *pInformation;
/* Points to the DEVICE_PROP structure of current device */
/* The purpose of this register is to speed up the execution */
DEVICE_PROP *pProperty;
/* Temporary save the state of Rx & Tx status. */
/* Whenever the Rx or Tx state is changed, its value is saved */
/* in this variable first and will be set to the EPRB or EPRA */
/* at the end of interrupt process */
uint16_t SaveState ;
uint16_t wInterrupt_Mask;
DEVICE_INFO Device_Info;
USER_STANDARD_REQUESTS *pUser_Standard_Requests;
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : USB_Init
* Description : USB system initialization
* Input : None.
* Output : None.
* Return : None.
*******************************************************************************/
void USB_Init(void)
{
pInformation = &Device_Info;
pInformation->ControlState = 2;
pProperty = &Device_Property;
pUser_Standard_Requests = &User_Standard_Requests;
/* Initialize devices one by one */
pProperty->Init();
}
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_init.c
|
C
|
asf20
| 3,109
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otgd_fs_int.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Endpoint interrupt's service routines.
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifdef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "usb_type.h"
#include "otgd_fs_int.h"
#include "usb_lib.h"
#include "usb_istr.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint8_t USBD_Data_Buffer [RX_FIFO_SIZE];
__IO uint8_t IsocBuff [(ISOC_BUFFER_SZE * NUM_SUB_BUFFERS)];
__IO uint32_t IsocBufferIdx = 0;
extern USB_OTG_CORE_REGS USB_OTG_FS_regs;
__IO uint16_t SaveRState;
__IO uint16_t SaveTState;
/* Extern variables ----------------------------------------------------------*/
extern void (*pEpInt_IN[7])(void); /* Handles IN interrupts */
extern void (*pEpInt_OUT[7])(void); /* Handles OUT interrupts */
/* Private function prototypes -----------------------------------------------*/
static uint32_t PCD_ReadDevInEP( USB_OTG_EP *ep);
static uint32_t PCD_WriteEmptyTxFifo(uint32_t epnum);
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : OTGD_FS_Handle_Sof_ISR
* Description : Handles the Start Of Frame detected interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_Sof_ISR(void)
{
USB_OTG_GINTSTS_TypeDef GINTSTS ;
GINTSTS.d32 = 0;
/* Call user function */
INTR_SOFINTR_Callback();
/* Clear interrupt */
GINTSTS.b.sofintr = 1;
USB_OTG_WRITE_REG32 (&USB_OTG_FS_regs.GREGS->GINTSTS, GINTSTS.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_RxStatusQueueLevel_ISR
* Description : Handles the Rx Status Queue Level Interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_RxStatusQueueLevel_ISR(void)
{
USB_OTG_GINTMSK_TypeDef int_mask;
USB_OTG_GRXSTSP_TypeDef status;
USB_OTG_EP *ep;
int_mask.d32 = 0;
status.d32 = 0;
/* Disable the Rx Status Queue Level interrupt */
int_mask.b.rxstsqlvl = 1;
USB_OTG_MODIFY_REG32( &USB_OTG_FS_regs.GREGS->GINTMSK, int_mask.d32, 0);
/* Get the Status from the top of the FIFO */
status.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.GREGS->GRXSTSP );
/* Get the related endpoint structure */
ep = PCD_GetOutEP(status.b.epnum);
switch (status.b.pktsts)
{
case STS_GOUT_NAK:
break;
case STS_DATA_UPDT:
if (status.b.bcnt)
{
if (ep->type == EP_TYPE_ISOC)
{
/* Call user function */
INTR_RXSTSQLVL_ISODU_Callback();
/* Copy the received buffer to the RAM */
OTGD_FS_ReadPacket((uint8_t*)(IsocBuff + (ISOC_BUFFER_SZE * IsocBufferIdx)), status.b.bcnt);
ep->xfer_buff = (uint8_t*)(IsocBuff + (ISOC_BUFFER_SZE * IsocBufferIdx));
/* Check if the end of the global buffer has been reached */
if (IsocBufferIdx == (NUM_SUB_BUFFERS - 1))
{
/* Reset the buffer index */
IsocBufferIdx = 0;
}
else
{
/* Increment the buffer index */
IsocBufferIdx ++;
}
}
else
{
/* Copy the received buffer to the RAM */
OTGD_FS_ReadPacket(USBD_Data_Buffer, status.b.bcnt);
ep->xfer_buff = USBD_Data_Buffer;
}
/* Update the endpoint structure */
ep->xfer_len = status.b.bcnt;
ep->xfer_count += status.b.bcnt;
}
break;
case STS_XFER_COMP:
break;
case STS_SETUP_COMP:
break;
case STS_SETUP_UPDT:
/* Copy the setup packet received in Fifo into the setup buffer in RAM */
OTGD_FS_ReadPacket(USBD_Data_Buffer, 8);
ep->xfer_buff = USBD_Data_Buffer;
ep->xfer_count += status.b.bcnt;
ep->xfer_len = status.b.bcnt;
break;
default:
break;
}
/* Call the user function */
INTR_RXSTSQLVL_Callback();
/* Enable the Rx Status Queue Level interrupt */
USB_OTG_MODIFY_REG32( &USB_OTG_FS_regs.GREGS->GINTMSK, 0, int_mask.d32);
/* Clear interrupt: this is a read only bit, it cannot be cleared by register
access */
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_GInNakEff_ISR
* Description : Handles the Global IN Endpoints NAK Effective interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_GInNakEff_ISR(void)
{
/* Call user function */
INTR_GINNAKEFF_Callback();
/* Clear interrupt: This is a read only bit, it cannot be cleared by register
access */
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_GOutNakEff_ISR
* Description : Handles the Global OUT Endpoints NAK Effective interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_GOutNakEff_ISR(void)
{
/* Call user function */
INTR_GOUTNAKEFF_Callback();
/* Clear interrupt: This is a read only bit, it cannot be cleared by register
access */
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_EarlySuspend_ISR
* Description : Handles the Early Suspend detected interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_EarlySuspend_ISR(void )
{
USB_OTG_GINTSTS_TypeDef gintsts;
USB_OTG_GINTMSK_TypeDef gintmsk;
gintsts.d32 = 0;
gintmsk.d32 = 0;
/* Call user function */
INTR_ERLYSUSPEND_Callback();
gintmsk.b.erlysuspend = 1;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.GREGS->GINTMSK, gintmsk.d32, 0 );
/* Clear interrupt */
gintsts.b.erlysuspend = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_USBSuspend_ISR
* Description : Handles the Suspend condition detected interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_USBSuspend_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
gintsts.d32 = 0;
/* Call user function */
INTR_USBSUSPEND_Callback();
/* Clear interrupt */
gintsts.b.usbsuspend = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_UsbReset_ISR
* Description : This interrupt occurs when a USB Reset is detected.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_UsbReset_ISR(void)
{
USB_OTG_DAINT_TypeDef daintmsk;
USB_OTG_DOEPMSKx_TypeDef doepmsk;
USB_OTG_DIEPMSKx_TypeDef diepmsk;
USB_OTG_DCFG_TypeDef dcfg;
USB_OTG_DCTL_TypeDef dctl;
USB_OTG_GINTSTS_TypeDef gintsts;
uint32_t i = 0;
daintmsk.d32 = 0;
doepmsk.d32 = 0;
diepmsk.d32 = 0;
dcfg.d32 =0;
dctl.d32 = 0;
gintsts.d32 = 0;
/* Clear the Remote Wakeup Signalling */
dctl.b.rmtwkupsig = 1;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32, 0 );
/* Flush the NP Tx FIFO */
OTGD_FS_FlushTxFifo( 0 );
/* clear pending interrupts */
for (i = 0; i < NUM_TX_FIFOS ; i++)
{
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DINEPS[i]->DIEPINTx, 0xFF);
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DOUTEPS[i]->DOEPINTx, 0xFF);
}
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DAINT, 0xFFFFFFFF );
daintmsk.ep.in = 1;
daintmsk.ep.out = 1;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DAINTMSK, daintmsk.d32 );
doepmsk.b.setup = 1;
doepmsk.b.b2bsetup = 1;
doepmsk.b.xfercompl = 1;
doepmsk.b.epdis = 1;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DOEPMSK, doepmsk.d32 );
diepmsk.b.xfercompl = 1;
diepmsk.b.timeout = 1;
diepmsk.b.epdis = 1;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DIEPMSK, diepmsk.d32 );
/* Reset Device Address */
dcfg.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.DEV->DCFG);
dcfg.b.devaddr = 0;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DCFG, dcfg.d32);
/* setup EP0 to receive SETUP packets */
PCD_EP0_OutStart();
/* Clear interrupt */
gintsts.d32 = 0;
gintsts.b.usbreset = 1;
USB_OTG_WRITE_REG32 (&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
/* Call the user reset function */
OTGD_FS_DEVICE_RESET;
/* Call user function */
INTR_USBRESET_Callback();
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_EnumDone_ISR
* Description : Reads the device status register and set the device speed
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_EnumDone_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
USB_OTG_GUSBCFG_TypeDef gusbcfg;
gintsts.d32 = 0;
gusbcfg.d32 = 0;
OTGD_FS_EP0Activate();
/* Set USB turnaround time */
gusbcfg.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GUSBCFG);
gusbcfg.b.usbtrdtim = 9;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GUSBCFG, gusbcfg.d32);
/* Call user function */
INTR_ENUMDONE_Callback();
/* Clear interrupt */
gintsts.b.enumdone = 1;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32 );
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_IsoOutDrop_ISR
* Description : Handles the Isochrounous Out packet Dropped interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_IsoOutDrop_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
gintsts.d32 = 0;
/* Call user function */
INTR_ISOOUTDROP_Callback();
/* Clear interrupt */
gintsts.b.isooutdrop = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_EOPF_ISR
* Description : Handles the Expexted End Of Periodic Frame interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_EOPF_ISR(void )
{
USB_OTG_GINTSTS_TypeDef gintsts;
USB_OTG_GINTMSK_TypeDef gintmsk;
gintsts.d32 = 0;
gintmsk.d32 = 0;
gintmsk.b.eopframe = 1;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.GREGS->GINTMSK, gintmsk.d32, 0 );
/* Call user function */
INTR_EOPFRAME_Callback();
/* Clear interrupt */
gintsts.b.eopframe = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_InEP_ISR
* Description : Handles all IN endpoints interrupts.
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_InEP_ISR(void)
{
USB_OTG_DIEPINTx_TypeDef diepint;
uint32_t ep_intr = 0;
uint32_t epnum = 0;
USB_OTG_EP *ep;
uint32_t fifoemptymsk = 0;
diepint.d32 = 0;
ep_intr = OTGD_FS_ReadDevAllInEPItr();
while ( ep_intr )
{
if (ep_intr&0x1) /* In ITR */
{
ep = PCD_GetInEP(epnum);
diepint.d32 = PCD_ReadDevInEP(ep); /* Get In ITR status */
if ( diepint.b.xfercompl )
{
fifoemptymsk = 0x1 << ep->num;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DIEPEMPMSK, fifoemptymsk, 0);
/* Clear the Interrupt flag */
CLEAR_IN_EP_INTR(epnum, xfercompl);
if (epnum == 0)
{
/* Call the core IN process for EP0 */
In0_Process();
/* before terminate set Tx & Rx status */
OTG_DEV_SetEPRxStatus(epnum, SaveRState);
OTG_DEV_SetEPTxStatus(epnum, SaveTState);
}
else
{
/* Call the relative IN endpoint callback */
(*pEpInt_IN[epnum -1])();
}
}
if ( diepint.b.timeout )
{
CLEAR_IN_EP_INTR(epnum, timeout);
}
if (diepint.b.intktxfemp)
{
CLEAR_IN_EP_INTR(epnum, intktxfemp);
}
if (diepint.b.inepnakeff)
{
CLEAR_IN_EP_INTR(epnum, inepnakeff);
}
if (diepint.b.txfempty)
{
if ((epnum == 0) || (OTG_DEV_GetEPTxStatus(epnum) == DEV_EP_TX_VALID))
{
PCD_WriteEmptyTxFifo(epnum);
}
CLEAR_IN_EP_INTR(epnum, txfempty);
}
if ( diepint.b.epdis)
{
/* Reset Endpoint Frame ID to 0 */
ep->even_odd_frame = 0;
CLEAR_IN_EP_INTR(epnum, epdis);
}
}
epnum++;
ep_intr >>= 1;
}
/* Call user function */
INTR_INEPINTR_Callback();
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_OutEP_ISR
* Description : Handles all OUT endpoints interrupts.
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
uint32_t OTGD_FS_Handle_OutEP_ISR(void)
{
uint32_t ep_intr = 0;
USB_OTG_DOEPINTx_TypeDef doepint;
uint32_t epnum = 0;
USB_OTG_EP *ep;
doepint.d32 = 0;
/* Read in the device interrupt bits */
ep_intr = OTGD_FS_ReadDevAllOutEp_itr();
while ( ep_intr )
{
if (ep_intr&0x1)
{
/* Get EP pointer */
ep = PCD_GetOutEP(epnum);
doepint.d32 = OTGD_FS_ReadDevOutEP_itr(ep);
/* Transfer complete */
if ( doepint.b.xfercompl )
{
/* Clear the bit in DOEPINTn for this interrupt */
CLEAR_OUT_EP_INTR(epnum, xfercompl);
if (epnum == 0)
{
/* Call the OUT process for the EP0 */
Out0_Process();
}
else
{
(*pEpInt_OUT[epnum-1])();
}
}
/* Endpoint disable */
if ( doepint.b.epdis)
{
/* Clear the bit in DOEPINTn for this interrupt */
CLEAR_OUT_EP_INTR(epnum, epdis);
}
/* Setup Phase Done (control EPs) */
if ( doepint.b.setup )
{
if (epnum == 0)
{
/* Call the SETUP process for the EP0 */
Setup0_Process();
/* Before exit, update the Tx status */
OTG_DEV_SetEPTxStatus(0x80, SaveTState);
}
else
{
/* Other control endpoints */
}
/* Clear the EP Interrupt */
CLEAR_OUT_EP_INTR(epnum, setup);
}
/* Back to back setup received */
if ( doepint.b.b2bsetup )
{
if (epnum == 0)
{
/* Call the SETUP process for the EP0 */
Setup0_Process();
/* Before exit, update the Tx status */
OTG_DEV_SetEPTxStatus(0x80, SaveTState);
}
}
}
epnum++;
ep_intr >>= 1;
}
/* Call user function */
INTR_OUTEPINTR_Callback();
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_IncomplIsoIn_ISR
* Description : Handles the Incomplete Isochrous IN tranfer error interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_IncomplIsoIn_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
gintsts.d32 = 0;
/* Call user function */
INTR_INCOMPLISOIN_Callback();
/* Clear interrupt */
gintsts.b.incomplisoin = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_IncomplIsoOut_ISR
* Description : Handles the Incomplete Isochrous OUT tranfer error interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_IncomplIsoOut_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
gintsts.d32 = 0;
/* Call user function */
INTR_INCOMPLISOOUT_Callback();
/* Clear interrupt */
gintsts.b.outepintr = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : OTGD_FS_Handle_Wakeup_ISR
* Description : Handles the Wakeup or Remote Wakeup detected interrupt.
* Input : None
* Output : None
* Return : status
*******************************************************************************/
uint32_t OTGD_FS_Handle_Wakeup_ISR(void)
{
USB_OTG_GINTSTS_TypeDef gintsts;
gintsts.d32 = 0;
/* Call user function */
INTR_WKUPINTR_Callback();
/* Clear interrupt */
gintsts.b.wkupintr = 1;
USB_OTG_WRITE_REG32 (&USB_OTG_FS_regs.GREGS->GINTSTS, gintsts.d32);
return 1;
}
/*******************************************************************************
* Function Name : PCD_ReadDevInEP
* Description : Reads all the Endpoints flags.
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
static uint32_t PCD_ReadDevInEP( USB_OTG_EP *ep)
{
uint32_t v = 0, msk = 0, emp=0;
msk = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DIEPMSK);
emp = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DIEPEMPMSK);
msk |= ((emp >> ep->num) & 0x1) << 7;
v = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DINEPS[ep->num]->DIEPINTx) & msk;
return v;
}
/*******************************************************************************
* Function Name : PCD_WriteEmptyTxFifo
* Description : Checks Fifo for the next packet to be loaded.
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
static uint32_t PCD_WriteEmptyTxFifo(uint32_t epnum)
{
USB_OTG_DTXFSTS_TypeDef txstatus;
USB_OTG_EP *ep;
uint32_t len = 0;
uint32_t dwords = 0;
txstatus.d32 = 0;
ep = PCD_GetInEP(epnum);
len = ep->xfer_len - ep->xfer_count;
if (len > ep->maxpacket)
{
len = ep->maxpacket;
}
dwords = (len + 3) / 4;
txstatus.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.DINEPS[epnum]->DTXFSTSx);
while ((txstatus.b.txfspcavail > dwords) &&
(ep->xfer_count < ep->xfer_len) &&
(ep->xfer_len) != 0)
{
len = ep->xfer_len - ep->xfer_count;
if (len > ep->maxpacket)
{
len = ep->maxpacket;
}
dwords = (len + 3) / 4;
OTGD_FS_WritePacket(ep->xfer_buff, epnum, len);
ep->xfer_count += len;
ep->xfer_buff += len;
txstatus.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DINEPS[epnum]->DTXFSTSx);
}
return 1;
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/otgd_fs_int.c
|
C
|
asf20
| 22,063
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : otgd_fs_cal.c
* Author : STMicroelectronics
* Version : V3.2.1
* Date : 07/05/2010
* Description : OTG FS Device Core Access Layer interface.
********************************************************************************
* THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
#ifdef STM32F10X_CL
/* Includes ------------------------------------------------------------------*/
#include "otgd_fs_cal.h"
#include "usb_conf.h"
#include "otgd_fs_regs.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
USB_OTG_CORE_REGS USB_OTG_FS_regs;
/* Private function prototypes -----------------------------------------------*/
static USB_OTG_Status OTGD_FS_SetDeviceMode(void);
static USB_OTG_Status OTGD_FS_CoreReset(void);
extern uint32_t STM32_PCD_OTG_ISR_Handler (void);
/******************************************************************************/
/* Common Core Layer */
/******************************************************************************/
/*******************************************************************************
* Function Name : OTGD_FS_WritePacket
* Description : Writes a packet into the Tx FIFO associated with the EP
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_WritePacket(uint8_t *src, uint8_t ep_num, uint16_t bytes)
{
USB_OTG_Status status = USB_OTG_OK;
uint32_t dword_count = 0 , i = 0;
__IO uint32_t *fifo;
/* Find the DWORD length, padded by extra bytes as neccessary if MPS
* is not a multiple of DWORD */
dword_count = (bytes + 3) / 4;
fifo = USB_OTG_FS_regs.FIFO[ep_num];
for (i = 0; i < dword_count; i++, src += 4)
{
USB_OTG_WRITE_REG32( fifo, *((__packed uint32_t *)src) );
}
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadPacket
* Description : Reads a packet from the Rx FIFO
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void* OTGD_FS_ReadPacket(uint8_t *dest, uint16_t bytes)
{
uint32_t i = 0;
uint32_t word_count = (bytes + 3) / 4;
__IO uint32_t *fifo = USB_OTG_FS_regs.FIFO[0];
uint32_t *data_buff = (uint32_t *)dest;
for (i = 0; i < word_count; i++, data_buff++)
{
*data_buff = USB_OTG_READ_REG32(fifo);
}
/* Return the buffer pointer because if the transfer is composed of several packets,
the data of the next packet must be stored following the previous packet's data */
return ((void *)data_buff);
}
/*******************************************************************************
* Function Name : OTGD_FS_SetAddress
* Description : Initialize core registers addresses.
* Input : BaseAddress
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_SetAddress(uint32_t BaseAddress)
{
uint32_t i = 0;
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_FS_regs.GREGS = (USB_OTG_GREGS *)(BaseAddress +\
USB_OTG_CORE_GLOBAL_REGS_OFFSET);
USB_OTG_FS_regs.DEV = (USB_OTG_DEV *) (BaseAddress +\
USB_OTG_DEV_GLOBAL_REG_OFFSET);
for (i = 0; i < NUM_TX_FIFOS; i++)
{
USB_OTG_FS_regs.DINEPS[i] = (USB_OTG_DINEPS *) (BaseAddress + \
USB_OTG_DEV_IN_EP_REG_OFFSET + (i * USB_OTG_EP_REG_OFFSET));
USB_OTG_FS_regs.DOUTEPS[i] = (USB_OTG_DOUTEPS *) (BaseAddress + \
USB_OTG_DEV_OUT_EP_REG_OFFSET + (i * USB_OTG_EP_REG_OFFSET));
}
for (i = 0; i < NUM_TX_FIFOS; i++)
{
USB_OTG_FS_regs.FIFO[i] = (uint32_t *)(BaseAddress + \
USB_OTG_DATA_FIFO_OFFSET + (i * USB_OTG_DATA_FIFO_SIZE));
}
USB_OTG_FS_regs.PCGCCTL = (uint32_t *)(BaseAddress + USB_OTG_PCGCCTL_OFFSET);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_CoreInit
* Description : Initialize the USB_OTG controller registers and prepares the core
for device mode or host mode operation.
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_CoreInit(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_GUSBCFG_TypeDef usbcfg;
USB_OTG_GCCFG_TypeDef gccfg;
usbcfg.d32 = 0;
gccfg.d32 = 0;
usbcfg.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GUSBCFG);
usbcfg.b.physel = 1;
USB_OTG_WRITE_REG32 (&USB_OTG_FS_regs.GREGS->GUSBCFG, usbcfg.d32);
/* init and configure the phy */
gccfg.d32 = 0;
gccfg.b.vbussensingB = 1;
gccfg.b.pwdn = 1;
USB_OTG_WRITE_REG32 (&USB_OTG_FS_regs.GREGS->GCCFG, gccfg.d32);
mDELAY(50);
/* Reset after a PHY select and set Host mode */
OTGD_FS_CoreReset();
/* Set Device Mode */
OTGD_FS_SetDeviceMode();
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_CoreReset
* Description : Soft reset of the core
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
static USB_OTG_Status OTGD_FS_CoreReset(void)
{
USB_OTG_Status status = USB_OTG_OK;
__IO USB_OTG_GRSTCTL_TypeDef greset;
uint32_t timeout = 0;
greset.d32 = 0;
/* Wait for AHB master IDLE state. */
do
{
uDELAY(5);
greset.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GRSTCTL);
if (++timeout > USB_OTG_TIMEOUT)
{
return USB_OTG_OK;
}
}
while (greset.b.ahbidle == 0);
/* Core Soft Reset */
timeout = 0;
greset.b.csftrst = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GRSTCTL, greset.d32 );
do
{
greset.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GRSTCTL);
if (++timeout > USB_OTG_TIMEOUT)
{
break;
}
}
while (greset.b.csftrst == 1);
/* Wait for 3 PHY Clocks*/
uDELAY(5);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EnableGlobalInt
* Description : Enables the controller's Global Int in the AHB Config reg
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EnableGlobalInt(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_GAHBCFG_TypeDef ahbcfg;
ahbcfg.d32 = 0;
ahbcfg.b.gintmsk = 1; /* Enable interrupts */
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.GREGS->GAHBCFG, 0, ahbcfg.d32);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_DisableGlobalInt
* Description : Disables the controller's Global Int in the AHB Config reg
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_DisableGlobalInt(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_GAHBCFG_TypeDef ahbcfg;
ahbcfg.d32 = 0;
ahbcfg.b.gintmsk = 1; /* Enable interrupts */
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.GREGS->GAHBCFG, ahbcfg.d32, 0);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_FlushTxFifo
* Description : Flush a Tx FIFO
* Input : FIFO num
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_FlushTxFifo (uint32_t num )
{
USB_OTG_Status status = USB_OTG_OK;
__IO USB_OTG_GRSTCTL_TypeDef greset;
uint32_t timeout = 0;
greset.d32 = 0;
greset.b.txfflsh = 1;
greset.b.txfnum = num;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GRSTCTL, greset.d32 );
do
{
greset.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.GREGS->GRSTCTL);
if (++timeout > USB_OTG_TIMEOUT)
{
break;
}
}
while (greset.b.txfflsh == 1);
/* Wait for 3 PHY Clocks*/
uDELAY(5);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_FlushRxFifo
* Description : Flush a Rx FIFO
* Input : None
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_FlushRxFifo( void )
{
USB_OTG_Status status = USB_OTG_OK;
__IO USB_OTG_GRSTCTL_TypeDef greset;
uint32_t timeout = 0;
greset.d32 = 0;
greset.b.rxfflsh = 1;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GRSTCTL, greset.d32 );
do
{
greset.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.GREGS->GRSTCTL);
if (++timeout > USB_OTG_TIMEOUT)
{
break;
}
}
while (greset.b.rxfflsh == 1);
/* Wait for 3 PHY Clocks*/
uDELAY(5);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_SetDeviceMode
* Description : Set device mode
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_SetDeviceMode(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_GUSBCFG_TypeDef usbcfg ;
usbcfg.d32 = 0;
usbcfg.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GUSBCFG);
usbcfg.b.force_dev = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.GREGS->GUSBCFG, usbcfg.d32);
mDELAY(50);
return status;
}
/*******************************************************************************
* Function Name : IsDeviceMode
* Description : check device mode
* Input : None
* Output : None
* Return : current mode
*******************************************************************************/
uint32_t USBD_FS_IsDeviceMode(void)
{
return ((USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS ) & 0x1) == 0 );
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadCoreItr
* Description : returns the Core Interrupt register
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint32_t OTGD_FS_ReadCoreItr(void)
{
uint32_t v = 0;
v = USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GINTSTS);
v &= USB_OTG_READ_REG32(&USB_OTG_FS_regs.GREGS->GINTMSK);
return v;
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadOtgItr
* Description : returns the USB_OTG Interrupt register
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint32_t OTGD_FS_ReadOtgItr (void)
{
return (USB_OTG_READ_REG32 (&USB_OTG_FS_regs.GREGS->GOTGINT));
}
/******************************************************************************/
/* PCD Core Layer */
/******************************************************************************/
/*******************************************************************************
* Function Name : InitDevSpeed
* Description : Initializes the DevSpd field of the DCFG register depending
on the PHY type and the enumeration speed of the device.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
static void InitDevSpeed(void)
{
USB_OTG_DCFG_TypeDef dcfg;
dcfg.d32 = 0;
dcfg.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCFG);
dcfg.b.devspd = 0x3; /* Full speed PHY */
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCFG, dcfg.d32);
}
/*******************************************************************************
* Function Name : OTGD_FS_CoreInitDev
* Description : Initialize the USB_OTG controller registers for device mode
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_CoreInitDev (void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef depctl;
USB_OTG_DCFG_TypeDef dcfg;
USB_OTG_FIFOSIZ_TypeDef txfifosize0;
USB_OTG_FIFOSIZ_TypeDef txfifosize;
uint32_t i = 0;
depctl.d32 = 0;
dcfg.d32 = 0;
txfifosize0.d32 = 0;
txfifosize.d32 = 0;
/* Set device speed */
InitDevSpeed ();
/* Restart the Phy Clock */
USB_OTG_WRITE_REG32(USB_OTG_FS_regs.PCGCCTL, 0);
/* Device configuration register */
dcfg.d32 = USB_OTG_READ_REG32( &USB_OTG_FS_regs.DEV->DCFG);
dcfg.b.perfrint = DCFG_FRAME_INTERVAL_80;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DCFG, dcfg.d32 );
/* set Rx FIFO size */
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GRXFSIZ, RX_FIFO_SIZE);
/* EP0 TX*/
txfifosize0.b.depth = TX0_FIFO_SIZE;
txfifosize0.b.startaddr = RX_FIFO_SIZE;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->DIEPTXF0, txfifosize0.d32 );
/* EP1 TX*/
txfifosize.b.startaddr = txfifosize0.b.startaddr + txfifosize0.b.depth;
txfifosize.b.depth = TX1_FIFO_SIZE;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->DIEPTXFx[0], txfifosize.d32 );
/* EP2 TX*/
txfifosize.b.startaddr += txfifosize.b.depth;
txfifosize.b.depth = TX2_FIFO_SIZE;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->DIEPTXFx[1], txfifosize.d32 );
/* EP3 TX*/
txfifosize.b.startaddr += txfifosize.b.depth;
txfifosize.b.depth = TX3_FIFO_SIZE;
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->DIEPTXFx[2], txfifosize.d32 );
/* Flush the FIFOs */
OTGD_FS_FlushTxFifo(0x10); /* all Tx FIFOs */
OTGD_FS_FlushRxFifo();
/* Clear all pending Device Interrupts */
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DIEPMSK, 0 );
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DOEPMSK, 0 );
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DAINT, 0xFFFFFFFF );
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DEV->DAINTMSK, 0 );
for (i = 0; i <= NUM_TX_FIFOS; i++)
{
depctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DINEPS[i]->DIEPCTLx);
if (depctl.b.epena)
{
depctl.d32 = 0;
depctl.b.epdis = 1;
depctl.b.snak = 1;
}
else
{
depctl.d32 = 0;
}
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DINEPS[i]->DIEPCTLx, depctl.d32);
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DINEPS[i]->DIEPTSIZx, 0);
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DINEPS[i]->DIEPINTx, 0xFF);
}
for (i = 0; i < 1/* NUM_OUT_EPS*/; i++)
{
depctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DOUTEPS[i]->DOEPCTLx);
if (depctl.b.epena)
{
depctl.d32 = 0;
depctl.b.epdis = 1;
depctl.b.snak = 1;
}
else
{
depctl.d32 = 0;
}
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DOUTEPS[i]->DOEPCTLx, depctl.d32);
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DOUTEPS[i]->DOEPTSIZx, 0);
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.DOUTEPS[i]->DOEPINTx, 0xFF);
}
OTGD_FS_EnableDevInt();
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EnableDevInt
* Description : Enables the Device mode interrupts
* Input : None
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EnableDevInt(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_GINTMSK_TypeDef intr_mask;
intr_mask.d32 = 0;
/* Disable all interrupts. */
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GINTMSK, 0);
/* Clear any pending interrupts */
USB_OTG_WRITE_REG32( &USB_OTG_FS_regs.GREGS->GINTSTS, 0xFFFFFFFF);
/* Enable the defined interrupts in Device mode */
#ifdef INTR_SOFINTR
intr_mask.b.sofintr = 1;
#endif /* INTR_SOFINTR */
#ifdef INTR_RXSTSQLVL
intr_mask.b.rxstsqlvl = 1;
#endif /* INTR_RXSTSQLVL */
#ifdef INTR_GINNAKEFF
intr_mask.b.ginnakeff = 1;
#endif /* INTR_GINNAKEFF */
#ifdef INTR_GOUTNAKEFF
intr_mask.b.goutnakeff = 1;
#endif /* INTR_GOUTNAKEFF */
#ifdef INTR_ERLYSUSPEND
intr_mask.b.erlysuspend = 1;
#endif /* INTR_ERLYSUSPEND */
#ifdef INTR_USBSUSPEND
intr_mask.b.usbsuspend = 1;
#endif /* INTR_USBSUSPEND */
#ifdef INTR_USBRESET
intr_mask.b.usbreset = 1;
#endif /* INTR_USBRESET */
#ifdef INTR_ENUMDONE
intr_mask.b.enumdone = 1;
#endif /* INTR_ENUMDONE */
#ifdef INTR_ISOOUTDROP
intr_mask.b.isooutdrop = 1;
#endif /* INTR_ISOOUTDROP */
#ifdef INTR_EOPFRAME
intr_mask.b.eopframe = 1;
#endif /* INTR_EOPFRAME */
#ifdef INTR_INEPINTR
intr_mask.b.inepintr = 1;
#endif /* INTR_INEPINTR */
#ifdef INTR_OUTEPINTR
intr_mask.b.outepintr = 1;
#endif /* INTR_OUTEPINTR */
#ifdef INTR_INCOMPLISOIN
intr_mask.b.incomplisoin = 1;
#endif /* INTR_INCOMPLISOIN */
#ifdef INTR_INCOMPLISOOUT
intr_mask.b.incomplisoout = 1;
#endif /* INTR_INCOMPLISOOUT */
#ifdef INTR_DISCONNECT
intr_mask.b.disconnect = 1;
#endif /* INTR_DISCONNECT */
#ifdef INTR_WKUPINTR
intr_mask.b.wkupintr = 1;
#endif /* INTR_WKUPINTR */
USB_OTG_MODIFY_REG32( &USB_OTG_FS_regs.GREGS->GINTMSK, intr_mask.d32, intr_mask.d32);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EP0Activate
* Description : enables EP0 OUT to receive SETUP packets and configures EP0
IN for transmitting packets
* Input : None
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EP0Activate(void)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef diepctl;
USB_OTG_DCTL_TypeDef dctl;
diepctl.d32 = 0;
dctl.d32 = 0;
diepctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DINEPS[0]->DIEPCTLx);
diepctl.b.mps = DEP0CTL_MPS_64;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DINEPS[0]->DIEPCTLx, diepctl.d32);
dctl.b.cgnpinnak = 1;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DCTL, dctl.d32, dctl.d32);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EPActivate
* Description : Activates an EP
* Input : ep
* Output : None
* Return : num_in_ep
*******************************************************************************/
USB_OTG_Status OTGD_FS_EPActivate(USB_OTG_EP *ep)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef depctl;
USB_OTG_DAINT_TypeDef daintmsk;
__IO uint32_t *addr;
depctl.d32 = 0;
daintmsk.d32 = 0;
/* Read DEPCTLn register */
if (ep->is_in == 1)
{
addr = &USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx;
daintmsk.ep.in = 1 << ep->num;
}
else
{
addr = &USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx;
daintmsk.ep.out = 1 << ep->num;
}
/* If the EP is already active don't change the EP Control
* register. */
depctl.d32 = USB_OTG_READ_REG32(addr);
if (!depctl.b.usbactep)
{
depctl.b.mps = ep->maxpacket;
depctl.b.eptype = ep->type;
depctl.b.txfnum = ep->tx_fifo_num;
depctl.b.setd0pid = 1;
depctl.b.usbactep = 1;
USB_OTG_WRITE_REG32(addr, depctl.d32);
}
/* Enable the Interrupt for this EP */
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DAINTMSK, 0, daintmsk.d32);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EPDeactivate
* Description : Deactivates an EP
* Input : ep
* Output : None
* Return : num_in_ep
*******************************************************************************/
USB_OTG_Status OTGD_FS_EPDeactivate(USB_OTG_EP *ep)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef depctl;
__IO uint32_t *addr;
USB_OTG_DAINT_TypeDef daintmsk;
depctl.d32 = 0;
daintmsk.d32 = 0;
/* Read DEPCTLn register */
if (ep->is_in == 1)
{
addr = &USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx;
daintmsk.ep.in = 1 << ep->num;
}
else
{
addr = &USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx;
daintmsk.ep.out = 1 << ep->num;
}
depctl.b.usbactep = 0;
USB_OTG_WRITE_REG32(addr, depctl.d32);
/* Disable the Interrupt for this EP */
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DAINTMSK, daintmsk.d32, 0);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EPStartXfer
* Description : Handle the setup for data xfer for an EP and starts the xfer
* Input : None
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EPStartXfer(USB_OTG_EP *ep)
{
USB_OTG_DSTS_TypeDef dsts;
USB_OTG_Status status = USB_OTG_OK;
__IO USB_OTG_DEPCTLx_TypeDef depctl;
OTG_FS_DEPTSIZx_TypeDef deptsiz;
depctl.d32 = 0;
deptsiz.d32 = 0;
/* IN endpoint */
if (ep->is_in == 1)
{
depctl.d32 = USB_OTG_READ_REG32(&(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx));
deptsiz.d32 = USB_OTG_READ_REG32(&(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPTSIZx));
/* Zero Length Packet? */
if (ep->xfer_len == 0)
{
deptsiz.b.xfersize = 0;
deptsiz.b.pktcnt = 1;
}
else
{
/* Program the transfer size and packet count
* as follows: xfersize = N * maxpacket +
* short_packet pktcnt = N + (short_packet
* exist ? 1 : 0)
*/
deptsiz.b.xfersize = ep->xfer_len;
deptsiz.b.pktcnt = (ep->xfer_len - 1 + ep->maxpacket) / ep->maxpacket;
if (ep->type == EP_TYPE_ISOC)
{
deptsiz.b.mcount = 1;
}
}
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DINEPS[ep->num]->DIEPTSIZx, deptsiz.d32);
if (ep->type != EP_TYPE_ISOC)
{
/* Enable the Tx FIFO Empty Interrupt for this EP */
uint32_t fifoemptymsk = 0;
fifoemptymsk = 1 << ep->num;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DIEPEMPMSK, 0, fifoemptymsk);
}
/* EP enable, IN data in FIFO */
depctl.b.cnak = 1;
depctl.b.epena = 1;
if (ep->type == EP_TYPE_ISOC)
{
dsts.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DSTS);
if (((dsts.b.soffn)&0x1)==0)
{
depctl.b.setoddfrm=1;
}
else
{
depctl.b.setd0pid=1;
}
}
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx, depctl.d32);
if (ep->type == EP_TYPE_ISOC)
{
/*write buffer in TXFIFO*/
/* user should ensure taht ep->xfer_len <= ep->maxpacket */
OTGD_FS_WritePacket(ep->xfer_buff, ep->num, ep->xfer_len);
}
}
else
{
/* OUT endpoint */
depctl.d32 = USB_OTG_READ_REG32(&(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx));
deptsiz.d32 = USB_OTG_READ_REG32(&(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPTSIZx));
/* Program the transfer size and packet count as follows:
* pktcnt = N
* xfersize = N * maxpacket
*/
if (ep->xfer_len == 0)
{
deptsiz.b.xfersize = ep->maxpacket;
deptsiz.b.pktcnt = 1;
}
else
{
deptsiz.b.pktcnt = (ep->xfer_len + (ep->maxpacket - 1)) / ep->maxpacket;
deptsiz.b.xfersize = deptsiz.b.pktcnt * ep->maxpacket;
}
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPTSIZx, deptsiz.d32);
if (ep->type == EP_TYPE_ISOC)
{
if (ep->even_odd_frame)
{
depctl.b.setoddfrm = 1;
}
else
{
depctl.b.setd0pid = 1;
}
}
/* EP enable */
depctl.b.cnak = 1;
depctl.b.epena = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx, depctl.d32);
}
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EP0StartXfer
* Description : Handle the setup for a data xfer for EP0 and starts the xfer
* Input : None
* Output : None
* Return : status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EP0StartXfer(USB_OTG_EP *ep)
{
USB_OTG_Status status = USB_OTG_OK;
uint32_t fifoemptymsk = 0;
USB_OTG_DEPCTLx_TypeDef depctl;
OTG_FS_DEPTSIZx_TypeDef deptsiz;
USB_OTG_DINEPS *in_regs ;
depctl.d32 = 0;
deptsiz.d32 = 0;
/* IN endpoint */
if (ep->is_in == 1)
{
in_regs = USB_OTG_FS_regs.DINEPS[0];
depctl.d32 = USB_OTG_READ_REG32(&in_regs->DIEPCTLx);
deptsiz.d32 = USB_OTG_READ_REG32(&in_regs->DIEPTSIZx);
/* Zero Length Packet? */
if (ep->xfer_len == 0)
{
deptsiz.b.xfersize = 0;
deptsiz.b.pktcnt = 1;
}
else
{
if (ep->xfer_len > ep->maxpacket)
{
ep->xfer_len = ep->maxpacket;
deptsiz.b.xfersize = ep->maxpacket;
}
else
{
deptsiz.b.xfersize = ep->xfer_len;
}
deptsiz.b.pktcnt = 1;
}
USB_OTG_WRITE_REG32(&in_regs->DIEPTSIZx, deptsiz.d32);
/* EP enable, IN data in FIFO */
depctl.b.cnak = 1;
depctl.b.epena = 1;
USB_OTG_WRITE_REG32(&in_regs->DIEPCTLx, depctl.d32);
/* Enable the Tx FIFO Empty Interrupt for this EP */
if (ep->xfer_len > 0)
{
fifoemptymsk |= 1 << ep->num;
USB_OTG_MODIFY_REG32(&USB_OTG_FS_regs.DEV->DIEPEMPMSK, 0, fifoemptymsk);
}
}
else
{
/* OUT endpoint */
depctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DOUTEPS[0]->DOEPCTLx);
deptsiz.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DOUTEPS[0]->DOEPTSIZx);
/* Program the transfer size and packet count as follows:
* xfersize = N * (maxpacket + 4 - (maxpacket % 4))
* pktcnt = N */
if (ep->xfer_len == 0)
{
deptsiz.b.xfersize = ep->maxpacket;
deptsiz.b.pktcnt = 1;
}
else
{
deptsiz.b.pktcnt = (ep->xfer_len + (ep->maxpacket - 1)) / ep->maxpacket;
deptsiz.b.xfersize = deptsiz.b.pktcnt * ep->maxpacket;
}
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DOUTEPS[0]->DOEPTSIZx, deptsiz.d32);
/* EP enable */
depctl.b.cnak = 1;
depctl.b.epena = 1;
USB_OTG_WRITE_REG32 (&(USB_OTG_FS_regs.DOUTEPS[0]->DOEPCTLx), depctl.d32);
}
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EPSetStall
* Description : Set the EP STALL
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EPSetStall(USB_OTG_EP *ep)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef depctl;
__IO uint32_t *depctl_addr;
depctl.d32 = 0;
if (ep->is_in == 1)
{
depctl_addr = &(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx);
depctl.d32 = USB_OTG_READ_REG32(depctl_addr);
/* set the disable and stall bits */
if (depctl.b.epena)
{
depctl.b.epdis = 1;
}
depctl.b.stall = 1;
USB_OTG_WRITE_REG32(depctl_addr, depctl.d32);
}
else
{
depctl_addr = &(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx);
depctl.d32 = USB_OTG_READ_REG32(depctl_addr);
/* set the stall bit */
depctl.b.stall = 1;
USB_OTG_WRITE_REG32(depctl_addr, depctl.d32);
}
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_EPClearStall
* Description : Clear the EP STALL
* Input : None
* Output : None
* Return : Status
*******************************************************************************/
USB_OTG_Status OTGD_FS_EPClearStall(USB_OTG_EP *ep)
{
USB_OTG_Status status = USB_OTG_OK;
USB_OTG_DEPCTLx_TypeDef depctl;
__IO uint32_t *depctl_addr;
depctl.d32 = 0;
if (ep->is_in == 1)
{
depctl_addr = &(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx);
}
else
{
depctl_addr = &(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx);
}
depctl.d32 = USB_OTG_READ_REG32(depctl_addr);
/* clear the stall bits */
depctl.b.stall = 0;
if (ep->type == EP_TYPE_INTR || ep->type == EP_TYPE_BULK)
{
depctl.b.setd0pid = 1; /* DATA0 */
}
USB_OTG_WRITE_REG32(depctl_addr, depctl.d32);
return status;
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadDevAllOutEp_itr
* Description : returns the OUT endpoint interrupt bits
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint32_t OTGD_FS_ReadDevAllOutEp_itr(void)
{
uint32_t v = 0;
v = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DAINT);
v &= USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DAINTMSK);
return ((v & 0xffff0000) >> 16);
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadDevOutEP_itr
* Description : returns the Device OUT EP Interrupt register
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint32_t OTGD_FS_ReadDevOutEP_itr(USB_OTG_EP *ep)
{
uint32_t v = 0;
v = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPINTx);
v &= USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DOEPMSK);
return v;
}
/*******************************************************************************
* Function Name : OTGD_FS_ReadDevAllInEPItr
* Description : Get int status register
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint32_t OTGD_FS_ReadDevAllInEPItr(void)
{
uint32_t v = 0;
v = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DAINT);
v &= USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DAINTMSK);
return (v & 0xffff);
}
/*******************************************************************************
* Function Name : OTGD_FS_GetEPStatus
* Description : returns the EP Status
* Input : - ep: pointer to the EP structure
* Output : None
* Return : status: DEV_EP_TX_STALL, DEV_EP_TX_VALID, DEV_EP_TX_NAK,
* DEV_EP_RX_STALL, DEV_EP_RX_VALID or DEV_EP_RX_NAK,
*******************************************************************************/
uint32_t OTGD_FS_GetEPStatus(USB_OTG_EP *ep)
{
USB_OTG_DEPCTLx_TypeDef depctl;
__IO uint32_t *depctl_addr;
uint32_t Status = 0;
depctl.d32 = 0;
if (ep->is_in == 1)
{
depctl_addr = &(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx);
}
else
{
depctl_addr = &(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx);
}
depctl.d32 = USB_OTG_READ_REG32(depctl_addr);
/* Process for IN endpoint */
if (ep->is_in == 1)
{
if (depctl.b.stall == 1)
Status = DEV_EP_TX_STALL;
else if (depctl.b.naksts == 1)
Status = DEV_EP_TX_NAK;
else
Status = DEV_EP_TX_VALID;
}
/* Process for OUT endpoint */
else
{
if (depctl.b.stall == 1)
Status = DEV_EP_RX_STALL;
else if (depctl.b.naksts == 1)
Status = DEV_EP_RX_NAK;
else
Status = DEV_EP_RX_VALID;
}
/* Return the current status */
return Status;
}
/*******************************************************************************
* Function Name : OTGD_FS_SetEPStatus
* Description : Sets the EP Status
* Input : - ep: pointer to the EP structure
* - Status: new status to be set
* Output : None
* Return : None
*******************************************************************************/
void OTGD_FS_SetEPStatus(USB_OTG_EP *ep, uint32_t Status)
{
USB_OTG_DEPCTLx_TypeDef depctl;
__IO uint32_t *depctl_addr;
depctl.d32 = 0;
if (ep->is_in == 1)
{
depctl_addr = &(USB_OTG_FS_regs.DINEPS[ep->num]->DIEPCTLx);
}
else
{
depctl_addr = &(USB_OTG_FS_regs.DOUTEPS[ep->num]->DOEPCTLx);
}
depctl.d32 = USB_OTG_READ_REG32(depctl_addr);
/* Process for IN endpoint */
if (ep->is_in == 1)
{
if (Status == DEV_EP_TX_STALL)
{
OTGD_FS_EPSetStall(ep); return;
}
else if (Status == DEV_EP_TX_NAK)
depctl.b.snak = 1;
else if (Status == DEV_EP_TX_VALID)
{
if (depctl.b.stall == 1)
{
ep->even_odd_frame = 0;
OTGD_FS_EPClearStall(ep);
return;
}
depctl.b.cnak = 1;
depctl.b.usbactep = 1;
depctl.b.epena = 1;
}
else if (Status == DEV_EP_TX_DIS)
depctl.b.usbactep = 0;
}
else /* Process for OUT endpoint */
{
if (Status == DEV_EP_RX_STALL) {
depctl.b.stall = 1;
}
else if (Status == DEV_EP_RX_NAK)
depctl.b.snak = 1;
else if (Status == DEV_EP_RX_VALID)
{
if (depctl.b.stall == 1)
{
ep->even_odd_frame = 0;
OTGD_FS_EPClearStall(ep);
return;
}
depctl.b.cnak = 1;
depctl.b.usbactep = 1;
depctl.b.epena = 1;
}
else if (Status == DEV_EP_RX_DIS)
{
depctl.b.usbactep = 0;
}
}
USB_OTG_WRITE_REG32(depctl_addr, depctl.d32);
}
/*******************************************************************************
* Function Name : OTGD_FS_SetRemoteWakeup
* Description : Enable Remote wakeup signaling
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void OTGD_FS_SetRemoteWakeup()
{
USB_OTG_DCTL_TypeDef devctl;
devctl.d32 = 0;
devctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Enable the Remote Wakeup signal */
devctl.b.rmtwkupsig = 1;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, devctl.d32);
}
/*******************************************************************************
* Function Name : OTGD_FS_ResetRemoteWakeup
* Description : Disable Remote wakeup signaling
* Input : None
* Output : None
* Return : status
*******************************************************************************/
void OTGD_FS_ResetRemoteWakeup()
{
USB_OTG_DCTL_TypeDef devctl;
devctl.d32 = 0;
devctl.d32 = USB_OTG_READ_REG32(&USB_OTG_FS_regs.DEV->DCTL);
/* Disable the Remote Wakeup signal */
devctl.b.rmtwkupsig = 0;
USB_OTG_WRITE_REG32(&USB_OTG_FS_regs.DEV->DCTL, devctl.d32);
}
#endif /* STM32F10X_CL */
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/otgd_fs_cal.c
|
C
|
asf20
| 37,097
|
/******************** (C) COPYRIGHT 2010 STMicroelectronics ********************
* File Name : usb_sil.c
* Author : MCD Application Team
* Version : V3.2.1
* Date : 07/05/2010
* Description : Simplified Interface Layer for Global Initialization and
* Endpoint Rea/Write operations.
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : USB_SIL_Init
* Description : Initialize the USB Device IP and the Endpoint 0.
* Input : None.
* Output : None.
* Return : Status.
*******************************************************************************/
uint32_t USB_SIL_Init(void)
{
#ifndef STM32F10X_CL
/* USB interrupts initialization */
/* clear pending interrupts */
_SetISTR(0);
wInterrupt_Mask = IMR_MSK;
/* set interrupts mask */
_SetCNTR(wInterrupt_Mask);
#else
/* Perform OTG Device initialization procedure (including EP0 init) */
OTG_DEV_Init();
#endif /* STM32F10X_CL */
return 0;
}
/*******************************************************************************
* Function Name : USB_SIL_Write
* Description : Write a buffer of data to a selected endpoint.
* Input : - bEpAddr: The address of the non control endpoint.
* - pBufferPointer: The pointer to the buffer of data to be written
* to the endpoint.
* - wBufferSize: Number of data to be written (in bytes).
* Output : None.
* Return : Status.
*******************************************************************************/
uint32_t USB_SIL_Write(uint8_t bEpAddr, uint8_t* pBufferPointer, uint32_t wBufferSize)
{
#ifndef STM32F10X_CL
/* Use the memory interface function to write to the selected endpoint */
UserToPMABufferCopy(pBufferPointer, GetEPTxAddr(bEpAddr & 0x7F), wBufferSize);
/* Update the data length in the control register */
SetEPTxCount((bEpAddr & 0x7F), wBufferSize);
#else
/* Use the PCD interface layer function to write to the selected endpoint */
PCD_EP_Write (bEpAddr, pBufferPointer, wBufferSize);
#endif /* STM32F10X_CL */
return 0;
}
/*******************************************************************************
* Function Name : USB_SIL_Read
* Description : Write a buffer of data to a selected endpoint.
* Input : - bEpAddr: The address of the non control endpoint.
* - pBufferPointer: The pointer to which will be saved the
* received data buffer.
* Output : None.
* Return : Number of received data (in Bytes).
*******************************************************************************/
uint32_t USB_SIL_Read(uint8_t bEpAddr, uint8_t* pBufferPointer)
{
uint32_t DataLength = 0;
#ifndef STM32F10X_CL
/* Get the number of received data on the selected Endpoint */
DataLength = GetEPRxCount(bEpAddr & 0x7F);
/* Use the memory interface function to write to the selected endpoint */
PMAToUserBufferCopy(pBufferPointer, GetEPRxAddr(bEpAddr & 0x7F), DataLength);
#else
USB_OTG_EP *ep;
/* Get the structure pointer of the selected Endpoint */
ep = PCD_GetOutEP(bEpAddr);
/* Get the number of received data */
DataLength = ep->xfer_len;
/* Use the PCD interface layer function to read the selected endpoint */
PCD_EP_Read (bEpAddr, pBufferPointer, DataLength);
#endif /* STM32F10X_CL */
/* Return the number of received data */
return DataLength;
}
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Libraries/STM32_USB-FS-Device_Driver/src/usb_sil.c
|
C
|
asf20
| 5,050
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:st1="urn:schemas-microsoft-com:office:smarttags" xmlns="http://www.w3.org/TR/REC-html40"><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="File-List" href="stm32_usb-fs-device_lib_contents_files/filelist.xml">
<link rel="Edit-Time-Data" href="stm32_usb-fs-device_lib_contents_files/editdata.mso"><!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]-->
<title>STM32 USB Library package</title><o:smarttagtype namespaceuri="urn:schemas-microsoft-com:office:smarttags" name="PlaceType"></o:smarttagtype>
<o:smarttagtype namespaceuri="urn:schemas-microsoft-com:office:smarttags" name="PlaceName"></o:smarttagtype>
<o:smarttagtype namespaceuri="urn:schemas-microsoft-com:office:smarttags" name="place"></o:smarttagtype><!--[if gte mso 9]><xml>
<o:DocumentProperties>
<o:Author>raouf hosni</o:Author>
<o:LastAuthor>raouf hosni</o:LastAuthor>
<o:Revision>5</o:Revision>
<o:TotalTime>3</o:TotalTime>
<o:Created>2009-11-09T09:27:00Z</o:Created>
<o:LastSaved>2009-11-09T09:31:00Z</o:LastSaved>
<o:Pages>1</o:Pages>
<o:Words>840</o:Words>
<o:Characters>4789</o:Characters>
<o:Company>STMicroelectronics</o:Company>
<o:Lines>39</o:Lines>
<o:Paragraphs>11</o:Paragraphs>
<o:CharactersWithSpaces>5618</o:CharactersWithSpaces>
<o:Version>11.9999</o:Version>
</o:DocumentProperties>
</xml><![endif]--><!--[if gte mso 9]><xml>
<w:WordDocument>
<w:Zoom>105</w:Zoom>
<w:SpellingState>Clean</w:SpellingState>
<w:GrammarState>Clean</w:GrammarState>
<w:ValidateAgainstSchemas/>
<w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
<w:IgnoreMixedContent>false</w:IgnoreMixedContent>
<w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
</w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
<w:LatentStyles DefLockedState="false" LatentStyleCount="156">
</w:LatentStyles>
</xml><![endif]--><!--[if !mso]><object
classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui></object>
<style>
st1\:*{behavior:url(#ieooui) }
</style>
<![endif]-->
<style>
<!--
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-parent:"";
margin:0cm;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"Times New Roman";}
a:link, span.MsoHyperlink
{color:blue;
text-decoration:underline;
text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
{color:blue;
text-decoration:underline;
text-underline:single;}
p
{mso-margin-top-alt:auto;
margin-right:0cm;
mso-margin-bottom-alt:auto;
margin-left:0cm;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"Times New Roman";}
span.SpellE
{mso-style-name:"";
mso-spl-e:yes;}
span.GramE
{mso-style-name:"";
mso-gram-e:yes;}
@page Section1
{size:612.0pt 792.0pt;
margin:72.0pt 90.0pt 72.0pt 90.0pt;
mso-header-margin:36.0pt;
mso-footer-margin:36.0pt;
mso-paper-source:0;}
div.Section1
{page:Section1;}
/* List Definitions */
@list l0
{mso-list-id:1145705928;
mso-list-template-ids:-2068006730;}
@list l0:level1
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:36.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Symbol;}
@list l1
{mso-list-id:2074965730;
mso-list-template-ids:972482700;}
@list l1:level1
{mso-level-number-format:bullet;
mso-level-text:\F0B7;
mso-level-tab-stop:36.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;
mso-ansi-font-size:10.0pt;
font-family:Symbol;}
@list l1:level2
{mso-level-tab-stop:72.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level3
{mso-level-tab-stop:108.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level4
{mso-level-tab-stop:144.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level5
{mso-level-tab-stop:180.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level6
{mso-level-tab-stop:216.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level7
{mso-level-tab-stop:252.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level8
{mso-level-tab-stop:288.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
@list l1:level9
{mso-level-tab-stop:324.0pt;
mso-level-number-position:left;
text-indent:-18.0pt;}
ol
{margin-bottom:0cm;}
ul
{margin-bottom:0cm;}
-->
</style><!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"Times New Roman";
mso-ansi-language:#0400;
mso-fareast-language:#0400;
mso-bidi-language:#0400;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="3074"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]--></head>
<body style="" lang="EN-US" link="blue" vlink="blue">
<div class="Section1">
<div align="center">
<table class="MsoNormalTable" style="width: 675pt;" border="0" cellpadding="0" cellspacing="0" width="900">
<tbody><tr style="">
<td style="padding: 0cm;" valign="top">
<table class="MsoNormalTable" style="width: 100%;" border="0" cellpadding="0" width="100%">
<tbody><tr style="">
<td style="padding: 0.75pt;">
<p class="MsoNormal" style="text-align: right;" align="right"><span style="font-family: Arial;"><img id="_x0000_i1025" src="_htmresc/stm32_ryc.jpg" style="height: 85px; width: 900px;" alt="STM32 Releasing your creativity" height="85" width="900"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial;"><o:p> </o:p></span></p>
<table class="MsoNormalTable" style="width: 675pt;" border="0" cellpadding="0" cellspacing="0" width="900">
<tbody><tr style="">
<td style="padding: 1.5pt;">
<p class="MsoNormal"><strong><span style="font-size: 13.5pt; font-family: Arial; color: black;">Easy-to-use USB-FS-Device Library for STM32</span></strong><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial; display: none;"><o:p> </o:p></span></p>
<table class="MsoNormalTable" style="width: 675pt;" border="0" cellpadding="0" width="900">
<tbody><tr style="">
<td style="padding: 0cm;" valign="top">
<p class="MsoNormal" style=""><span style="font-size: 10pt; font-family: Arial;">The <strong><span style="font-family: Arial;">STM32</span></strong> <strong><span style="font-family: Arial;">USB-FS-Device Library</span></strong> provides a free,
complete firmware package that makes implementation of USB-FS-Device
interfaces in STM32 applications quick and easy, that allows
developers to painlessly develop any flavor of USB-FS-Device firmware
including:</span><span style="font-family: Arial;"><o:p></o:p></span></p>
<ul type="disc">
<li class="MsoNormal" style=""><span style="font-size: 10pt; font-family: Arial;"> <strong><span style="font-family: Arial;">Control transfer</span></strong> with
generic device management tasks <o:p></o:p></span></li>
<li class="MsoNormal" style=""><span style="font-size: 10pt; font-family: Arial;"> <strong><span style="font-family: Arial;">Interrupt transfer</span></strong> with HID
Mouse/Joystick and Custom HID demos <o:p></o:p></span></li>
<li class="MsoNormal" style=""><span style="font-size: 10pt; font-family: Arial;"> <strong><span style="font-family: Arial;">Bulk transfer</span></strong> with mass
storage demo <o:p></o:p></span></li>
<li class="MsoNormal" style=""><span style="font-size: 10pt; font-family: Arial;"> <strong><span style="font-family: Arial;">Isochronous transfer</span></strong> with
Audio speaker/streaming demos <o:p></o:p></span></li>
</ul>
<p><span style="font-size: 10pt; font-family: Arial;">In addition,
the package provides implementation of DFU for firmware updates
on USB-FS-Device, and of the popular Virtual COM (CDC class) for
emulation of a classic RS232 interface on USB-FS-Device. </span><span style="font-family: Arial;"><o:p></o:p></span></p>
<p><span style="font-size: 10pt; font-family: Arial;">For more details
about USB-FS-Device Library and demos implementation, please refer to
the User manual "UM0424 STM32F10xxx USB development kit",
available for download from the STMicroelectronics microcontrollers website: <a href="http://www.st.com/stm32" target="_blank">www.st.com/stm32</a> </span><span style="font-family: Arial;"><o:p></o:p></span></p>
<p><span style="font-size: 10pt; font-family: Arial;">The STM32 USB-FS-Device Library is </span><span style="font-size: 10pt; font-family: Arial;">USB Full Speed certified and </span><span style="font-size: 10pt; font-family: Arial;"> full CMSIS compliant.</span></p><p style="text-align: center;"><span style="font-size: 10pt; font-family: Arial;"></span><span style="font-size: 10pt; font-family: Arial;"><img style="width: 261px; height: 100px;" alt="Certified USB Full Speed" src="_htmresc/USB-RGB-1008.jpg"></span></p><p style="text-align: center;"><span style="font-size: 10pt; font-family: Arial;"></span></p><p style="text-align: center;"><span style="font-size: 10pt; font-family: Arial;"><img style="width: 273px; height: 108px;" alt="" src="_htmresc/CMSIS_Logo_Final.jpg"></span><span style="font-size: 10pt; font-family: Arial;"></span><span style="font-size: 10pt; font-family: Arial;"></span></p><p><span style="font-size: 10pt; font-family: Arial;">The package contains
the following demos: </span><span style="font-family: Arial;"><o:p></o:p></span></p>
<p><em><u><span style="font-size: 10pt; font-family: Arial;">Note</span></u></em><u><span style="font-size: 10pt; font-family: Arial;">:</span></u><span style="font-size: 10pt; font-family: Arial;"> Most of these demos run on
STMicroelectronics STM3210B-EVAL, STM3210C-EVAL and STM3210E-EVAL
evaluation boards and can be easily tailored to any other hardware. To
select the STMicroelectronics evaluation board used to run the example,
uncomment the corresponding line in <span class="SpellE">platform_config.h</span>
file.</span></p><p><em><u><span style="font-size: 10pt; font-family: Arial;">Note</span></u></em><u><span style="font-size: 10pt; font-family: Arial;">:</span></u><span style="font-size: 10pt; font-family: Arial;"> All demos provided by STMicroelectronics are compatible and tested with Microsoft Windows 2000, XP, VISTA and Windows 7.</span><span style="font-size: 10pt; font-family: Arial;"></span><span style="font-family: Arial;"><o:p></o:p></span></p>
<table class="MsoNormalTable" style="width: 100%;" border="0" cellpadding="0" cellspacing="5" width="100%">
<tbody><tr style="height: 31.5pt;">
<td style="padding: 0cm; height: 31.5pt;" valign="top">
<table class="MsoNormalTable" style="width: 100%;" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr style="height: 14.25pt;">
<td style="padding: 0cm; width: 144pt; height: 14.25pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 14.25pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1026" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Audio_Speaker" target="_blank"><span class="SpellE">Audio_Speaker</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">The
USB Audio Speaker demo gives examples of how to use the STM32F10x2/3
USB-FS_Device peripheral to communicate with the PC host in the
isochronous transfer mode. It provides a demonstration of the correct
method for configuring an isochronous endpoint, receiving or
transmitting data from/to the host.</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 16.5pt;">
<td style="padding: 0cm; width: 144pt; height: 16.5pt;" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"><o:p> </o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 16.5pt;" width="694">
<p class="MsoNormal"><span style="font-family: Arial;"><o:p> </o:p></span></p>
</td>
</tr>
<tr style="">
<td style="padding: 0cm; width: 144pt;" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1027" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Audio_Streaming" target="_blank"><span class="SpellE">Audio_Streaming</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt;" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">The
USB Audio Streaming demo gives examples of how to use the STM32F10x5/7
OTG-FS_Device peripheral to communicate with the PC host in the
isochronous transfer mode. This demo provides possibilities to
configure high audio quality streaming and low CPU charge using the
audio-class I2S peripheral. This demo runs only on STM3210C-EVAL
board</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><o:p> </o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><o:p> </o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1028" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Custom_HID" target="_blank"><span class="SpellE">Custom_HID</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">This
Demo provides a description of how to use the </span><span style="font-size: 10pt; font-family: Arial;">USB-FS-Device library</span><span style="font-size: 10pt; font-family: Arial;"> on the
STM32 devices. The STM32 device is enumerated as HID compliant <span class="GramE">device, that</span> uses the native PC Host USB HID driver.</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 16.5pt;">
<td style="padding: 0cm; width: 144pt; height: 16.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 16.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"> </span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1029" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Device_Firmware_Upgrade" target="_blank"><span class="SpellE">Device_Firmware_Upgrade</span></a> </span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">This
Demo presents the implementation of a device firmware upgrade (DFU)
capability in the STM32 microcontrollers. It follows the DFU class
specification defined by the USB Implementers Forum for
reprogramming an application through USB. The DFU
principle is particularly well suited to USB
applications that need to be reprogrammed in the field.</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 16.5pt;">
<td style="padding: 0cm; width: 144pt; height: 16.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 16.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"> </span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1030" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/JoyStickMouse" target="_blank"><span class="SpellE">JoyStickMouse</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">This
Demo provides a description of how to use the USB-FS-Device library on the
STM32 devices. The STM32 device is enumerated as an USB
Joystick <span class="GramE">Mouse, that</span> uses the native PC
Host USB HID driver. The Joystick mounted on the STM3210B-EVAL,
STM3210C-EVAL and STM3210E-EVAL boards is used to emulate the Mouse
directions.</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 16.5pt;">
<td style="padding: 0cm; width: 144pt; height: 16.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 16.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"> </span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1031" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Mass_Storage" target="_blank"><span class="SpellE">Mass_Storage</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">This
<span class="GramE">Demo gives</span> a typical example of how to
use the </span><span style="font-size: 10pt; font-family: Arial;">USB-FS-Device library</span><span style="font-size: 10pt; font-family: Arial;"> on the STM32 device to communicate with the PC
host using the bulk transfer. This demo supports the BOT (bulk only
transfer) protocol and all needed SCSI (small computer system
interface) commands.</span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 16.5pt;">
<td style="padding: 0cm; width: 144pt; height: 16.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 16.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"> </span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="height: 19.5pt;">
<td style="padding: 0cm; width: 144pt; height: 19.5pt;" valign="top" width="192">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1032" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"> <strong><span style="font-family: Arial;"><a href="Project/Virtual_COM_Port" target="_blank"><span class="SpellE">Virtual_COM_Port</span></a></span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 520.6pt; height: 19.5pt;" valign="top" width="694">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">In
modern PCs, USB is the standard communication port for
almost all peripherals. However many industrial software applications
still use the classic <st1:place w:st="on"><st1:placename w:st="on">COM</st1:placename>
<st1:placetype w:st="on">Port</st1:placetype></st1:place> (UART). The <st1:placename w:st="on">Virtual</st1:placename> <st1:placename w:st="on">COM</st1:placename>
<st1:placetype w:st="on">Port</st1:placetype> Demo provides a simple
solution to bypass this problem; it uses the USB as a
COM port by affecting the legacy PC application designed for <st1:place w:st="on"><st1:placename w:st="on">COM</st1:placename> <st1:placetype w:st="on">Port</st1:placetype></st1:place> communication. </span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial;"><o:p> </o:p></span></p>
<table class="MsoNormalTable" style="width: 100%;" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr style="">
<td style="padding: 1.5pt;">
<p class="MsoNormal"><strong><span style="font-size: 13.5pt; font-family: Arial;">Firmware, software and documents</span></strong><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial; display: none;"><o:p> </o:p></span></p>
<table class="MsoNormalTable" style="width: 100%;" border="0" cellpadding="0" cellspacing="5" width="100%">
<tbody><tr style="">
<td style="padding: 0cm; width: 3%;" width="3%">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><img id="_x0000_i1033" src="_htmresc/ar_s.gif" style="height: 12px; width: 14px;" border="0" height="12" width="14"></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
<td style="padding: 0cm; width: 97%;" width="97%">
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;">For
complete documentation refer to <a href="http://www.st.com/stm32" target="_blank">www.st.com/STM32</a><strong><span style="font-family: Arial;"> </span></strong></span><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
<tr style="">
<td style="padding: 0cm;" valign="top">
<p class="MsoNormal"><span style="font-family: Arial;"> <o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-size: 10pt; font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
<p class="MsoNormal"><span style="font-family: Arial;"><o:p></o:p></span></p>
</td>
</tr>
</tbody></table>
</div>
<p class="MsoNormal"><span style="font-family: Arial;"><o:p> </o:p></span></p>
</div>
</body></html>
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/stm32_usb-fs-device_lib_contents.htm
|
HTML
|
asf20
| 26,581
|
/**
******************************************************************************
* @file stm3210e_eval.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains definitions for STM3210E_EVAL's Leds, push-buttons
* COM ports, sFLASH (on SPI) and Temperature Sensor LM75 (on I2C)
* hardware resources.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210E_EVAL_H
#define __STM3210E_EVAL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL
* @{
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Exported_Constants
* @{
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_LED
* @{
*/
#define LEDn 4
#define LED1_PIN GPIO_Pin_6
#define LED1_GPIO_PORT GPIOF
#define LED1_GPIO_CLK RCC_APB2Periph_GPIOF
#define LED2_PIN GPIO_Pin_7
#define LED2_GPIO_PORT GPIOF
#define LED2_GPIO_CLK RCC_APB2Periph_GPIOF
#define LED3_PIN GPIO_Pin_8
#define LED3_GPIO_PORT GPIOF
#define LED3_GPIO_CLK RCC_APB2Periph_GPIOF
#define LED4_PIN GPIO_Pin_9
#define LED4_GPIO_PORT GPIOF
#define LED4_GPIO_CLK RCC_APB2Periph_GPIOF
/**
* @}
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_BUTTON
* @{
*/
#define BUTTONn 8
/**
* @brief Wakeup push-button
*/
#define WAKEUP_BUTTON_PIN GPIO_Pin_0
#define WAKEUP_BUTTON_GPIO_PORT GPIOA
#define WAKEUP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOA
#define WAKEUP_BUTTON_EXTI_LINE EXTI_Line0
#define WAKEUP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOA
#define WAKEUP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define WAKEUP_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Tamper push-button
*/
#define TAMPER_BUTTON_PIN GPIO_Pin_13
#define TAMPER_BUTTON_GPIO_PORT GPIOC
#define TAMPER_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOC
#define TAMPER_BUTTON_EXTI_LINE EXTI_Line13
#define TAMPER_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOC
#define TAMPER_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource13
#define TAMPER_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Key push-button
*/
#define KEY_BUTTON_PIN GPIO_Pin_8
#define KEY_BUTTON_GPIO_PORT GPIOG
#define KEY_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOG
#define KEY_BUTTON_EXTI_LINE EXTI_Line8
#define KEY_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOG
#define KEY_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource8
#define KEY_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @brief Joystick Right push-button
*/
#define RIGHT_BUTTON_PIN GPIO_Pin_13
#define RIGHT_BUTTON_GPIO_PORT GPIOG
#define RIGHT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOG
#define RIGHT_BUTTON_EXTI_LINE EXTI_Line13
#define RIGHT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOG
#define RIGHT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource13
#define RIGHT_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Joystick Left push-button
*/
#define LEFT_BUTTON_PIN GPIO_Pin_14
#define LEFT_BUTTON_GPIO_PORT GPIOG
#define LEFT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOG
#define LEFT_BUTTON_EXTI_LINE EXTI_Line14
#define LEFT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOG
#define LEFT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource14
#define LEFT_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Joystick Up push-button
*/
#define UP_BUTTON_PIN GPIO_Pin_15
#define UP_BUTTON_GPIO_PORT GPIOG
#define UP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOG
#define UP_BUTTON_EXTI_LINE EXTI_Line15
#define UP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOG
#define UP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource15
#define UP_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Joystick Down push-button
*/
#define DOWN_BUTTON_PIN GPIO_Pin_3
#define DOWN_BUTTON_GPIO_PORT GPIOD
#define DOWN_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define DOWN_BUTTON_EXTI_LINE EXTI_Line3
#define DOWN_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define DOWN_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource3
#define DOWN_BUTTON_EXTI_IRQn EXTI3_IRQn
/**
* @brief Joystick Sel push-button
*/
#define SEL_BUTTON_PIN GPIO_Pin_7
#define SEL_BUTTON_GPIO_PORT GPIOG
#define SEL_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOG
#define SEL_BUTTON_EXTI_LINE EXTI_Line7
#define SEL_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOG
#define SEL_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource7
#define SEL_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @}
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_COM
* @{
*/
#define COMn 2
/**
* @brief Definition for COM port1, connected to USART1
*/
#define EVAL_COM1 USART1
#define EVAL_COM1_CLK RCC_APB2Periph_USART1
#define EVAL_COM1_TX_PIN GPIO_Pin_9
#define EVAL_COM1_TX_GPIO_PORT GPIOA
#define EVAL_COM1_TX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_RX_PIN GPIO_Pin_10
#define EVAL_COM1_RX_GPIO_PORT GPIOA
#define EVAL_COM1_RX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_IRQn USART1_IRQn
/**
* @brief Definition for COM port2, connected to USART2
*/
#define EVAL_COM2 USART2
#define EVAL_COM2_CLK RCC_APB1Periph_USART2
#define EVAL_COM2_TX_PIN GPIO_Pin_2
#define EVAL_COM2_TX_GPIO_PORT GPIOA
#define EVAL_COM2_TX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM2_RX_PIN GPIO_Pin_3
#define EVAL_COM2_RX_GPIO_PORT GPIOA
#define EVAL_COM2_RX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM2_IRQn USART2_IRQn
/**
* @}
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_SD_FLASH
* @{
*/
/**
* @brief SD FLASH SDIO Interface
*/
#define SD_DETECT_PIN GPIO_Pin_11 /* PF.11 */
#define SD_DETECT_GPIO_PORT GPIOF /* GPIOF */
#define SD_DETECT_GPIO_CLK RCC_APB2Periph_GPIOF
#define SDIO_FIFO_ADDRESS ((uint32_t)0x40018080)
/**
* @brief SDIO Intialization Frequency (400KHz max)
*/
#define SDIO_INIT_CLK_DIV ((uint8_t)0xB2)
/**
* @brief SDIO Data Transfer Frequency (25MHz max)
*/
#define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x1)
/**
* @}
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_M25P_FLASH_SPI
* @{
*/
/**
* @brief M25P FLASH SPI Interface pins
*/
#define sFLASH_SPI SPI1
#define sFLASH_SPI_CLK RCC_APB2Periph_SPI1
#define sFLASH_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */
#define sFLASH_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */
#define sFLASH_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */
#define sFLASH_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_CS_PIN GPIO_Pin_2 /* PB.02 */
#define sFLASH_CS_GPIO_PORT GPIOB /* GPIOB */
#define sFLASH_CS_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @}
*/
/** @addtogroup STM3210E_EVAL_LOW_LEVEL_TSENSOR_I2C
* @{
*/
/**
* @brief LM75 Temperature Sensor I2C Interface pins
*/
#define LM75_I2C I2C1
#define LM75_I2C_CLK RCC_APB1Periph_I2C1
#define LM75_I2C_SCL_PIN GPIO_Pin_6 /* PB.06 */
#define LM75_I2C_SCL_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SCL_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SDA_PIN GPIO_Pin_7 /* PB.07 */
#define LM75_I2C_SDA_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SDA_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SMBUSALERT_PIN GPIO_Pin_5 /* PB.05 */
#define LM75_I2C_SMBUSALERT_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SMBUSALERT_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @}
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Exported_Functions
* @{
*/
void STM_EVAL_LEDInit(Led_TypeDef Led);
void STM_EVAL_LEDOn(Led_TypeDef Led);
void STM_EVAL_LEDOff(Led_TypeDef Led);
void STM_EVAL_LEDToggle(Led_TypeDef Led);
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode);
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button);
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct);
void SD_LowLevel_DeInit(void);
void SD_LowLevel_Init(void);
void SD_LowLevel_DMA_TxConfig(uint32_t *BufferSRC, uint32_t BufferSize);
void SD_LowLevel_DMA_RxConfig(uint32_t *BufferDST, uint32_t BufferSize);
void SD_WaitForDMAEndOfTransfer(void);
void sFLASH_LowLevel_DeInit(void);
void sFLASH_LowLevel_Init(void);
void LM75_LowLevel_DeInit(void);
void LM75_LowLevel_Init(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM3210E_EVAL_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval.h
|
C
|
asf20
| 11,449
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_nand.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to drive the
* NAND512W3A2 memory mounted on STM3210E-EVAL board.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210e_eval_fsmc_nand.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_NAND
* @brief This file provides a set of functions needed to drive the
* NAND512W3A2 memory mounted on STM3210E-EVAL board.
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Defines
* @{
*/
/**
* @brief FSMC Bank 2
*/
#define FSMC_Bank_NAND FSMC_Bank2_NAND
#define Bank_NAND_ADDR Bank2_NAND_ADDR
#define Bank2_NAND_ADDR ((uint32_t)0x70000000)
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Macros
* @{
*/
#define ROW_ADDRESS (Address.Page + (Address.Block + (Address.Zone * NAND_ZONE_SIZE)) * NAND_BLOCK_SIZE)
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Private_Functions
* @{
*/
/**
* @brief Configures the FSMC and GPIOs to interface with the NAND memory.
* This function must be called before any write/read operation on the
* NAND.
* @param None
* @retval None
*/
void NAND_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
FSMC_NANDInitTypeDef FSMC_NANDInitStructure;
FSMC_NAND_PCCARDTimingInitTypeDef p;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE |
RCC_APB2Periph_GPIOF | RCC_APB2Periph_GPIOG, ENABLE);
/*-- GPIO Configuration ------------------------------------------------------*/
/*!< CLE, ALE, D0->D3, NOE, NWE and NCE2 NAND pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_14 | GPIO_Pin_15 |
GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4 | GPIO_Pin_5 |
GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< D4->D7 NAND pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*!< NWAIT NAND pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< INT2 NAND pin configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_Init(GPIOG, &GPIO_InitStructure);
/*-- FSMC Configuration ------------------------------------------------------*/
p.FSMC_SetupTime = 0x1;
p.FSMC_WaitSetupTime = 0x3;
p.FSMC_HoldSetupTime = 0x2;
p.FSMC_HiZSetupTime = 0x1;
FSMC_NANDInitStructure.FSMC_Bank = FSMC_Bank2_NAND;
FSMC_NANDInitStructure.FSMC_Waitfeature = FSMC_Waitfeature_Enable;
FSMC_NANDInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_8b;
FSMC_NANDInitStructure.FSMC_ECC = FSMC_ECC_Enable;
FSMC_NANDInitStructure.FSMC_ECCPageSize = FSMC_ECCPageSize_512Bytes;
FSMC_NANDInitStructure.FSMC_TCLRSetupTime = 0x00;
FSMC_NANDInitStructure.FSMC_TARSetupTime = 0x00;
FSMC_NANDInitStructure.FSMC_CommonSpaceTimingStruct = &p;
FSMC_NANDInitStructure.FSMC_AttributeSpaceTimingStruct = &p;
FSMC_NANDInit(&FSMC_NANDInitStructure);
/*!< FSMC NAND Bank Cmd Test */
FSMC_NANDCmd(FSMC_Bank2_NAND, ENABLE);
}
/**
* @brief Reads NAND memory's ID.
* @param NAND_ID: pointer to a NAND_IDTypeDef structure which will hold
* the Manufacturer and Device ID.
* @retval None
*/
void NAND_ReadID(NAND_IDTypeDef* NAND_ID)
{
uint32_t data = 0;
/*!< Send Command to the command area */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = 0x90;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = 0x00;
/*!< Sequence to read ID from NAND flash */
data = *(__IO uint32_t *)(Bank_NAND_ADDR | DATA_AREA);
NAND_ID->Maker_ID = ADDR_1st_CYCLE (data);
NAND_ID->Device_ID = ADDR_2nd_CYCLE (data);
NAND_ID->Third_ID = ADDR_3rd_CYCLE (data);
NAND_ID->Fourth_ID = ADDR_4th_CYCLE (data);
}
/**
* @brief This routine is for writing one or several 512 Bytes Page size.
* @param pBuffer: pointer on the Buffer containing data to be written
* @param Address: First page address
* @param NumPageToWrite: Number of page to write
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
* And the new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t NAND_WriteSmallPage(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToWrite)
{
uint32_t index = 0x00, numpagewritten = 0x00, addressstatus = NAND_VALID_ADDRESS;
uint32_t status = NAND_READY, size = 0x00;
while((NumPageToWrite != 0x00) && (addressstatus == NAND_VALID_ADDRESS) && (status == NAND_READY))
{
/*!< Page write command and address */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_A;
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_WRITE0;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = 0x00;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_1st_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_2nd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_3rd_CYCLE(ROW_ADDRESS);
/*!< Calculate the size */
size = NAND_PAGE_SIZE + (NAND_PAGE_SIZE * numpagewritten);
/*!< Write data */
for(; index < size; index++)
{
*(__IO uint8_t *)(Bank_NAND_ADDR | DATA_AREA) = pBuffer[index];
}
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_WRITE_TRUE1;
/*!< Check status for successful operation */
status = NAND_GetStatus();
if(status == NAND_READY)
{
numpagewritten++;
NumPageToWrite--;
/*!< Calculate Next small page Address */
addressstatus = NAND_AddressIncrement(&Address);
}
}
return (status | addressstatus);
}
/**
* @brief This routine is for sequential read from one or several 512 Bytes Page size.
* @param pBuffer: pointer on the Buffer to fill
* @param Address: First page address
* @param NumPageToRead: Number of page to read
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
* And the new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t NAND_ReadSmallPage(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToRead)
{
uint32_t index = 0x00, numpageread = 0x00, addressstatus = NAND_VALID_ADDRESS;
uint32_t status = NAND_READY, size = 0x00;
while((NumPageToRead != 0x0) && (addressstatus == NAND_VALID_ADDRESS))
{
/*!< Page Read command and page address */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_A;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = 0x00;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_1st_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_2nd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_3rd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_TRUE1;
/*!< Calculate the size */
size = NAND_PAGE_SIZE + (NAND_PAGE_SIZE * numpageread);
/*!< Get Data into Buffer */
for(; index < size; index++)
{
pBuffer[index]= *(__IO uint8_t *)(Bank_NAND_ADDR | DATA_AREA);
}
numpageread++;
NumPageToRead--;
/*!< Calculate page address */
addressstatus = NAND_AddressIncrement(&Address);
}
status = NAND_GetStatus();
return (status | addressstatus);
}
/**
* @brief This routine write the spare area information for the specified
* pages addresses.
* @param pBuffer: pointer on the Buffer containing data to be written
* @param Address: First page address
* @param NumSpareAreaTowrite: Number of Spare Area to write
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
* And the new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t NAND_WriteSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaTowrite)
{
uint32_t index = 0x00, numsparesreawritten = 0x00, addressstatus = NAND_VALID_ADDRESS;
uint32_t status = NAND_READY, size = 0x00;
while((NumSpareAreaTowrite != 0x00) && (addressstatus == NAND_VALID_ADDRESS) && (status == NAND_READY))
{
/*!< Page write Spare area command and address */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_C;
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_WRITE0;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = 0x00;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_1st_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_2nd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_3rd_CYCLE(ROW_ADDRESS);
/*!< Calculate the size */
size = NAND_SPARE_AREA_SIZE + (NAND_SPARE_AREA_SIZE * numsparesreawritten);
/*!< Write the data */
for(; index < size; index++)
{
*(__IO uint8_t *)(Bank_NAND_ADDR | DATA_AREA) = pBuffer[index];
}
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_WRITE_TRUE1;
/*!< Check status for successful operation */
status = NAND_GetStatus();
if(status == NAND_READY)
{
numsparesreawritten++;
NumSpareAreaTowrite--;
/*!< Calculate Next page Address */
addressstatus = NAND_AddressIncrement(&Address);
}
}
return (status | addressstatus);
}
/**
* @brief This routine read the spare area information from the specified
* pages addresses.
* @param pBuffer: pointer on the Buffer to fill
* @param Address: First page address
* @param NumSpareAreaToRead: Number of Spare Area to read
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
* And the new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t NAND_ReadSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaToRead)
{
uint32_t numsparearearead = 0x00, index = 0x00, addressstatus = NAND_VALID_ADDRESS;
uint32_t status = NAND_READY, size = 0x00;
while((NumSpareAreaToRead != 0x0) && (addressstatus == NAND_VALID_ADDRESS))
{
/*!< Page Read command and page address */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_C;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = 0x00;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_1st_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_2nd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_3rd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_AREA_TRUE1;
/*!< Data Read */
size = NAND_SPARE_AREA_SIZE + (NAND_SPARE_AREA_SIZE * numsparearearead);
/*!< Get Data into Buffer */
for ( ;index < size; index++)
{
pBuffer[index] = *(__IO uint8_t *)(Bank_NAND_ADDR | DATA_AREA);
}
numsparearearead++;
NumSpareAreaToRead--;
/*!< Calculate page address */
addressstatus = NAND_AddressIncrement(&Address);
}
status = NAND_GetStatus();
return (status | addressstatus);
}
/**
* @brief This routine erase complete block from NAND FLASH
* @param Address: Any address into block to be erased
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
*/
uint32_t NAND_EraseBlock(NAND_ADDRESS Address)
{
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_ERASE0;
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_1st_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_2nd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | ADDR_AREA) = ADDR_3rd_CYCLE(ROW_ADDRESS);
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_ERASE1;
return (NAND_GetStatus());
}
/**
* @brief This routine reset the NAND FLASH.
* @param None
* @retval NAND_READY
*/
uint32_t NAND_Reset(void)
{
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_RESET;
return (NAND_READY);
}
/**
* @brief Get the NAND operation status.
* @param None
* @retval New status of the NAND operation. This parameter can be:
* - NAND_TIMEOUT_ERROR: when the previous operation generate
* a Timeout error
* - NAND_READY: when memory is ready for the next operation
*/
uint32_t NAND_GetStatus(void)
{
uint32_t timeout = 0x1000000, status = NAND_READY;
status = NAND_ReadStatus();
/*!< Wait for a NAND operation to complete or a TIMEOUT to occur */
while ((status != NAND_READY) &&( timeout != 0x00))
{
status = NAND_ReadStatus();
timeout --;
}
if(timeout == 0x00)
{
status = NAND_TIMEOUT_ERROR;
}
/*!< Return the operation status */
return (status);
}
/**
* @brief Reads the NAND memory status using the Read status command.
* @param None
* @retval The status of the NAND memory. This parameter can be:
* - NAND_BUSY: when memory is busy
* - NAND_READY: when memory is ready for the next operation
* - NAND_ERROR: when the previous operation gererates error
*/
uint32_t NAND_ReadStatus(void)
{
uint32_t data = 0x00, status = NAND_BUSY;
/*!< Read status operation ------------------------------------ */
*(__IO uint8_t *)(Bank_NAND_ADDR | CMD_AREA) = NAND_CMD_STATUS;
data = *(__IO uint8_t *)(Bank_NAND_ADDR);
if((data & NAND_ERROR) == NAND_ERROR)
{
status = NAND_ERROR;
}
else if((data & NAND_READY) == NAND_READY)
{
status = NAND_READY;
}
else
{
status = NAND_BUSY;
}
return (status);
}
/**
* @brief Increment the NAND memory address.
* @param Address: address to be incremented.
* @retval The new status of the increment address operation. It can be:
* - NAND_VALID_ADDRESS: When the new address is valid address
* - NAND_INVALID_ADDRESS: When the new address is invalid address
*/
uint32_t NAND_AddressIncrement(NAND_ADDRESS* Address)
{
uint32_t status = NAND_VALID_ADDRESS;
Address->Page++;
if(Address->Page == NAND_BLOCK_SIZE)
{
Address->Page = 0;
Address->Block++;
if(Address->Block == NAND_ZONE_SIZE)
{
Address->Block = 0;
Address->Zone++;
if(Address->Zone == NAND_MAX_ZONE)
{
status = NAND_INVALID_ADDRESS;
}
}
}
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_nand.c
|
C
|
asf20
| 18,044
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_sram.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the
* stm3210e_eval_fsmc_sram firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210E_EVAL_FSMC_SRAM_H
#define __STM3210E_EVAL_FSMC_SRAM_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_SRAM
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Exported_Constants
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Exported_Functions
* @{
*/
void SRAM_Init(void);
void SRAM_WriteBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite);
void SRAM_ReadBuffer(uint16_t* pBuffer, uint32_t ReadAddr, uint32_t NumHalfwordToRead);
#ifdef __cplusplus
}
#endif
#endif /* __STM3210E_EVAL_FSMC_SRAM_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_sram.h
|
C
|
asf20
| 2,331
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_sram.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to drive the
* IS61WV51216BLL SRAM memory mounted on STM3210E-EVAL board.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210e_eval_fsmc_sram.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_SRAM
* @brief This file provides a set of functions needed to drive the
* IS61WV51216BLL SRAM memory mounted on STM3210E-EVAL board.
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Defines
* @{
*/
/**
* @brief FSMC Bank 1 NOR/SRAM3
*/
#define Bank1_SRAM3_ADDR ((uint32_t)0x68000000)
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_SRAM_Private_Functions
* @{
*/
/**
* @brief Configures the FSMC and GPIOs to interface with the SRAM memory.
* This function must be called before any write/read operation
* on the SRAM.
* @param None
* @retval None
*/
void SRAM_Init(void)
{
FSMC_NORSRAMInitTypeDef FSMC_NORSRAMInitStructure;
FSMC_NORSRAMTimingInitTypeDef p;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOG | RCC_APB2Periph_GPIOE |
RCC_APB2Periph_GPIOF, ENABLE);
/*-- GPIO Configuration ------------------------------------------------------*/
/*!< SRAM Data lines configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_8 | GPIO_Pin_9 |
GPIO_Pin_10 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 |
GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 |
GPIO_Pin_15;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*!< SRAM Address lines configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 |
GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_12 | GPIO_Pin_13 |
GPIO_Pin_14 | GPIO_Pin_15;
GPIO_Init(GPIOF, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 |
GPIO_Pin_4 | GPIO_Pin_5;
GPIO_Init(GPIOG, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< NOE and NWE configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 |GPIO_Pin_5;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< NE3 configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_Init(GPIOG, &GPIO_InitStructure);
/*!< NBL0, NBL1 configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*-- FSMC Configuration ------------------------------------------------------*/
p.FSMC_AddressSetupTime = 0;
p.FSMC_AddressHoldTime = 0;
p.FSMC_DataSetupTime = 2;
p.FSMC_BusTurnAroundDuration = 0;
p.FSMC_CLKDivision = 0;
p.FSMC_DataLatency = 0;
p.FSMC_AccessMode = FSMC_AccessMode_A;
FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM3;
FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_SRAM;
FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &p;
FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &p;
FSMC_NORSRAMInit(&FSMC_NORSRAMInitStructure);
/*!< Enable FSMC Bank1_SRAM Bank */
FSMC_NORSRAMCmd(FSMC_Bank1_NORSRAM3, ENABLE);
}
/**
* @brief Writes a Half-word buffer to the FSMC SRAM memory.
* @param pBuffer : pointer to buffer.
* @param WriteAddr : SRAM memory internal address from which the data will be
* written.
* @param NumHalfwordToWrite : number of half-words to write.
* @retval None
*/
void SRAM_WriteBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite)
{
for(; NumHalfwordToWrite != 0; NumHalfwordToWrite--) /*!< while there is data to write */
{
/*!< Transfer data to the memory */
*(uint16_t *) (Bank1_SRAM3_ADDR + WriteAddr) = *pBuffer++;
/*!< Increment the address*/
WriteAddr += 2;
}
}
/**
* @brief Reads a block of data from the FSMC SRAM memory.
* @param pBuffer : pointer to the buffer that receives the data read from the
* SRAM memory.
* @param ReadAddr : SRAM memory internal address to read from.
* @param NumHalfwordToRead : number of half-words to read.
* @retval None
*/
void SRAM_ReadBuffer(uint16_t* pBuffer, uint32_t ReadAddr, uint32_t NumHalfwordToRead)
{
for(; NumHalfwordToRead != 0; NumHalfwordToRead--) /*!< while there is data to read */
{
/*!< Read a half-word from the memory */
*pBuffer++ = *(__IO uint16_t*) (Bank1_SRAM3_ADDR + ReadAddr);
/*!< Increment the address*/
ReadAddr += 2;
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_sram.c
|
C
|
asf20
| 7,493
|
/**
******************************************************************************
* @file stm3210e_eval_lcd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm3210e_eval_lcd
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210E_EVAL_LCD_H
#define __STM3210E_EVAL_LCD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "../Common/fonts.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_LCD
* @{
*/
/** @defgroup STM3210E_EVAL_LCD_Exported_Types
* @{
*/
typedef struct
{
int16_t X;
int16_t Y;
} Point, * pPoint;
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LCD_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line below if you want to use user defined Delay function
* (for precise timing), otherwise default _delay_ function defined within
* this driver is used (less precise timing).
*/
/* #define USE_Delay */
#ifdef USE_Delay
#include "main.h"
#define _delay_ Delay /* !< User can provide more timing precise _delay_ function
(with 10ms time base), using SysTick for example */
#else
#define _delay_ delay /* !< Default _delay_ function with less precise timing */
#endif
/**
* @brief LCD Registers
*/
#define LCD_REG_0 0x00
#define LCD_REG_1 0x01
#define LCD_REG_2 0x02
#define LCD_REG_3 0x03
#define LCD_REG_4 0x04
#define LCD_REG_5 0x05
#define LCD_REG_6 0x06
#define LCD_REG_7 0x07
#define LCD_REG_8 0x08
#define LCD_REG_9 0x09
#define LCD_REG_10 0x0A
#define LCD_REG_12 0x0C
#define LCD_REG_13 0x0D
#define LCD_REG_14 0x0E
#define LCD_REG_15 0x0F
#define LCD_REG_16 0x10
#define LCD_REG_17 0x11
#define LCD_REG_18 0x12
#define LCD_REG_19 0x13
#define LCD_REG_20 0x14
#define LCD_REG_21 0x15
#define LCD_REG_22 0x16
#define LCD_REG_23 0x17
#define LCD_REG_24 0x18
#define LCD_REG_25 0x19
#define LCD_REG_26 0x1A
#define LCD_REG_27 0x1B
#define LCD_REG_28 0x1C
#define LCD_REG_29 0x1D
#define LCD_REG_30 0x1E
#define LCD_REG_31 0x1F
#define LCD_REG_32 0x20
#define LCD_REG_33 0x21
#define LCD_REG_34 0x22
#define LCD_REG_36 0x24
#define LCD_REG_37 0x25
#define LCD_REG_40 0x28
#define LCD_REG_41 0x29
#define LCD_REG_43 0x2B
#define LCD_REG_45 0x2D
#define LCD_REG_48 0x30
#define LCD_REG_49 0x31
#define LCD_REG_50 0x32
#define LCD_REG_51 0x33
#define LCD_REG_52 0x34
#define LCD_REG_53 0x35
#define LCD_REG_54 0x36
#define LCD_REG_55 0x37
#define LCD_REG_56 0x38
#define LCD_REG_57 0x39
#define LCD_REG_58 0x3A
#define LCD_REG_59 0x3B
#define LCD_REG_60 0x3C
#define LCD_REG_61 0x3D
#define LCD_REG_62 0x3E
#define LCD_REG_63 0x3F
#define LCD_REG_64 0x40
#define LCD_REG_65 0x41
#define LCD_REG_66 0x42
#define LCD_REG_67 0x43
#define LCD_REG_68 0x44
#define LCD_REG_69 0x45
#define LCD_REG_70 0x46
#define LCD_REG_71 0x47
#define LCD_REG_72 0x48
#define LCD_REG_73 0x49
#define LCD_REG_74 0x4A
#define LCD_REG_75 0x4B
#define LCD_REG_76 0x4C
#define LCD_REG_77 0x4D
#define LCD_REG_78 0x4E
#define LCD_REG_79 0x4F
#define LCD_REG_80 0x50
#define LCD_REG_81 0x51
#define LCD_REG_82 0x52
#define LCD_REG_83 0x53
#define LCD_REG_96 0x60
#define LCD_REG_97 0x61
#define LCD_REG_106 0x6A
#define LCD_REG_118 0x76
#define LCD_REG_128 0x80
#define LCD_REG_129 0x81
#define LCD_REG_130 0x82
#define LCD_REG_131 0x83
#define LCD_REG_132 0x84
#define LCD_REG_133 0x85
#define LCD_REG_134 0x86
#define LCD_REG_135 0x87
#define LCD_REG_136 0x88
#define LCD_REG_137 0x89
#define LCD_REG_139 0x8B
#define LCD_REG_140 0x8C
#define LCD_REG_141 0x8D
#define LCD_REG_143 0x8F
#define LCD_REG_144 0x90
#define LCD_REG_145 0x91
#define LCD_REG_146 0x92
#define LCD_REG_147 0x93
#define LCD_REG_148 0x94
#define LCD_REG_149 0x95
#define LCD_REG_150 0x96
#define LCD_REG_151 0x97
#define LCD_REG_152 0x98
#define LCD_REG_153 0x99
#define LCD_REG_154 0x9A
#define LCD_REG_157 0x9D
#define LCD_REG_192 0xC0
#define LCD_REG_193 0xC1
#define LCD_REG_229 0xE5
/**
* @brief LCD color
*/
#define LCD_COLOR_WHITE 0xFFFF
#define LCD_COLOR_BLACK 0x0000
#define LCD_COLOR_GREY 0xF7DE
#define LCD_COLOR_BLUE 0x001F
#define LCD_COLOR_BLUE2 0x051F
#define LCD_COLOR_RED 0xF800
#define LCD_COLOR_MAGENTA 0xF81F
#define LCD_COLOR_GREEN 0x07E0
#define LCD_COLOR_CYAN 0x7FFF
#define LCD_COLOR_YELLOW 0xFFE0
/**
* @brief LCD Lines depending on the chosen fonts.
*/
#define LCD_LINE_0 LINE(0)
#define LCD_LINE_1 LINE(1)
#define LCD_LINE_2 LINE(2)
#define LCD_LINE_3 LINE(3)
#define LCD_LINE_4 LINE(4)
#define LCD_LINE_5 LINE(5)
#define LCD_LINE_6 LINE(6)
#define LCD_LINE_7 LINE(7)
#define LCD_LINE_8 LINE(8)
#define LCD_LINE_9 LINE(9)
#define LCD_LINE_10 LINE(10)
#define LCD_LINE_11 LINE(11)
#define LCD_LINE_12 LINE(12)
#define LCD_LINE_13 LINE(13)
#define LCD_LINE_14 LINE(14)
#define LCD_LINE_15 LINE(15)
#define LCD_LINE_16 LINE(16)
#define LCD_LINE_17 LINE(17)
#define LCD_LINE_18 LINE(18)
#define LCD_LINE_19 LINE(19)
#define LCD_LINE_20 LINE(20)
#define LCD_LINE_21 LINE(21)
#define LCD_LINE_22 LINE(22)
#define LCD_LINE_23 LINE(23)
#define LCD_LINE_24 LINE(24)
#define LCD_LINE_25 LINE(25)
#define LCD_LINE_26 LINE(26)
#define LCD_LINE_27 LINE(27)
#define LCD_LINE_28 LINE(28)
#define LCD_LINE_29 LINE(29)
/**
* @brief LCD default font
*/
#define LCD_DEFAULT_FONT Font16x24
/**
* @brief LCD Direction
*/
#define LCD_DIR_HORIZONTAL 0x0000
#define LCD_DIR_VERTICAL 0x0001
/**
* @brief LCD Size (Width and Height)
*/
#define LCD_PIXEL_WIDTH 0x0140
#define LCD_PIXEL_HEIGHT 0x00F0
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LCD_Exported_Macros
* @{
*/
#define ASSEMBLE_RGB(R, G, B) ((((R)& 0xF8) << 8) | (((G) & 0xFC) << 3) | (((B) & 0xF8) >> 3))
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LCD_Exported_Functions
* @{
*/
/** @defgroup
* @{
*/
void LCD_DeInit(void);
void STM3210E_LCD_Init(void);
void LCD_SetColors(__IO uint16_t _TextColor, __IO uint16_t _BackColor);
void LCD_GetColors(__IO uint16_t *_TextColor, __IO uint16_t *_BackColor);
void LCD_SetTextColor(__IO uint16_t Color);
void LCD_SetBackColor(__IO uint16_t Color);
void LCD_ClearLine(uint8_t Line);
void LCD_Clear(uint16_t Color);
void LCD_SetCursor(uint8_t Xpos, uint16_t Ypos);
void LCD_DrawChar(uint8_t Xpos, uint16_t Ypos, const uint16_t *c);
void LCD_DisplayChar(uint8_t Line, uint16_t Column, uint8_t Ascii);
void LCD_SetFont(sFONT *fonts);
sFONT *LCD_GetFont(void);
void LCD_DisplayStringLine(uint8_t Line, uint8_t *ptr);
void LCD_SetDisplayWindow(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_WindowModeDisable(void);
void LCD_DrawLine(uint8_t Xpos, uint16_t Ypos, uint16_t Length, uint8_t Direction);
void LCD_DrawRect(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_DrawCircle(uint8_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_DrawMonoPict(const uint32_t *Pict);
void LCD_WriteBMP(uint32_t BmpAddress);
void LCD_DrawUniLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
void LCD_DrawFullRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height);
void LCD_DrawFullCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_PolyLine(pPoint Points, uint16_t PointCount);
void LCD_PolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLine(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_FillPolyLine(pPoint Points, uint16_t PointCount);
/**
* @}
*/
/** @defgroup
* @{
*/
void LCD_WriteReg(uint8_t LCD_Reg, uint16_t LCD_RegValue);
uint16_t LCD_ReadReg(uint8_t LCD_Reg);
void LCD_WriteRAM_Prepare(void);
void LCD_WriteRAM(uint16_t RGB_Code);
uint16_t LCD_ReadRAM(void);
void LCD_PowerOn(void);
void LCD_DisplayOn(void);
void LCD_DisplayOff(void);
/**
* @}
*/
/** @defgroup
* @{
*/
void LCD_CtrlLinesConfig(void);
void LCD_FSMCConfig(void);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM3210E_EVAL_LCD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_lcd.h
|
C
|
asf20
| 11,137
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_nor.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the
* stm3210e_eval_fsmc_nor firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210E_EVAL_FSMC_NOR_H
#define __STM3210E_EVAL_FSMC_NOR_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_NOR
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Exported_Types
* @{
*/
typedef struct
{
uint16_t Manufacturer_Code;
uint16_t Device_Code1;
uint16_t Device_Code2;
uint16_t Device_Code3;
}NOR_IDTypeDef;
/* NOR Status */
typedef enum
{
NOR_SUCCESS = 0,
NOR_ONGOING,
NOR_ERROR,
NOR_TIMEOUT
}NOR_Status;
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Exported_Constants
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Exported_Functions
* @{
*/
void NOR_Init(void);
void NOR_ReadID(NOR_IDTypeDef* NOR_ID);
NOR_Status NOR_EraseBlock(uint32_t BlockAddr);
NOR_Status NOR_EraseChip(void);
NOR_Status NOR_WriteHalfWord(uint32_t WriteAddr, uint16_t Data);
NOR_Status NOR_WriteBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite);
NOR_Status NOR_ProgramBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite);
uint16_t NOR_ReadHalfWord(uint32_t ReadAddr);
void NOR_ReadBuffer(uint16_t* pBuffer, uint32_t ReadAddr, uint32_t NumHalfwordToRead);
NOR_Status NOR_ReturnToReadMode(void);
NOR_Status NOR_Reset(void);
NOR_Status NOR_GetStatus(uint32_t Timeout);
#ifdef __cplusplus
}
#endif
#endif /* __STM3210E_EVAL_FSMC_NOR_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_nor.h
|
C
|
asf20
| 3,030
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_nand.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the
* stm3210e_eval_fsmc_nand firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210E_EVAL_FSMC_NAND_H
#define __STM3210E_EVAL_FSMC_NAND_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_NAND
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Exported_Types
* @{
*/
typedef struct
{
uint8_t Maker_ID;
uint8_t Device_ID;
uint8_t Third_ID;
uint8_t Fourth_ID;
}NAND_IDTypeDef;
typedef struct
{
uint16_t Zone;
uint16_t Block;
uint16_t Page;
} NAND_ADDRESS;
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Exported_Constants
* @{
*/
/**
* @brief NAND Area definition for STM3210E-EVAL Board RevD
*/
#define CMD_AREA (uint32_t)(1<<16) /* A16 = CLE high */
#define ADDR_AREA (uint32_t)(1<<17) /* A17 = ALE high */
#define DATA_AREA ((uint32_t)0x00000000)
/**
* @brief FSMC NAND memory command
*/
#define NAND_CMD_AREA_A ((uint8_t)0x00)
#define NAND_CMD_AREA_B ((uint8_t)0x01)
#define NAND_CMD_AREA_C ((uint8_t)0x50)
#define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30)
#define NAND_CMD_WRITE0 ((uint8_t)0x80)
#define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10)
#define NAND_CMD_ERASE0 ((uint8_t)0x60)
#define NAND_CMD_ERASE1 ((uint8_t)0xD0)
#define NAND_CMD_READID ((uint8_t)0x90)
#define NAND_CMD_STATUS ((uint8_t)0x70)
#define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A)
#define NAND_CMD_RESET ((uint8_t)0xFF)
/**
* @brief NAND memory status
*/
#define NAND_VALID_ADDRESS ((uint32_t)0x00000100)
#define NAND_INVALID_ADDRESS ((uint32_t)0x00000200)
#define NAND_TIMEOUT_ERROR ((uint32_t)0x00000400)
#define NAND_BUSY ((uint32_t)0x00000000)
#define NAND_ERROR ((uint32_t)0x00000001)
#define NAND_READY ((uint32_t)0x00000040)
/**
* @brief FSMC NAND memory parameters
*/
#define NAND_PAGE_SIZE ((uint16_t)0x0200) /* 512 bytes per page w/o Spare Area */
#define NAND_BLOCK_SIZE ((uint16_t)0x0020) /* 32x512 bytes pages per block */
#define NAND_ZONE_SIZE ((uint16_t)0x0400) /* 1024 Block per zone */
#define NAND_SPARE_AREA_SIZE ((uint16_t)0x0010) /* last 16 bytes as spare area */
#define NAND_MAX_ZONE ((uint16_t)0x0004) /* 4 zones of 1024 block */
/**
* @brief FSMC NAND memory address computation
*/
#define ADDR_1st_CYCLE(ADDR) (uint8_t)((ADDR)& 0xFF) /* 1st addressing cycle */
#define ADDR_2nd_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF00) >> 8) /* 2nd addressing cycle */
#define ADDR_3rd_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF0000) >> 16) /* 3rd addressing cycle */
#define ADDR_4th_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF000000) >> 24) /* 4th addressing cycle */
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NAND_Exported_Functions
* @{
*/
void NAND_Init(void);
void NAND_ReadID(NAND_IDTypeDef* NAND_ID);
uint32_t NAND_WriteSmallPage(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToWrite);
uint32_t NAND_ReadSmallPage (uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToRead);
uint32_t NAND_WriteSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaTowrite);
uint32_t NAND_ReadSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaToRead);
uint32_t NAND_EraseBlock(NAND_ADDRESS Address);
uint32_t NAND_Reset(void);
uint32_t NAND_GetStatus(void);
uint32_t NAND_ReadStatus(void);
uint32_t NAND_AddressIncrement(NAND_ADDRESS* Address);
#ifdef __cplusplus
}
#endif
#endif /* __STM3210E_EVAL_FSMC_NAND_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_nand.h
|
C
|
asf20
| 5,353
|
/**
******************************************************************************
* @file stm3210e_eval_fsmc_nor.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to drive the M29W128FL,
* M29W128GL and S29GL128P NOR memories mounted on STM3210E-EVAL board.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210e_eval_fsmc_nor.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL_FSMC_NOR
* @brief This file provides a set of functions needed to drive the M29W128FL,
* M29W128GL and S29GL128P NOR memories mounted on STM3210E-EVAL board.
* @{
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Private_Defines
* @{
*/
/**
* @brief FSMC Bank 1 NOR/SRAM2
*/
#define Bank1_NOR2_ADDR ((uint32_t)0x64000000)
/* Delay definition */
#define BlockErase_Timeout ((uint32_t)0x00A00000)
#define ChipErase_Timeout ((uint32_t)0x30000000)
#define Program_Timeout ((uint32_t)0x00001400)
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Private_Macros
* @{
*/
#define ADDR_SHIFT(A) (Bank1_NOR2_ADDR + (2 * (A)))
#define NOR_WRITE(Address, Data) (*(__IO uint16_t *)(Address) = (Data))
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroupSTM3210E_EVAL_FSMC_NOR_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_FSMC_NOR_Private_Functions
* @{
*/
/**
* @brief Configures the FSMC and GPIOs to interface with the NOR memory.
* This function must be called before any write/read operation
* on the NOR.
* @param None
* @retval None
*/
void NOR_Init(void)
{
FSMC_NORSRAMInitTypeDef FSMC_NORSRAMInitStructure;
FSMC_NORSRAMTimingInitTypeDef p;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE |
RCC_APB2Periph_GPIOF | RCC_APB2Periph_GPIOG, ENABLE);
/*-- GPIO Configuration ------------------------------------------------------*/
/*!< NOR Data lines configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_8 | GPIO_Pin_9 |
GPIO_Pin_10 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 |
GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13 |
GPIO_Pin_14 | GPIO_Pin_15;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*!< NOR Address lines configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 |
GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_12 | GPIO_Pin_13 |
GPIO_Pin_14 | GPIO_Pin_15;
GPIO_Init(GPIOF, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 |
GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_Init(GPIOG, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*!< NOE and NWE configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< NE2 configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_Init(GPIOG, &GPIO_InitStructure);
/*!< Configure PD6 for NOR memory Ready/Busy signal */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*-- FSMC Configuration ----------------------------------------------------*/
p.FSMC_AddressSetupTime = 0x02;
p.FSMC_AddressHoldTime = 0x00;
p.FSMC_DataSetupTime = 0x05;
p.FSMC_BusTurnAroundDuration = 0x00;
p.FSMC_CLKDivision = 0x00;
p.FSMC_DataLatency = 0x00;
p.FSMC_AccessMode = FSMC_AccessMode_B;
FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM2;
FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_NOR;
FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &p;
FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &p;
FSMC_NORSRAMInit(&FSMC_NORSRAMInitStructure);
/*!< Enable FSMC Bank1_NOR Bank */
FSMC_NORSRAMCmd(FSMC_Bank1_NORSRAM2, ENABLE);
}
/**
* @brief Reads NOR memory's Manufacturer and Device Code.
* @param NOR_ID: pointer to a NOR_IDTypeDef structure which will hold the
* Manufacturer and Device Code.
* @retval None
*/
void NOR_ReadID(NOR_IDTypeDef* NOR_ID)
{
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x0090);
NOR_ID->Manufacturer_Code = *(__IO uint16_t *) ADDR_SHIFT(0x0000);
NOR_ID->Device_Code1 = *(__IO uint16_t *) ADDR_SHIFT(0x0001);
NOR_ID->Device_Code2 = *(__IO uint16_t *) ADDR_SHIFT(0x000E);
NOR_ID->Device_Code3 = *(__IO uint16_t *) ADDR_SHIFT(0x000F);
}
/**
* @brief Erases the specified Nor memory block.
* @param BlockAddr: address of the block to erase.
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_EraseBlock(uint32_t BlockAddr)
{
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x0080);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE((Bank1_NOR2_ADDR + BlockAddr), 0x30);
return (NOR_GetStatus(BlockErase_Timeout));
}
/**
* @brief Erases the entire chip.
* @param None
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_EraseChip(void)
{
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x0080);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x0010);
return (NOR_GetStatus(ChipErase_Timeout));
}
/**
* @brief Writes a half-word to the NOR memory.
* @param WriteAddr: NOR memory internal address to write to.
* @param Data: Data to write.
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_WriteHalfWord(uint32_t WriteAddr, uint16_t Data)
{
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00A0);
NOR_WRITE((Bank1_NOR2_ADDR + WriteAddr), Data);
return (NOR_GetStatus(Program_Timeout));
}
/**
* @brief Writes a half-word buffer to the FSMC NOR memory.
* @param pBuffer: pointer to buffer.
* @param WriteAddr: NOR memory internal address from which the data will be
* written.
* @param NumHalfwordToWrite: number of Half words to write.
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_WriteBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite)
{
NOR_Status status = NOR_ONGOING;
do
{
/*!< Transfer data to the memory */
status = NOR_WriteHalfWord(WriteAddr, *pBuffer++);
WriteAddr = WriteAddr + 2;
NumHalfwordToWrite--;
}
while((status == NOR_SUCCESS) && (NumHalfwordToWrite != 0));
return (status);
}
/**
* @brief Writes a half-word buffer to the FSMC NOR memory. This function
* must be used only with S29GL128P NOR memory.
* @param pBuffer: pointer to buffer.
* @param WriteAddr: NOR memory internal address from which the data will be
* written.
* @param NumHalfwordToWrite: number of Half words to write.
* The maximum allowed value is 32 Half words (64 bytes).
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_ProgramBuffer(uint16_t* pBuffer, uint32_t WriteAddr, uint32_t NumHalfwordToWrite)
{
uint32_t lastloadedaddress = 0x00;
uint32_t currentaddress = 0x00;
uint32_t endaddress = 0x00;
/*!< Initialize variables */
currentaddress = WriteAddr;
endaddress = WriteAddr + NumHalfwordToWrite - 1;
lastloadedaddress = WriteAddr;
/*!< Issue unlock command sequence */
NOR_WRITE(ADDR_SHIFT(0x00555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
/*!< Write Write Buffer Load Command */
NOR_WRITE(ADDR_SHIFT(WriteAddr), 0x0025);
NOR_WRITE(ADDR_SHIFT(WriteAddr), (NumHalfwordToWrite - 1));
/*!< Load Data into NOR Buffer */
while(currentaddress <= endaddress)
{
/*!< Store last loaded address & data value (for polling) */
lastloadedaddress = currentaddress;
NOR_WRITE(ADDR_SHIFT(currentaddress), *pBuffer++);
currentaddress += 1;
}
NOR_WRITE(ADDR_SHIFT(lastloadedaddress), 0x29);
return(NOR_GetStatus(Program_Timeout));
}
/**
* @brief Reads a half-word from the NOR memory.
* @param ReadAddr: NOR memory internal address to read from.
* @retval Half-word read from the NOR memory
*/
uint16_t NOR_ReadHalfWord(uint32_t ReadAddr)
{
NOR_WRITE(ADDR_SHIFT(0x00555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x002AA), 0x0055);
NOR_WRITE((Bank1_NOR2_ADDR + ReadAddr), 0x00F0 );
return (*(__IO uint16_t *)((Bank1_NOR2_ADDR + ReadAddr)));
}
/**
* @brief Reads a block of data from the FSMC NOR memory.
* @param pBuffer: pointer to the buffer that receives the data read from the
* NOR memory.
* @param ReadAddr: NOR memory internal address to read from.
* @param NumHalfwordToRead : number of Half word to read.
* @retval None
*/
void NOR_ReadBuffer(uint16_t* pBuffer, uint32_t ReadAddr, uint32_t NumHalfwordToRead)
{
NOR_WRITE(ADDR_SHIFT(0x0555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x02AA), 0x0055);
NOR_WRITE((Bank1_NOR2_ADDR + ReadAddr), 0x00F0);
for(; NumHalfwordToRead != 0x00; NumHalfwordToRead--) /*!< while there is data to read */
{
/*!< Read a Halfword from the NOR */
*pBuffer++ = *(__IO uint16_t *)((Bank1_NOR2_ADDR + ReadAddr));
ReadAddr = ReadAddr + 2;
}
}
/**
* @brief Returns the NOR memory to Read mode.
* @param None
* @retval NOR_SUCCESS
*/
NOR_Status NOR_ReturnToReadMode(void)
{
NOR_WRITE(Bank1_NOR2_ADDR, 0x00F0);
return (NOR_SUCCESS);
}
/**
* @brief Returns the NOR memory to Read mode and resets the errors in the NOR
* memory Status Register.
* @param None
* @retval NOR_SUCCESS
*/
NOR_Status NOR_Reset(void)
{
NOR_WRITE(ADDR_SHIFT(0x00555), 0x00AA);
NOR_WRITE(ADDR_SHIFT(0x002AA), 0x0055);
NOR_WRITE(Bank1_NOR2_ADDR, 0x00F0);
return (NOR_SUCCESS);
}
/**
* @brief Returns the NOR operation status.
* @param Timeout: NOR progamming Timeout
* @retval NOR_Status: The returned value can be: NOR_SUCCESS, NOR_ERROR
* or NOR_TIMEOUT
*/
NOR_Status NOR_GetStatus(uint32_t Timeout)
{
uint16_t val1 = 0x00, val2 = 0x00;
NOR_Status status = NOR_ONGOING;
uint32_t timeout = Timeout;
/*!< Poll on NOR memory Ready/Busy signal ----------------------------------*/
while((GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) != RESET) && (timeout > 0))
{
timeout--;
}
timeout = Timeout;
while((GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) == RESET) && (timeout > 0))
{
timeout--;
}
/*!< Get the NOR memory operation status -----------------------------------*/
while((Timeout != 0x00) && (status != NOR_SUCCESS))
{
Timeout--;
/*!< Read DQ6 and DQ5 */
val1 = *(__IO uint16_t *)(Bank1_NOR2_ADDR);
val2 = *(__IO uint16_t *)(Bank1_NOR2_ADDR);
/*!< If DQ6 did not toggle between the two reads then return NOR_Success */
if((val1 & 0x0040) == (val2 & 0x0040))
{
return NOR_SUCCESS;
}
if((val1 & 0x0020) != 0x0020)
{
status = NOR_ONGOING;
}
val1 = *(__IO uint16_t *)(Bank1_NOR2_ADDR);
val2 = *(__IO uint16_t *)(Bank1_NOR2_ADDR);
if((val1 & 0x0040) == (val2 & 0x0040))
{
return NOR_SUCCESS;
}
else if((val1 & 0x0020) == 0x0020)
{
return NOR_ERROR;
}
}
if(Timeout == 0x00)
{
status = NOR_TIMEOUT;
}
/*!< Return the operation status */
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval_fsmc_nor.c
|
C
|
asf20
| 14,774
|
/**
******************************************************************************
* @file stm3210e_eval.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides
* - set of firmware functions to manage Leds, push-button and COM ports
* - low level initialization functions for SD card (on SDIO), SPI serial
* flash (sFLASH) and temperature sensor (LM75)
* available on STM3210E-EVAL evaluation board from STMicroelectronics.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210e_eval.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_i2c.h"
#include "stm32f10x_sdio.h"
#include "stm32f10x_dma.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210E_EVAL
* @{
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL
* @brief This file provides firmware functions to manage Leds, push-buttons,
* COM ports, SD card on SDIO, serial flash (sFLASH), serial EEPROM (sEE)
* and temperature sensor (LM75) available on STM3210E-EVAL evaluation
* board from STMicroelectronics.
* @{
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_Variables
* @{
*/
GPIO_TypeDef* GPIO_PORT[LEDn] = {LED1_GPIO_PORT, LED2_GPIO_PORT, LED3_GPIO_PORT,
LED4_GPIO_PORT};
const uint16_t GPIO_PIN[LEDn] = {LED1_PIN, LED2_PIN, LED3_PIN,
LED4_PIN};
const uint32_t GPIO_CLK[LEDn] = {LED1_GPIO_CLK, LED2_GPIO_CLK, LED3_GPIO_CLK,
LED4_GPIO_CLK};
GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {WAKEUP_BUTTON_GPIO_PORT, TAMPER_BUTTON_GPIO_PORT,
KEY_BUTTON_GPIO_PORT, RIGHT_BUTTON_GPIO_PORT,
LEFT_BUTTON_GPIO_PORT, UP_BUTTON_GPIO_PORT,
DOWN_BUTTON_GPIO_PORT, SEL_BUTTON_GPIO_PORT};
const uint16_t BUTTON_PIN[BUTTONn] = {WAKEUP_BUTTON_PIN, TAMPER_BUTTON_PIN,
KEY_BUTTON_PIN, RIGHT_BUTTON_PIN,
LEFT_BUTTON_PIN, UP_BUTTON_PIN,
DOWN_BUTTON_PIN, SEL_BUTTON_PIN};
const uint32_t BUTTON_CLK[BUTTONn] = {WAKEUP_BUTTON_GPIO_CLK, TAMPER_BUTTON_GPIO_CLK,
KEY_BUTTON_GPIO_CLK, RIGHT_BUTTON_GPIO_CLK,
LEFT_BUTTON_GPIO_CLK, UP_BUTTON_GPIO_CLK,
DOWN_BUTTON_GPIO_CLK, SEL_BUTTON_GPIO_CLK};
const uint16_t BUTTON_EXTI_LINE[BUTTONn] = {WAKEUP_BUTTON_EXTI_LINE,
TAMPER_BUTTON_EXTI_LINE,
KEY_BUTTON_EXTI_LINE,
RIGHT_BUTTON_EXTI_LINE,
LEFT_BUTTON_EXTI_LINE,
UP_BUTTON_EXTI_LINE,
DOWN_BUTTON_EXTI_LINE,
SEL_BUTTON_EXTI_LINE};
const uint16_t BUTTON_PORT_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PORT_SOURCE,
TAMPER_BUTTON_EXTI_PORT_SOURCE,
KEY_BUTTON_EXTI_PORT_SOURCE,
RIGHT_BUTTON_EXTI_PORT_SOURCE,
LEFT_BUTTON_EXTI_PORT_SOURCE,
UP_BUTTON_EXTI_PORT_SOURCE,
DOWN_BUTTON_EXTI_PORT_SOURCE,
SEL_BUTTON_EXTI_PORT_SOURCE};
const uint16_t BUTTON_PIN_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PIN_SOURCE,
TAMPER_BUTTON_EXTI_PIN_SOURCE,
KEY_BUTTON_EXTI_PIN_SOURCE,
RIGHT_BUTTON_EXTI_PIN_SOURCE,
LEFT_BUTTON_EXTI_PIN_SOURCE,
UP_BUTTON_EXTI_PIN_SOURCE,
DOWN_BUTTON_EXTI_PIN_SOURCE,
SEL_BUTTON_EXTI_PIN_SOURCE};
const uint16_t BUTTON_IRQn[BUTTONn] = {WAKEUP_BUTTON_EXTI_IRQn, TAMPER_BUTTON_EXTI_IRQn,
KEY_BUTTON_EXTI_IRQn, RIGHT_BUTTON_EXTI_IRQn,
LEFT_BUTTON_EXTI_IRQn, UP_BUTTON_EXTI_IRQn,
DOWN_BUTTON_EXTI_IRQn, SEL_BUTTON_EXTI_IRQn};
USART_TypeDef* COM_USART[COMn] = {EVAL_COM1, EVAL_COM2};
GPIO_TypeDef* COM_TX_PORT[COMn] = {EVAL_COM1_TX_GPIO_PORT, EVAL_COM2_TX_GPIO_PORT};
GPIO_TypeDef* COM_RX_PORT[COMn] = {EVAL_COM1_RX_GPIO_PORT, EVAL_COM2_RX_GPIO_PORT};
const uint32_t COM_USART_CLK[COMn] = {EVAL_COM1_CLK, EVAL_COM2_CLK};
const uint32_t COM_TX_PORT_CLK[COMn] = {EVAL_COM1_TX_GPIO_CLK, EVAL_COM2_TX_GPIO_CLK};
const uint32_t COM_RX_PORT_CLK[COMn] = {EVAL_COM1_RX_GPIO_CLK, EVAL_COM2_RX_GPIO_CLK};
const uint16_t COM_TX_PIN[COMn] = {EVAL_COM1_TX_PIN, EVAL_COM2_TX_PIN};
const uint16_t COM_RX_PIN[COMn] = {EVAL_COM1_RX_PIN, EVAL_COM2_RX_PIN};
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210E_EVAL_LOW_LEVEL_Private_Functions
* @{
*/
/**
* @brief Configures LED GPIO.
* @param Led: Specifies the Led to be configured.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDInit(Led_TypeDef Led)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable the GPIO_LED Clock */
RCC_APB2PeriphClockCmd(GPIO_CLK[Led], ENABLE);
/* Configure the GPIO_LED pin */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN[Led];
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIO_PORT[Led], &GPIO_InitStructure);
}
/**
* @brief Turns selected LED On.
* @param Led: Specifies the Led to be set on.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOn(Led_TypeDef Led)
{
GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}
/**
* @brief Turns selected LED Off.
* @param Led: Specifies the Led to be set off.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOff(Led_TypeDef Led)
{
GPIO_PORT[Led]->BRR = GPIO_PIN[Led];
}
/**
* @brief Toggles the selected LED.
* @param Led: Specifies the Led to be toggled.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDToggle(Led_TypeDef Led)
{
GPIO_PORT[Led]->ODR ^= GPIO_PIN[Led];
}
/**
* @brief Configures Button GPIO and EXTI Line.
* @param Button: Specifies the Button to be configured.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @param Button_Mode: Specifies Button mode.
* This parameter can be one of following parameters:
* @arg BUTTON_MODE_GPIO: Button will be used as simple IO
* @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
* generation capability
* @retval None
*/
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the BUTTON Clock */
RCC_APB2PeriphClockCmd(BUTTON_CLK[Button] | RCC_APB2Periph_AFIO, ENABLE);
/* Configure Button pin as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN[Button];
GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStructure);
if (Button_Mode == BUTTON_MODE_EXTI)
{
/* Connect Button EXTI Line to Button GPIO Pin */
GPIO_EXTILineConfig(BUTTON_PORT_SOURCE[Button], BUTTON_PIN_SOURCE[Button]);
/* Configure Button EXTI line */
EXTI_InitStructure.EXTI_Line = BUTTON_EXTI_LINE[Button];
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
if(Button != BUTTON_WAKEUP)
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
}
else
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
}
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set Button EXTI Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = BUTTON_IRQn[Button];
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
}
/**
* @brief Returns the selected Button state.
* @param Button: Specifies the Button to be checked.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @retval The Button GPIO pin value.
*/
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button)
{
return GPIO_ReadInputDataBit(BUTTON_PORT[Button], BUTTON_PIN[Button]);
}
/**
* @brief Configures COM port.
* @param COM: Specifies the COM port to be configured.
* This parameter can be one of following parameters:
* @arg COM1
* @arg COM2
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure that
* contains the configuration information for the specified USART peripheral.
* @retval None
*/
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_APB2PeriphClockCmd(COM_TX_PORT_CLK[COM] | COM_RX_PORT_CLK[COM] | RCC_APB2Periph_AFIO, ENABLE);
/* Enable UART clock */
if (COM == COM1)
{
RCC_APB2PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
else
{
RCC_APB1PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = COM_TX_PIN[COM];
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = COM_RX_PIN[COM];
GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);
/* USART configuration */
USART_Init(COM_USART[COM], USART_InitStruct);
/* Enable USART */
USART_Cmd(COM_USART[COM], ENABLE);
}
/**
* @brief DeInitializes the SDIO interface.
* @param None
* @retval None
*/
void SD_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable SDIO Clock */
SDIO_ClockCmd(DISABLE);
/*!< Set Power State to OFF */
SDIO_SetPowerState(SDIO_PowerState_OFF);
/*!< DeInitializes the SDIO peripheral */
SDIO_DeInit();
/*!< Disable the SDIO AHB Clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SDIO, DISABLE);
/*!< Configure PC.08, PC.09, PC.10, PC.11, PC.12 pin: D0, D1, D2, D3, CLK pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/*!< Configure PD.02 CMD line */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_Init(GPIOD, &GPIO_InitStructure);
}
/**
* @brief Initializes the SD Card and put it into StandBy State (Ready for
* data transfer).
* @param None
* @retval None
*/
void SD_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< GPIOC and GPIOD Periph clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD | SD_DETECT_GPIO_CLK, ENABLE);
/*!< Configure PC.08, PC.09, PC.10, PC.11, PC.12 pin: D0, D1, D2, D3, CLK pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/*!< Configure PD.02 CMD line */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
/*!< Enable the SDIO AHB Clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SDIO, ENABLE);
/*!< Enable the DMA2 Clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);
}
/**
* @brief Configures the DMA2 Channel4 for SDIO Tx request.
* @param BufferSRC: pointer to the source buffer
* @param BufferSize: buffer size
* @retval None
*/
void SD_LowLevel_DMA_TxConfig(uint32_t *BufferSRC, uint32_t BufferSize)
{
DMA_InitTypeDef DMA_InitStructure;
DMA_ClearFlag(DMA2_FLAG_TC4 | DMA2_FLAG_TE4 | DMA2_FLAG_HT4 | DMA2_FLAG_GL4);
/*!< DMA2 Channel4 disable */
DMA_Cmd(DMA2_Channel4, DISABLE);
/*!< DMA2 Channel4 Config */
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SDIO_FIFO_ADDRESS;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)BufferSRC;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = BufferSize / 4;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA2_Channel4, &DMA_InitStructure);
/*!< DMA2 Channel4 enable */
DMA_Cmd(DMA2_Channel4, ENABLE);
}
/**
* @brief Configures the DMA2 Channel4 for SDIO Rx request.
* @param BufferDST: pointer to the destination buffer
* @param BufferSize: buffer size
* @retval None
*/
void SD_LowLevel_DMA_RxConfig(uint32_t *BufferDST, uint32_t BufferSize)
{
DMA_InitTypeDef DMA_InitStructure;
DMA_ClearFlag(DMA2_FLAG_TC4 | DMA2_FLAG_TE4 | DMA2_FLAG_HT4 | DMA2_FLAG_GL4);
/*!< DMA2 Channel4 disable */
DMA_Cmd(DMA2_Channel4, DISABLE);
/*!< DMA2 Channel4 Config */
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SDIO_FIFO_ADDRESS;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)BufferDST;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = BufferSize / 4;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Word;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA2_Channel4, &DMA_InitStructure);
/*!< DMA2 Channel4 enable */
DMA_Cmd(DMA2_Channel4, ENABLE);
}
/**
* @brief Wait For DMA End Of Transfer.
* @param None
* @retval None
*/
void SD_WaitForDMAEndOfTransfer(void)
{
while (DMA_GetFlagStatus(DMA2_FLAG_TC4) == RESET)
{}
}
/**
* @brief DeInitializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable the sFLASH_SPI */
SPI_Cmd(sFLASH_SPI, DISABLE);
/*!< DeInitializes the sFLASH_SPI */
SPI_I2S_DeInit(sFLASH_SPI);
/*!< sFLASH_SPI Periph clock disable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, DISABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< sFLASH_SPI_CS_GPIO, sFLASH_SPI_MOSI_GPIO, sFLASH_SPI_MISO_GPIO
and sFLASH_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_CS_GPIO_CLK | sFLASH_SPI_MOSI_GPIO_CLK | sFLASH_SPI_MISO_GPIO_CLK |
sFLASH_SPI_SCK_GPIO_CLK, ENABLE);
/*!< sFLASH_SPI Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, ENABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief DeInitializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable LM75_I2C */
I2C_Cmd(LM75_I2C, DISABLE);
/*!< DeInitializes the LM75_I2C */
I2C_DeInit(LM75_I2C);
/*!< LM75_I2C Periph clock disable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, DISABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the LM75_I2C..
* @param None
* @retval None
*/
void LM75_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< LM75_I2C Periph clock enable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, ENABLE);
/*!< LM75_I2C_SCL_GPIO_CLK, LM75_I2C_SDA_GPIO_CLK
and LM75_I2C_SMBUSALERT_GPIO_CLK Periph clock enable */
RCC_APB2PeriphClockCmd(LM75_I2C_SCL_GPIO_CLK | LM75_I2C_SDA_GPIO_CLK |
LM75_I2C_SMBUSALERT_GPIO_CLK, ENABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210E_EVAL/stm3210e_eval.c
|
C
|
asf20
| 22,683
|
/**
******************************************************************************
* @file fonts.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides text fonts for STM32xx-EVAL's LCD driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "fonts.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup FONTS
* @brief This file includes the Fonts driver of STM32-EVAL boards.
* @{
*/
/** @defgroup FONTS_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup FONTS_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup FONTS_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup FONTS_Private_Variables
* @{
*/
const uint16_t ASCII16x24_Table [] = {
/**
* @brief Space ' '
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '!'
*/
0x0000, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0000, 0x0000,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '"'
*/
0x0000, 0x0000, 0x00CC, 0x00CC, 0x00CC, 0x00CC, 0x00CC, 0x00CC,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '#'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C60, 0x0C60,
0x0C60, 0x0630, 0x0630, 0x1FFE, 0x1FFE, 0x0630, 0x0738, 0x0318,
0x1FFE, 0x1FFE, 0x0318, 0x0318, 0x018C, 0x018C, 0x018C, 0x0000,
/**
* @brief '$'
*/
0x0000, 0x0080, 0x03E0, 0x0FF8, 0x0E9C, 0x1C8C, 0x188C, 0x008C,
0x0098, 0x01F8, 0x07E0, 0x0E80, 0x1C80, 0x188C, 0x188C, 0x189C,
0x0CB8, 0x0FF0, 0x03E0, 0x0080, 0x0080, 0x0000, 0x0000, 0x0000,
/**
* @brief '%'
*/
0x0000, 0x0000, 0x0000, 0x180E, 0x0C1B, 0x0C11, 0x0611, 0x0611,
0x0311, 0x0311, 0x019B, 0x018E, 0x38C0, 0x6CC0, 0x4460, 0x4460,
0x4430, 0x4430, 0x4418, 0x6C18, 0x380C, 0x0000, 0x0000, 0x0000,
/**
* @brief '&'
*/
0x0000, 0x01E0, 0x03F0, 0x0738, 0x0618, 0x0618, 0x0330, 0x01F0,
0x00F0, 0x00F8, 0x319C, 0x330E, 0x1E06, 0x1C06, 0x1C06, 0x3F06,
0x73FC, 0x21F0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '''
*/
0x0000, 0x0000, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '('
*/
0x0000, 0x0200, 0x0300, 0x0180, 0x00C0, 0x00C0, 0x0060, 0x0060,
0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
0x0060, 0x0060, 0x00C0, 0x00C0, 0x0180, 0x0300, 0x0200, 0x0000,
/**
* @brief ')'
*/
0x0000, 0x0020, 0x0060, 0x00C0, 0x0180, 0x0180, 0x0300, 0x0300,
0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600,
0x0300, 0x0300, 0x0180, 0x0180, 0x00C0, 0x0060, 0x0020, 0x0000,
/**
* @brief '*'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x00C0, 0x00C0,
0x06D8, 0x07F8, 0x01E0, 0x0330, 0x0738, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '+'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x3FFC, 0x3FFC, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief ','
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0180, 0x0180, 0x0100, 0x0100, 0x0080, 0x0000, 0x0000,
/**
* @brief '-'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x07E0, 0x07E0, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '.'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '/'
*/
0x0000, 0x0C00, 0x0C00, 0x0600, 0x0600, 0x0600, 0x0300, 0x0300,
0x0300, 0x0380, 0x0180, 0x0180, 0x0180, 0x00C0, 0x00C0, 0x00C0,
0x0060, 0x0060, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '0'
*/
0x0000, 0x03E0, 0x07F0, 0x0E38, 0x0C18, 0x180C, 0x180C, 0x180C,
0x180C, 0x180C, 0x180C, 0x180C, 0x180C, 0x180C, 0x0C18, 0x0E38,
0x07F0, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '1'
*/
0x0000, 0x0100, 0x0180, 0x01C0, 0x01F0, 0x0198, 0x0188, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '2'
*/
0x0000, 0x03E0, 0x0FF8, 0x0C18, 0x180C, 0x180C, 0x1800, 0x1800,
0x0C00, 0x0600, 0x0300, 0x0180, 0x00C0, 0x0060, 0x0030, 0x0018,
0x1FFC, 0x1FFC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '3'
*/
0x0000, 0x01E0, 0x07F8, 0x0E18, 0x0C0C, 0x0C0C, 0x0C00, 0x0600,
0x03C0, 0x07C0, 0x0C00, 0x1800, 0x1800, 0x180C, 0x180C, 0x0C18,
0x07F8, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '4'
*/
0x0000, 0x0C00, 0x0E00, 0x0F00, 0x0F00, 0x0D80, 0x0CC0, 0x0C60,
0x0C60, 0x0C30, 0x0C18, 0x0C0C, 0x3FFC, 0x3FFC, 0x0C00, 0x0C00,
0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '5'
*/
0x0000, 0x0FF8, 0x0FF8, 0x0018, 0x0018, 0x000C, 0x03EC, 0x07FC,
0x0E1C, 0x1C00, 0x1800, 0x1800, 0x1800, 0x180C, 0x0C1C, 0x0E18,
0x07F8, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '6'
*/
0x0000, 0x07C0, 0x0FF0, 0x1C38, 0x1818, 0x0018, 0x000C, 0x03CC,
0x0FEC, 0x0E3C, 0x1C1C, 0x180C, 0x180C, 0x180C, 0x1C18, 0x0E38,
0x07F0, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '7'
*/
0x0000, 0x1FFC, 0x1FFC, 0x0C00, 0x0600, 0x0600, 0x0300, 0x0380,
0x0180, 0x01C0, 0x00C0, 0x00E0, 0x0060, 0x0060, 0x0070, 0x0030,
0x0030, 0x0030, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '8'
*/
0x0000, 0x03E0, 0x07F0, 0x0E38, 0x0C18, 0x0C18, 0x0C18, 0x0638,
0x07F0, 0x07F0, 0x0C18, 0x180C, 0x180C, 0x180C, 0x180C, 0x0C38,
0x0FF8, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '9'
*/
0x0000, 0x03E0, 0x07F0, 0x0E38, 0x0C1C, 0x180C, 0x180C, 0x180C,
0x1C1C, 0x1E38, 0x1BF8, 0x19E0, 0x1800, 0x0C00, 0x0C00, 0x0E1C,
0x07F8, 0x01F0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief ':'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0180, 0x0180,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief ';'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0180, 0x0180,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0180, 0x0180, 0x0100, 0x0100, 0x0080, 0x0000, 0x0000, 0x0000,
/**
* @brief '<'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x1000, 0x1C00, 0x0F80, 0x03E0, 0x00F8, 0x0018, 0x00F8, 0x03E0,
0x0F80, 0x1C00, 0x1000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '='
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x1FF8, 0x0000, 0x0000, 0x0000, 0x1FF8, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '>'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0008, 0x0038, 0x01F0, 0x07C0, 0x1F00, 0x1800, 0x1F00, 0x07C0,
0x01F0, 0x0038, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '?'
*/
0x0000, 0x03E0, 0x0FF8, 0x0C18, 0x180C, 0x180C, 0x1800, 0x0C00,
0x0600, 0x0300, 0x0180, 0x00C0, 0x00C0, 0x00C0, 0x0000, 0x0000,
0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '@'
*/
0x0000, 0x0000, 0x07E0, 0x1818, 0x2004, 0x29C2, 0x4A22, 0x4411,
0x4409, 0x4409, 0x4409, 0x2209, 0x1311, 0x0CE2, 0x4002, 0x2004,
0x1818, 0x07E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'A'
*/
0x0000, 0x0380, 0x0380, 0x06C0, 0x06C0, 0x06C0, 0x0C60, 0x0C60,
0x1830, 0x1830, 0x1830, 0x3FF8, 0x3FF8, 0x701C, 0x600C, 0x600C,
0xC006, 0xC006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'B'
*/
0x0000, 0x03FC, 0x0FFC, 0x0C0C, 0x180C, 0x180C, 0x180C, 0x0C0C,
0x07FC, 0x0FFC, 0x180C, 0x300C, 0x300C, 0x300C, 0x300C, 0x180C,
0x1FFC, 0x07FC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'C'
*/
0x0000, 0x07C0, 0x1FF0, 0x3838, 0x301C, 0x700C, 0x6006, 0x0006,
0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x6006, 0x700C, 0x301C,
0x1FF0, 0x07E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'D'
*/
0x0000, 0x03FE, 0x0FFE, 0x0E06, 0x1806, 0x1806, 0x3006, 0x3006,
0x3006, 0x3006, 0x3006, 0x3006, 0x3006, 0x1806, 0x1806, 0x0E06,
0x0FFE, 0x03FE, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'E'
*/
0x0000, 0x3FFC, 0x3FFC, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x1FFC, 0x1FFC, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x3FFC, 0x3FFC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'F'
*/
0x0000, 0x3FF8, 0x3FF8, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018,
0x1FF8, 0x1FF8, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018,
0x0018, 0x0018, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'G'
*/
0x0000, 0x0FE0, 0x3FF8, 0x783C, 0x600E, 0xE006, 0xC007, 0x0003,
0x0003, 0xFE03, 0xFE03, 0xC003, 0xC007, 0xC006, 0xC00E, 0xF03C,
0x3FF8, 0x0FE0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'H'
*/
0x0000, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C,
0x3FFC, 0x3FFC, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C,
0x300C, 0x300C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'I'
*/
0x0000, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'J'
*/
0x0000, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600,
0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0618, 0x0618, 0x0738,
0x03F0, 0x01E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'K'
*/
0x0000, 0x3006, 0x1806, 0x0C06, 0x0606, 0x0306, 0x0186, 0x00C6,
0x0066, 0x0076, 0x00DE, 0x018E, 0x0306, 0x0606, 0x0C06, 0x1806,
0x3006, 0x6006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'L'
*/
0x0000, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018,
0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018,
0x1FF8, 0x1FF8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'M'
*/
0x0000, 0xE00E, 0xF01E, 0xF01E, 0xF01E, 0xD836, 0xD836, 0xD836,
0xD836, 0xCC66, 0xCC66, 0xCC66, 0xC6C6, 0xC6C6, 0xC6C6, 0xC6C6,
0xC386, 0xC386, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'N'
*/
0x0000, 0x300C, 0x301C, 0x303C, 0x303C, 0x306C, 0x306C, 0x30CC,
0x30CC, 0x318C, 0x330C, 0x330C, 0x360C, 0x360C, 0x3C0C, 0x3C0C,
0x380C, 0x300C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'O'
*/
0x0000, 0x07E0, 0x1FF8, 0x381C, 0x700E, 0x6006, 0xC003, 0xC003,
0xC003, 0xC003, 0xC003, 0xC003, 0xC003, 0x6006, 0x700E, 0x381C,
0x1FF8, 0x07E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'P'
*/
0x0000, 0x0FFC, 0x1FFC, 0x380C, 0x300C, 0x300C, 0x300C, 0x300C,
0x180C, 0x1FFC, 0x07FC, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x000C, 0x000C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'Q'
*/
0x0000, 0x07E0, 0x1FF8, 0x381C, 0x700E, 0x6006, 0xE003, 0xC003,
0xC003, 0xC003, 0xC003, 0xC003, 0xE007, 0x6306, 0x3F0E, 0x3C1C,
0x3FF8, 0xF7E0, 0xC000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'R'
*/
0x0000, 0x0FFE, 0x1FFE, 0x3806, 0x3006, 0x3006, 0x3006, 0x3806,
0x1FFE, 0x07FE, 0x0306, 0x0606, 0x0C06, 0x1806, 0x1806, 0x3006,
0x3006, 0x6006, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'S'
*/
0x0000, 0x03E0, 0x0FF8, 0x0C1C, 0x180C, 0x180C, 0x000C, 0x001C,
0x03F8, 0x0FE0, 0x1E00, 0x3800, 0x3006, 0x3006, 0x300E, 0x1C1C,
0x0FF8, 0x07E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'T'
*/
0x0000, 0x7FFE, 0x7FFE, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'U'
*/
0x0000, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C,
0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x300C, 0x1818,
0x1FF8, 0x07E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'V'
*/
0x0000, 0x6003, 0x3006, 0x3006, 0x3006, 0x180C, 0x180C, 0x180C,
0x0C18, 0x0C18, 0x0E38, 0x0630, 0x0630, 0x0770, 0x0360, 0x0360,
0x01C0, 0x01C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'W'
*/
0x0000, 0x6003, 0x61C3, 0x61C3, 0x61C3, 0x3366, 0x3366, 0x3366,
0x3366, 0x3366, 0x3366, 0x1B6C, 0x1B6C, 0x1B6C, 0x1A2C, 0x1E3C,
0x0E38, 0x0E38, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'X'
*/
0x0000, 0xE00F, 0x700C, 0x3018, 0x1830, 0x0C70, 0x0E60, 0x07C0,
0x0380, 0x0380, 0x03C0, 0x06E0, 0x0C70, 0x1C30, 0x1818, 0x300C,
0x600E, 0xE007, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'Y'
*/
0x0000, 0xC003, 0x6006, 0x300C, 0x381C, 0x1838, 0x0C30, 0x0660,
0x07E0, 0x03C0, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'Z'
*/
0x0000, 0x7FFC, 0x7FFC, 0x6000, 0x3000, 0x1800, 0x0C00, 0x0600,
0x0300, 0x0180, 0x00C0, 0x0060, 0x0030, 0x0018, 0x000C, 0x0006,
0x7FFE, 0x7FFE, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '['
*/
0x0000, 0x03E0, 0x03E0, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060,
0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x0060,
0x0060, 0x0060, 0x0060, 0x0060, 0x0060, 0x03E0, 0x03E0, 0x0000,
/**
* @brief '\'
*/
0x0000, 0x0030, 0x0030, 0x0060, 0x0060, 0x0060, 0x00C0, 0x00C0,
0x00C0, 0x01C0, 0x0180, 0x0180, 0x0180, 0x0300, 0x0300, 0x0300,
0x0600, 0x0600, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief ']'
*/
0x0000, 0x03E0, 0x03E0, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300,
0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300,
0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x03E0, 0x03E0, 0x0000,
/**
* @brief '^'
*/
0x0000, 0x0000, 0x01C0, 0x01C0, 0x0360, 0x0360, 0x0360, 0x0630,
0x0630, 0x0C18, 0x0C18, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '_'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0xFFFF, 0xFFFF, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '''
*/
0x0000, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'a'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03F0, 0x07F8,
0x0C1C, 0x0C0C, 0x0F00, 0x0FF0, 0x0CF8, 0x0C0C, 0x0C0C, 0x0F1C,
0x0FF8, 0x18F0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'b'
*/
0x0000, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x03D8, 0x0FF8,
0x0C38, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x0C38,
0x0FF8, 0x03D8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'c'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03C0, 0x07F0,
0x0E30, 0x0C18, 0x0018, 0x0018, 0x0018, 0x0018, 0x0C18, 0x0E30,
0x07F0, 0x03C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'd'
*/
0x0000, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1BC0, 0x1FF0,
0x1C30, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1C30,
0x1FF0, 0x1BC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'e'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03C0, 0x0FF0,
0x0C30, 0x1818, 0x1FF8, 0x1FF8, 0x0018, 0x0018, 0x1838, 0x1C30,
0x0FF0, 0x07C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'f'
*/
0x0000, 0x0F80, 0x0FC0, 0x00C0, 0x00C0, 0x00C0, 0x07F0, 0x07F0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'g'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0DE0, 0x0FF8,
0x0E18, 0x0C0C, 0x0C0C, 0x0C0C, 0x0C0C, 0x0C0C, 0x0C0C, 0x0E18,
0x0FF8, 0x0DE0, 0x0C00, 0x0C0C, 0x061C, 0x07F8, 0x01F0, 0x0000,
/**
* @brief 'h'
*/
0x0000, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x07D8, 0x0FF8,
0x1C38, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818,
0x1818, 0x1818, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'i'
*/
0x0000, 0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'j'
*/
0x0000, 0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00F8, 0x0078, 0x0000,
/**
* @brief 'k'
*/
0x0000, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x0C0C, 0x060C,
0x030C, 0x018C, 0x00CC, 0x006C, 0x00FC, 0x019C, 0x038C, 0x030C,
0x060C, 0x0C0C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'l'
*/
0x0000, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'm'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3C7C, 0x7EFF,
0xE3C7, 0xC183, 0xC183, 0xC183, 0xC183, 0xC183, 0xC183, 0xC183,
0xC183, 0xC183, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'n'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0798, 0x0FF8,
0x1C38, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818,
0x1818, 0x1818, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'o'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03C0, 0x0FF0,
0x0C30, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x0C30,
0x0FF0, 0x03C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'p'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03D8, 0x0FF8,
0x0C38, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x0C38,
0x0FF8, 0x03D8, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0000,
/**
* @brief 'q'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1BC0, 0x1FF0,
0x1C30, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1C30,
0x1FF0, 0x1BC0, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x0000,
/**
* @brief 'r'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x07B0, 0x03F0,
0x0070, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
0x0030, 0x0030, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 's'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x03E0, 0x03F0,
0x0E38, 0x0C18, 0x0038, 0x03F0, 0x07C0, 0x0C00, 0x0C18, 0x0E38,
0x07F0, 0x03E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 't'
*/
0x0000, 0x0000, 0x0080, 0x00C0, 0x00C0, 0x00C0, 0x07F0, 0x07F0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x07C0, 0x0780, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'u'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1818, 0x1818,
0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1C38,
0x1FF0, 0x19E0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'v'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x180C, 0x0C18,
0x0C18, 0x0C18, 0x0630, 0x0630, 0x0630, 0x0360, 0x0360, 0x0360,
0x01C0, 0x01C0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'w'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x41C1, 0x41C1,
0x61C3, 0x6363, 0x6363, 0x6363, 0x3636, 0x3636, 0x3636, 0x1C1C,
0x1C1C, 0x1C1C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'x'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x381C, 0x1C38,
0x0C30, 0x0660, 0x0360, 0x0360, 0x0360, 0x0360, 0x0660, 0x0C30,
0x1C38, 0x381C, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief 'y'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3018, 0x1830,
0x1830, 0x1870, 0x0C60, 0x0C60, 0x0CE0, 0x06C0, 0x06C0, 0x0380,
0x0380, 0x0380, 0x0180, 0x0180, 0x01C0, 0x00F0, 0x0070, 0x0000,
/**
* @brief 'z'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1FFC, 0x1FFC,
0x0C00, 0x0600, 0x0300, 0x0180, 0x00C0, 0x0060, 0x0030, 0x0018,
0x1FFC, 0x1FFC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/**
* @brief '{'
*/
0x0000, 0x0300, 0x0180, 0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x00C0,
0x00C0, 0x0060, 0x0060, 0x0030, 0x0060, 0x0040, 0x00C0, 0x00C0,
0x00C0, 0x00C0, 0x00C0, 0x00C0, 0x0180, 0x0300, 0x0000, 0x0000,
/**
* @brief '|'
*/
0x0000, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0180, 0x0000,
/**
* @brief '}'
*/
0x0000, 0x0060, 0x00C0, 0x01C0, 0x0180, 0x0180, 0x0180, 0x0180,
0x0180, 0x0300, 0x0300, 0x0600, 0x0300, 0x0100, 0x0180, 0x0180,
0x0180, 0x0180, 0x0180, 0x0180, 0x00C0, 0x0060, 0x0000, 0x0000,
/**
* @brief '~'
*/
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x10F0, 0x1FF8, 0x0F08, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000};
const uint16_t ASCII12x12_Table [] = {
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x0000,0x2000,0x0000,0x0000,
0x0000,0x5000,0x5000,0x5000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0900,0x0900,0x1200,0x7f00,0x1200,0x7f00,0x1200,0x2400,0x2400,0x0000,0x0000,
0x1000,0x3800,0x5400,0x5000,0x5000,0x3800,0x1400,0x5400,0x5400,0x3800,0x1000,0x0000,
0x0000,0x3080,0x4900,0x4900,0x4a00,0x32c0,0x0520,0x0920,0x0920,0x10c0,0x0000,0x0000,
0x0000,0x0c00,0x1200,0x1200,0x1400,0x1800,0x2500,0x2300,0x2300,0x1d80,0x0000,0x0000,
0x0000,0x4000,0x4000,0x4000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0800,0x1000,0x1000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x1000,0x1000,
0x0000,0x4000,0x2000,0x2000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x2000,0x2000,
0x0000,0x2000,0x7000,0x2000,0x5000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0800,0x0800,0x7f00,0x0800,0x0800,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x2000,0x2000,0x4000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x7000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x2000,0x0000,0x0000,
0x0000,0x1000,0x1000,0x1000,0x2000,0x2000,0x2000,0x2000,0x4000,0x4000,0x0000,0x0000,
0x0000,0x1000,0x2800,0x4400,0x4400,0x4400,0x4400,0x4400,0x2800,0x1000,0x0000,0x0000,
0x0000,0x1000,0x3000,0x5000,0x1000,0x1000,0x1000,0x1000,0x1000,0x1000,0x0000,0x0000,
0x0000,0x3000,0x4800,0x4400,0x0400,0x0800,0x1000,0x2000,0x4000,0x7c00,0x0000,0x0000,
0x0000,0x3000,0x4800,0x0400,0x0800,0x1000,0x0800,0x4400,0x4800,0x3000,0x0000,0x0000,
0x0000,0x0800,0x1800,0x1800,0x2800,0x2800,0x4800,0x7c00,0x0800,0x0800,0x0000,0x0000,
0x0000,0x3c00,0x2000,0x4000,0x7000,0x4800,0x0400,0x4400,0x4800,0x3000,0x0000,0x0000,
0x0000,0x1800,0x2400,0x4000,0x5000,0x6800,0x4400,0x4400,0x2800,0x1000,0x0000,0x0000,
0x0000,0x7c00,0x0400,0x0800,0x1000,0x1000,0x1000,0x2000,0x2000,0x2000,0x0000,0x0000,
0x0000,0x1000,0x2800,0x4400,0x2800,0x1000,0x2800,0x4400,0x2800,0x1000,0x0000,0x0000,
0x0000,0x1000,0x2800,0x4400,0x4400,0x2c00,0x1400,0x0400,0x4800,0x3000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x2000,0x0000,0x0000,0x0000,0x0000,0x0000,0x2000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x2000,0x0000,0x0000,0x0000,0x0000,0x0000,0x2000,0x2000,0x4000,
0x0000,0x0000,0x0400,0x0800,0x3000,0x4000,0x3000,0x0800,0x0400,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x7c00,0x0000,0x0000,0x7c00,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x4000,0x2000,0x1800,0x0400,0x1800,0x2000,0x4000,0x0000,0x0000,0x0000,
0x0000,0x3800,0x6400,0x4400,0x0400,0x0800,0x1000,0x1000,0x0000,0x1000,0x0000,0x0000,
0x0000,0x0f80,0x1040,0x2ea0,0x51a0,0x5120,0x5120,0x5120,0x5320,0x4dc0,0x2020,0x1040,
0x0000,0x0800,0x1400,0x1400,0x1400,0x2200,0x3e00,0x2200,0x4100,0x4100,0x0000,0x0000,
0x0000,0x3c00,0x2200,0x2200,0x2200,0x3c00,0x2200,0x2200,0x2200,0x3c00,0x0000,0x0000,
0x0000,0x0e00,0x1100,0x2100,0x2000,0x2000,0x2000,0x2100,0x1100,0x0e00,0x0000,0x0000,
0x0000,0x3c00,0x2200,0x2100,0x2100,0x2100,0x2100,0x2100,0x2200,0x3c00,0x0000,0x0000,
0x0000,0x3e00,0x2000,0x2000,0x2000,0x3e00,0x2000,0x2000,0x2000,0x3e00,0x0000,0x0000,
0x0000,0x3e00,0x2000,0x2000,0x2000,0x3c00,0x2000,0x2000,0x2000,0x2000,0x0000,0x0000,
0x0000,0x0e00,0x1100,0x2100,0x2000,0x2700,0x2100,0x2100,0x1100,0x0e00,0x0000,0x0000,
0x0000,0x2100,0x2100,0x2100,0x2100,0x3f00,0x2100,0x2100,0x2100,0x2100,0x0000,0x0000,
0x0000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x0000,0x0000,
0x0000,0x0800,0x0800,0x0800,0x0800,0x0800,0x0800,0x4800,0x4800,0x3000,0x0000,0x0000,
0x0000,0x2200,0x2400,0x2800,0x2800,0x3800,0x2800,0x2400,0x2400,0x2200,0x0000,0x0000,
0x0000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x3e00,0x0000,0x0000,
0x0000,0x2080,0x3180,0x3180,0x3180,0x2a80,0x2a80,0x2a80,0x2a80,0x2480,0x0000,0x0000,
0x0000,0x2100,0x3100,0x3100,0x2900,0x2900,0x2500,0x2300,0x2300,0x2100,0x0000,0x0000,
0x0000,0x0c00,0x1200,0x2100,0x2100,0x2100,0x2100,0x2100,0x1200,0x0c00,0x0000,0x0000,
0x0000,0x3c00,0x2200,0x2200,0x2200,0x3c00,0x2000,0x2000,0x2000,0x2000,0x0000,0x0000,
0x0000,0x0c00,0x1200,0x2100,0x2100,0x2100,0x2100,0x2100,0x1600,0x0d00,0x0100,0x0000,
0x0000,0x3e00,0x2100,0x2100,0x2100,0x3e00,0x2400,0x2200,0x2100,0x2080,0x0000,0x0000,
0x0000,0x1c00,0x2200,0x2200,0x2000,0x1c00,0x0200,0x2200,0x2200,0x1c00,0x0000,0x0000,
0x0000,0x3e00,0x0800,0x0800,0x0800,0x0800,0x0800,0x0800,0x0800,0x0800,0x0000,0x0000,
0x0000,0x2100,0x2100,0x2100,0x2100,0x2100,0x2100,0x2100,0x1200,0x0c00,0x0000,0x0000,
0x0000,0x4100,0x4100,0x2200,0x2200,0x2200,0x1400,0x1400,0x1400,0x0800,0x0000,0x0000,
0x0000,0x4440,0x4a40,0x2a40,0x2a80,0x2a80,0x2a80,0x2a80,0x2a80,0x1100,0x0000,0x0000,
0x0000,0x4100,0x2200,0x1400,0x1400,0x0800,0x1400,0x1400,0x2200,0x4100,0x0000,0x0000,
0x0000,0x4100,0x2200,0x2200,0x1400,0x0800,0x0800,0x0800,0x0800,0x0800,0x0000,0x0000,
0x0000,0x7e00,0x0200,0x0400,0x0800,0x1000,0x1000,0x2000,0x4000,0x7e00,0x0000,0x0000,
0x0000,0x3000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,
0x0000,0x4000,0x4000,0x2000,0x2000,0x2000,0x2000,0x2000,0x1000,0x1000,0x0000,0x0000,
0x0000,0x6000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,
0x0000,0x1000,0x2800,0x2800,0x2800,0x4400,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x7e00,
0x4000,0x2000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3800,0x4400,0x0400,0x3c00,0x4400,0x4400,0x3c00,0x0000,0x0000,
0x0000,0x4000,0x4000,0x5800,0x6400,0x4400,0x4400,0x4400,0x6400,0x5800,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3000,0x4800,0x4000,0x4000,0x4000,0x4800,0x3000,0x0000,0x0000,
0x0000,0x0400,0x0400,0x3400,0x4c00,0x4400,0x4400,0x4400,0x4c00,0x3400,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3800,0x4400,0x4400,0x7c00,0x4000,0x4400,0x3800,0x0000,0x0000,
0x0000,0x6000,0x4000,0xe000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3400,0x4c00,0x4400,0x4400,0x4400,0x4c00,0x3400,0x0400,0x4400,
0x0000,0x4000,0x4000,0x5800,0x6400,0x4400,0x4400,0x4400,0x4400,0x4400,0x0000,0x0000,
0x0000,0x4000,0x0000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x0000,0x0000,
0x0000,0x4000,0x0000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,
0x0000,0x4000,0x4000,0x4800,0x5000,0x6000,0x5000,0x5000,0x4800,0x4800,0x0000,0x0000,
0x0000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x4000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x5200,0x6d00,0x4900,0x4900,0x4900,0x4900,0x4900,0x0000,0x0000,
0x0000,0x0000,0x0000,0x5800,0x6400,0x4400,0x4400,0x4400,0x4400,0x4400,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3800,0x4400,0x4400,0x4400,0x4400,0x4400,0x3800,0x0000,0x0000,
0x0000,0x0000,0x0000,0x5800,0x6400,0x4400,0x4400,0x4400,0x6400,0x5800,0x4000,0x4000,
0x0000,0x0000,0x0000,0x3400,0x4c00,0x4400,0x4400,0x4400,0x4c00,0x3400,0x0400,0x0400,
0x0000,0x0000,0x0000,0x5000,0x6000,0x4000,0x4000,0x4000,0x4000,0x4000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x3000,0x4800,0x4000,0x3000,0x0800,0x4800,0x3000,0x0000,0x0000,
0x0000,0x4000,0x4000,0xe000,0x4000,0x4000,0x4000,0x4000,0x4000,0x6000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x4400,0x4400,0x4400,0x4400,0x4400,0x4c00,0x3400,0x0000,0x0000,
0x0000,0x0000,0x0000,0x4400,0x4400,0x2800,0x2800,0x2800,0x2800,0x1000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x4900,0x4900,0x5500,0x5500,0x5500,0x5500,0x2200,0x0000,0x0000,
0x0000,0x0000,0x0000,0x4400,0x2800,0x2800,0x1000,0x2800,0x2800,0x4400,0x0000,0x0000,
0x0000,0x0000,0x0000,0x4400,0x4400,0x2800,0x2800,0x2800,0x1000,0x1000,0x1000,0x1000,
0x0000,0x0000,0x0000,0x7800,0x0800,0x1000,0x2000,0x2000,0x4000,0x7800,0x0000,0x0000,
0x0000,0x1000,0x2000,0x2000,0x2000,0x2000,0x4000,0x2000,0x2000,0x2000,0x2000,0x2000,
0x0000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,0x2000,
0x0000,0x4000,0x2000,0x2000,0x2000,0x2000,0x1000,0x2000,0x2000,0x2000,0x2000,0x2000,
0x0000,0x0000,0x0000,0x0000,0x7400,0x5800,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x7000,0x5000,0x5000,0x5000,0x5000,0x5000,0x5000,0x7000,0x0000,0x0000};
const uint16_t ASCII8x12_Table [] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x10,0x10,0x10,0x10,0x10,0x10,0x00,0x10,0x00,
0x00,0x00,0x00,0x28,0x28,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x14,0x14,0x3e,0x14,0x28,0x7c,0x28,0x28,0x00,
0x00,0x00,0x10,0x38,0x54,0x50,0x38,0x14,0x14,0x54,0x38,0x10,
0x00,0x00,0x00,0x44,0xa8,0xa8,0x50,0x14,0x1a,0x2a,0x24,0x00,
0x00,0x00,0x00,0x20,0x50,0x50,0x20,0xe8,0x98,0x98,0x60,0x00,
0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x40,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
0x00,0x00,0x00,0x80,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
0x00,0x00,0x00,0x40,0xe0,0x40,0xa0,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x20,0x20,0xf8,0x20,0x20,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x40,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,
0x00,0x00,0x00,0x20,0x20,0x20,0x40,0x40,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x60,0x90,0x90,0x90,0x90,0x90,0x90,0x60,0x00,
0x00,0x00,0x00,0x20,0x60,0xa0,0x20,0x20,0x20,0x20,0x20,0x00,
0x00,0x00,0x00,0x60,0x90,0x10,0x10,0x20,0x40,0x80,0xf0,0x00,
0x00,0x00,0x00,0x60,0x90,0x10,0x60,0x10,0x10,0x90,0x60,0x00,
0x00,0x00,0x00,0x10,0x30,0x50,0x50,0x90,0xf8,0x10,0x10,0x00,
0x00,0x00,0x00,0x70,0x40,0x80,0xe0,0x10,0x10,0x90,0x60,0x00,
0x00,0x00,0x00,0x60,0x90,0x80,0xa0,0xd0,0x90,0x90,0x60,0x00,
0x00,0x00,0x00,0xf0,0x10,0x20,0x20,0x20,0x40,0x40,0x40,0x00,
0x00,0x00,0x00,0x60,0x90,0x90,0x60,0x90,0x90,0x90,0x60,0x00,
0x00,0x00,0x00,0x60,0x90,0x90,0xb0,0x50,0x10,0x90,0x60,0x00,
0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x40,0x00,
0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x40,0x40,
0x00,0x00,0x00,0x00,0x00,0x10,0x60,0x80,0x60,0x10,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xf0,0x00,0xf0,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x10,0x60,0x80,0x00,0x00,
0x00,0x00,0x00,0x60,0x90,0x10,0x20,0x40,0x40,0x00,0x40,0x00,
0x00,0x00,0x00,0x1c,0x22,0x5b,0xa5,0xa5,0xa5,0xa5,0x9e,0x41,
0x00,0x00,0x00,0x20,0x50,0x50,0x50,0x50,0x70,0x88,0x88,0x00,
0x00,0x00,0x00,0xf0,0x88,0x88,0xf0,0x88,0x88,0x88,0xf0,0x00,
0x00,0x00,0x00,0x38,0x44,0x84,0x80,0x80,0x84,0x44,0x38,0x00,
0x00,0x00,0x00,0xe0,0x90,0x88,0x88,0x88,0x88,0x90,0xe0,0x00,
0x00,0x00,0x00,0xf8,0x80,0x80,0xf8,0x80,0x80,0x80,0xf8,0x00,
0x00,0x00,0x00,0x78,0x40,0x40,0x70,0x40,0x40,0x40,0x40,0x00,
0x00,0x00,0x00,0x38,0x44,0x84,0x80,0x9c,0x84,0x44,0x38,0x00,
0x00,0x00,0x00,0x88,0x88,0x88,0xf8,0x88,0x88,0x88,0x88,0x00,
0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x10,0x10,0x10,0x10,0x10,0x90,0x90,0x60,0x00,
0x00,0x00,0x00,0x88,0x90,0xa0,0xe0,0xa0,0x90,0x90,0x88,0x00,
0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0xf0,0x00,
0x00,0x00,0x00,0x82,0xc6,0xc6,0xaa,0xaa,0xaa,0xaa,0x92,0x00,
0x00,0x00,0x00,0x84,0xc4,0xa4,0xa4,0x94,0x94,0x8c,0x84,0x00,
0x00,0x00,0x00,0x30,0x48,0x84,0x84,0x84,0x84,0x48,0x30,0x00,
0x00,0x00,0x00,0xf0,0x88,0x88,0x88,0xf0,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x30,0x48,0x84,0x84,0x84,0x84,0x58,0x34,0x04,
0x00,0x00,0x00,0x78,0x44,0x44,0x78,0x50,0x48,0x44,0x42,0x00,
0x00,0x00,0x00,0x70,0x88,0x80,0x70,0x08,0x88,0x88,0x70,0x00,
0x00,0x00,0x00,0xf8,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x00,
0x00,0x00,0x00,0x84,0x84,0x84,0x84,0x84,0x84,0x48,0x30,0x00,
0x00,0x00,0x00,0x88,0x88,0x50,0x50,0x50,0x50,0x50,0x20,0x00,
0x00,0x00,0x00,0x92,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0x44,0x00,
0x00,0x00,0x00,0x84,0x48,0x48,0x30,0x30,0x48,0x48,0x84,0x00,
0x00,0x00,0x00,0x88,0x50,0x50,0x20,0x20,0x20,0x20,0x20,0x00,
0x00,0x00,0x00,0xf8,0x08,0x10,0x20,0x20,0x40,0x80,0xf8,0x00,
0x00,0x00,0x00,0xc0,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
0x00,0x00,0x00,0x80,0x80,0x40,0x40,0x40,0x40,0x20,0x20,0x00,
0x00,0x00,0x00,0xc0,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
0x00,0x00,0x00,0x40,0xa0,0xa0,0xa0,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf8,
0x00,0x00,0x00,0x80,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0xe0,0x10,0x70,0x90,0x90,0x70,0x00,
0x00,0x00,0x00,0x80,0x80,0xa0,0xd0,0x90,0x90,0xd0,0xa0,0x00,
0x00,0x00,0x00,0x00,0x00,0x60,0x90,0x80,0x80,0x90,0x60,0x00,
0x00,0x00,0x00,0x10,0x10,0x50,0xb0,0x90,0x90,0xb0,0x50,0x00,
0x00,0x00,0x00,0x00,0x00,0x60,0x90,0xf0,0x80,0x90,0x60,0x00,
0x00,0x00,0x00,0xc0,0x80,0xc0,0x80,0x80,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x00,0x00,0x50,0xb0,0x90,0x90,0xb0,0x50,0x10,
0x00,0x00,0x00,0x80,0x80,0xa0,0xd0,0x90,0x90,0x90,0x90,0x00,
0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
0x00,0x00,0x00,0x80,0x80,0x90,0xa0,0xc0,0xa0,0x90,0x90,0x00,
0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x00,0x00,0xa6,0xda,0x92,0x92,0x92,0x92,0x00,
0x00,0x00,0x00,0x00,0x00,0xa0,0xd0,0x90,0x90,0x90,0x90,0x00,
0x00,0x00,0x00,0x00,0x00,0x60,0x90,0x90,0x90,0x90,0x60,0x00,
0x00,0x00,0x00,0x00,0x00,0xa0,0xd0,0x90,0x90,0xd0,0xa0,0x80,
0x00,0x00,0x00,0x00,0x00,0x50,0xb0,0x90,0x90,0xb0,0x50,0x10,
0x00,0x00,0x00,0x00,0x00,0xa0,0xc0,0x80,0x80,0x80,0x80,0x00,
0x00,0x00,0x00,0x00,0x00,0xe0,0x90,0x40,0x20,0x90,0x60,0x00,
0x00,0x00,0x00,0x80,0x80,0xc0,0x80,0x80,0x80,0x80,0xc0,0x00,
0x00,0x00,0x00,0x00,0x00,0x90,0x90,0x90,0x90,0xb0,0x50,0x00,
0x00,0x00,0x00,0x00,0x00,0x88,0x88,0x50,0x50,0x50,0x20,0x00,
0x00,0x00,0x00,0x00,0x00,0x92,0xaa,0xaa,0xaa,0xaa,0x44,0x00,
0x00,0x00,0x00,0x00,0x00,0x88,0x50,0x20,0x20,0x50,0x88,0x00,
0x00,0x00,0x00,0x00,0x00,0x88,0x50,0x50,0x50,0x20,0x20,0x20,
0x00,0x00,0x00,0x00,0x00,0xf0,0x10,0x20,0x40,0x80,0xf0,0x00,
0x00,0x00,0x00,0xc0,0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x80,
0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
0x00,0x00,0x00,0xc0,0x40,0x40,0x40,0x20,0x40,0x40,0x40,0x40,
0x00,0x00,0x00,0x00,0x00,0x00,0xe8,0xb0,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xe0,0xa0,0xa0,0xa0,0xa0,0xa0,0xe0,0x00};
const uint16_t ASCII8x8_Table [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0x40,
0xa0, 0xa0, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x24, 0x24, 0xfe, 0x48, 0xfc, 0x48, 0x48,
0x38, 0x54, 0x50, 0x38, 0x14, 0x14, 0x54, 0x38,
0x44, 0xa8, 0xa8, 0x50, 0x14, 0x1a, 0x2a, 0x24,
0x10, 0x28, 0x28, 0x10, 0x74, 0x4c, 0x4c, 0x30,
0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08,
0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10,
0x00, 0x00, 0x24, 0x18, 0x3c, 0x18, 0x24, 0x00,
0x00, 0x00, 0x10, 0x10, 0x7c, 0x10, 0x10, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x10,
0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18,
0x08, 0x08, 0x08, 0x10, 0x10, 0x20, 0x20, 0x20,
0x18, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24, 0x18,
0x08, 0x18, 0x28, 0x08, 0x08, 0x08, 0x08, 0x08,
0x38, 0x44, 0x00, 0x04, 0x08, 0x10, 0x20, 0x7c,
0x18, 0x24, 0x04, 0x18, 0x04, 0x04, 0x24, 0x18,
0x04, 0x0c, 0x14, 0x24, 0x44, 0x7e, 0x04, 0x04,
0x3c, 0x20, 0x20, 0x38, 0x04, 0x04, 0x24, 0x18,
0x18, 0x24, 0x20, 0x38, 0x24, 0x24, 0x24, 0x18,
0x3c, 0x04, 0x08, 0x08, 0x08, 0x10, 0x10, 0x10,
0x18, 0x24, 0x24, 0x18, 0x24, 0x24, 0x24, 0x18,
0x18, 0x24, 0x24, 0x24, 0x1c, 0x04, 0x24, 0x18,
0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0x00, 0x08, 0x00, 0x00, 0x08, 0x10, 0x00,
0x00, 0x00, 0x04, 0x18, 0x20, 0x18, 0x04, 0x00,
0x00, 0x00, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x00,
0x00, 0x00, 0x20, 0x18, 0x04, 0x18, 0x20, 0x00,
0x18, 0x24, 0x04, 0x08, 0x10, 0x10, 0x00, 0x10,
0x3c, 0x42, 0x99, 0xa5, 0xa5, 0x9d, 0x42, 0x38,
0x38, 0x44, 0x44, 0x44, 0x7c, 0x44, 0x44, 0x44,
0x78, 0x44, 0x44, 0x78, 0x44, 0x44, 0x44, 0x78,
0x1c, 0x22, 0x42, 0x40, 0x40, 0x42, 0x22, 0x1c,
0x70, 0x48, 0x44, 0x44, 0x44, 0x44, 0x48, 0x70,
0x7c, 0x40, 0x40, 0x7c, 0x40, 0x40, 0x40, 0x7c,
0x3c, 0x20, 0x20, 0x38, 0x20, 0x20, 0x20, 0x20,
0x1c, 0x22, 0x42, 0x40, 0x4e, 0x42, 0x22, 0x1c,
0x44, 0x44, 0x44, 0x7c, 0x44, 0x44, 0x44, 0x44,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x04, 0x04, 0x04, 0x04, 0x04, 0x24, 0x24, 0x18,
0x44, 0x48, 0x50, 0x70, 0x50, 0x48, 0x48, 0x44,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c,
0x82, 0xc6, 0xc6, 0xaa, 0xaa, 0xaa, 0xaa, 0x92,
0x42, 0x62, 0x52, 0x52, 0x4a, 0x4a, 0x46, 0x42,
0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x24, 0x18,
0x78, 0x44, 0x44, 0x44, 0x78, 0x40, 0x40, 0x40,
0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x2c, 0x1a,
0x78, 0x44, 0x44, 0x78, 0x50, 0x48, 0x44, 0x42,
0x38, 0x44, 0x40, 0x38, 0x04, 0x44, 0x44, 0x38,
0x7c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x24, 0x18,
0x44, 0x44, 0x28, 0x28, 0x28, 0x28, 0x28, 0x10,
0x92, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x44,
0x42, 0x24, 0x24, 0x18, 0x18, 0x24, 0x24, 0x42,
0x44, 0x28, 0x28, 0x10, 0x10, 0x10, 0x10, 0x10,
0x7c, 0x04, 0x08, 0x10, 0x10, 0x20, 0x40, 0x7c,
0x1c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1c,
0x10, 0x10, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04,
0x1c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x1c,
0x10, 0x28, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x04, 0x1c, 0x24, 0x24, 0x1c,
0x20, 0x20, 0x28, 0x34, 0x24, 0x24, 0x34, 0x28,
0x00, 0x00, 0x18, 0x24, 0x20, 0x20, 0x24, 0x18,
0x04, 0x04, 0x14, 0x2c, 0x24, 0x24, 0x2c, 0x14,
0x00, 0x00, 0x18, 0x24, 0x3c, 0x20, 0x24, 0x18,
0x00, 0x18, 0x10, 0x10, 0x18, 0x10, 0x10, 0x10,
0x00, 0x18, 0x24, 0x24, 0x18, 0x04, 0x24, 0x18,
0x20, 0x20, 0x28, 0x34, 0x24, 0x24, 0x24, 0x24,
0x10, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x08, 0x00, 0x08, 0x08, 0x08, 0x08, 0x28, 0x10,
0x20, 0x20, 0x24, 0x28, 0x30, 0x28, 0x24, 0x24,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x00, 0x00, 0xa6, 0xda, 0x92, 0x92, 0x92, 0x92,
0x00, 0x00, 0x28, 0x34, 0x24, 0x24, 0x24, 0x24,
0x00, 0x00, 0x18, 0x24, 0x24, 0x24, 0x24, 0x18,
0x00, 0x28, 0x34, 0x24, 0x38, 0x20, 0x20, 0x20,
0x00, 0x14, 0x2c, 0x24, 0x1c, 0x04, 0x04, 0x04,
0x00, 0x00, 0x2c, 0x30, 0x20, 0x20, 0x20, 0x20,
0x00, 0x00, 0x18, 0x24, 0x10, 0x08, 0x24, 0x18,
0x00, 0x10, 0x38, 0x10, 0x10, 0x10, 0x10, 0x18,
0x00, 0x00, 0x24, 0x24, 0x24, 0x24, 0x2c, 0x14,
0x00, 0x00, 0x44, 0x44, 0x28, 0x28, 0x28, 0x10,
0x00, 0x00, 0x92, 0xaa, 0xaa, 0xaa, 0xaa, 0x44,
0x00, 0x00, 0x44, 0x28, 0x10, 0x10, 0x28, 0x44,
0x00, 0x28, 0x28, 0x28, 0x10, 0x10, 0x10, 0x10,
0x00, 0x00, 0x3c, 0x04, 0x08, 0x10, 0x20, 0x3c,
0x00, 0x08, 0x10, 0x10, 0x20, 0x10, 0x10, 0x08,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10,
0x00, 0x00, 0x00, 0x60, 0x92, 0x0c, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
sFONT Font16x24 = {
ASCII16x24_Table,
16, /* Width */
24, /* Height */
};
sFONT Font12x12 = {
ASCII12x12_Table,
12, /* Width */
12, /* Height */
};
sFONT Font8x12 = {
ASCII8x12_Table,
8, /* Width */
12, /* Height */
};
sFONT Font8x8 = {
ASCII8x8_Table,
8, /* Width */
8, /* Height */
};
/**
* @}
*/
/** @defgroup FONTS_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup FONTS_Private_Functions
* @{
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/fonts.c
|
C
|
asf20
| 47,200
|
/**
******************************************************************************
* @file stm32_eval_spi_flash.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm32_eval_spi_flash
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_SPI_FLASH_H
#define __STM32_EVAL_SPI_FLASH_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SPI_FLASH
* @{
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Exported_Constants
* @{
*/
/**
* @brief M25P SPI Flash supported commands
*/
#define sFLASH_CMD_WRITE 0x02 /*!< Write to Memory instruction */
#define sFLASH_CMD_WRSR 0x01 /*!< Write Status Register instruction */
#define sFLASH_CMD_WREN 0x06 /*!< Write enable instruction */
#define sFLASH_CMD_READ 0x03 /*!< Read from Memory instruction */
#define sFLASH_CMD_RDSR 0x05 /*!< Read Status Register instruction */
#define sFLASH_CMD_RDID 0x9F /*!< Read identification */
#define sFLASH_CMD_SE 0xD8 /*!< Sector Erase instruction */
#define sFLASH_CMD_BE 0xC7 /*!< Bulk Erase instruction */
#define sFLASH_WIP_FLAG 0x01 /*!< Write In Progress (WIP) flag */
#define sFLASH_DUMMY_BYTE 0xA5
#define sFLASH_SPI_PAGESIZE 0x100
#define sFLASH_M25P128_ID 0x202018
#define sFLASH_M25P64_ID 0x202017
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Exported_Macros
* @{
*/
/**
* @brief Select sFLASH: Chip Select pin low
*/
#define sFLASH_CS_LOW() GPIO_ResetBits(sFLASH_CS_GPIO_PORT, sFLASH_CS_PIN)
/**
* @brief Deselect sFLASH: Chip Select pin high
*/
#define sFLASH_CS_HIGH() GPIO_SetBits(sFLASH_CS_GPIO_PORT, sFLASH_CS_PIN)
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Exported_Functions
* @{
*/
/**
* @brief High layer functions
*/
void sFLASH_DeInit(void);
void sFLASH_Init(void);
void sFLASH_EraseSector(uint32_t SectorAddr);
void sFLASH_EraseBulk(void);
void sFLASH_WritePage(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite);
void sFLASH_WriteBuffer(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite);
void sFLASH_ReadBuffer(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t NumByteToRead);
uint32_t sFLASH_ReadID(void);
void sFLASH_StartReadSequence(uint32_t ReadAddr);
/**
* @brief Low layer functions
*/
uint8_t sFLASH_ReadByte(void);
uint8_t sFLASH_SendByte(uint8_t byte);
uint16_t sFLASH_SendHalfWord(uint16_t HalfWord);
void sFLASH_WriteEnable(void);
void sFLASH_WaitForWriteEnd(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_SPI_FLASH_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_spi_flash.h
|
C
|
asf20
| 4,055
|
/**
******************************************************************************
* @file stm32_eval_spi_sd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm32_eval_spi_sd
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_SPI_SD_H
#define __STM32_EVAL_SPI_SD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SPI_SD
* @{
*/
/** @defgroup STM32_EVAL_SPI_SD_Exported_Types
* @{
*/
typedef enum
{
/**
* @brief SD reponses and error flags
*/
SD_RESPONSE_NO_ERROR = (0x00),
SD_IN_IDLE_STATE = (0x01),
SD_ERASE_RESET = (0x02),
SD_ILLEGAL_COMMAND = (0x04),
SD_COM_CRC_ERROR = (0x08),
SD_ERASE_SEQUENCE_ERROR = (0x10),
SD_ADDRESS_ERROR = (0x20),
SD_PARAMETER_ERROR = (0x40),
SD_RESPONSE_FAILURE = (0xFF),
/**
* @brief Data response error
*/
SD_DATA_OK = (0x05),
SD_DATA_CRC_ERROR = (0x0B),
SD_DATA_WRITE_ERROR = (0x0D),
SD_DATA_OTHER_ERROR = (0xFF),
} SD_Error;
/**
* @brief Card Specific Data: CSD Register
*/
typedef struct
{
__IO uint8_t CSDStruct; /*!< CSD structure */
__IO uint8_t SysSpecVersion; /*!< System specification version */
__IO uint8_t Reserved1; /*!< Reserved */
__IO uint8_t TAAC; /*!< Data read access-time 1 */
__IO uint8_t NSAC; /*!< Data read access-time 2 in CLK cycles */
__IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */
__IO uint16_t CardComdClasses; /*!< Card command classes */
__IO uint8_t RdBlockLen; /*!< Max. read data block length */
__IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */
__IO uint8_t WrBlockMisalign; /*!< Write block misalignment */
__IO uint8_t RdBlockMisalign; /*!< Read block misalignment */
__IO uint8_t DSRImpl; /*!< DSR implemented */
__IO uint8_t Reserved2; /*!< Reserved */
__IO uint32_t DeviceSize; /*!< Device Size */
__IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */
__IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */
__IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */
__IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */
__IO uint8_t DeviceSizeMul; /*!< Device size multiplier */
__IO uint8_t EraseGrSize; /*!< Erase group size */
__IO uint8_t EraseGrMul; /*!< Erase group size multiplier */
__IO uint8_t WrProtectGrSize; /*!< Write protect group size */
__IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */
__IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */
__IO uint8_t WrSpeedFact; /*!< Write speed factor */
__IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */
__IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */
__IO uint8_t Reserved3; /*!< Reserded */
__IO uint8_t ContentProtectAppli; /*!< Content protection application */
__IO uint8_t FileFormatGrouop; /*!< File format group */
__IO uint8_t CopyFlag; /*!< Copy flag (OTP) */
__IO uint8_t PermWrProtect; /*!< Permanent write protection */
__IO uint8_t TempWrProtect; /*!< Temporary write protection */
__IO uint8_t FileFormat; /*!< File Format */
__IO uint8_t ECC; /*!< ECC code */
__IO uint8_t CSD_CRC; /*!< CSD CRC */
__IO uint8_t Reserved4; /*!< always 1*/
} SD_CSD;
/**
* @brief Card Identification Data: CID Register
*/
typedef struct
{
__IO uint8_t ManufacturerID; /*!< ManufacturerID */
__IO uint16_t OEM_AppliID; /*!< OEM/Application ID */
__IO uint32_t ProdName1; /*!< Product Name part1 */
__IO uint8_t ProdName2; /*!< Product Name part2*/
__IO uint8_t ProdRev; /*!< Product Revision */
__IO uint32_t ProdSN; /*!< Product Serial Number */
__IO uint8_t Reserved1; /*!< Reserved1 */
__IO uint16_t ManufactDate; /*!< Manufacturing Date */
__IO uint8_t CID_CRC; /*!< CID CRC */
__IO uint8_t Reserved2; /*!< always 1 */
} SD_CID;
/**
* @brief SD Card information
*/
typedef struct
{
SD_CSD SD_csd;
SD_CID SD_cid;
uint32_t CardCapacity; /*!< Card Capacity */
uint32_t CardBlockSize; /*!< Card Block Size */
} SD_CardInfo;
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Exported_Constants
* @{
*/
/**
* @brief Block Size
*/
#define SD_BLOCK_SIZE 0x200
/**
* @brief Dummy byte
*/
#define SD_DUMMY_BYTE 0xFF
/**
* @brief Start Data tokens:
* Tokens (necessary because at nop/idle (and CS active) only 0xff is
* on the data/command line)
*/
#define SD_START_DATA_SINGLE_BLOCK_READ 0xFE /*!< Data token start byte, Start Single Block Read */
#define SD_START_DATA_MULTIPLE_BLOCK_READ 0xFE /*!< Data token start byte, Start Multiple Block Read */
#define SD_START_DATA_SINGLE_BLOCK_WRITE 0xFE /*!< Data token start byte, Start Single Block Write */
#define SD_START_DATA_MULTIPLE_BLOCK_WRITE 0xFD /*!< Data token start byte, Start Multiple Block Write */
#define SD_STOP_DATA_MULTIPLE_BLOCK_WRITE 0xFD /*!< Data toke stop byte, Stop Multiple Block Write */
/**
* @brief SD detection on its memory slot
*/
#define SD_PRESENT ((uint8_t)0x01)
#define SD_NOT_PRESENT ((uint8_t)0x00)
/**
* @brief Commands: CMDxx = CMD-number | 0x40
*/
#define SD_CMD_GO_IDLE_STATE 0 /*!< CMD0 = 0x40 */
#define SD_CMD_SEND_OP_COND 1 /*!< CMD1 = 0x41 */
#define SD_CMD_SEND_CSD 9 /*!< CMD9 = 0x49 */
#define SD_CMD_SEND_CID 10 /*!< CMD10 = 0x4A */
#define SD_CMD_STOP_TRANSMISSION 12 /*!< CMD12 = 0x4C */
#define SD_CMD_SEND_STATUS 13 /*!< CMD13 = 0x4D */
#define SD_CMD_SET_BLOCKLEN 16 /*!< CMD16 = 0x50 */
#define SD_CMD_READ_SINGLE_BLOCK 17 /*!< CMD17 = 0x51 */
#define SD_CMD_READ_MULT_BLOCK 18 /*!< CMD18 = 0x52 */
#define SD_CMD_SET_BLOCK_COUNT 23 /*!< CMD23 = 0x57 */
#define SD_CMD_WRITE_SINGLE_BLOCK 24 /*!< CMD24 = 0x58 */
#define SD_CMD_WRITE_MULT_BLOCK 25 /*!< CMD25 = 0x59 */
#define SD_CMD_PROG_CSD 27 /*!< CMD27 = 0x5B */
#define SD_CMD_SET_WRITE_PROT 28 /*!< CMD28 = 0x5C */
#define SD_CMD_CLR_WRITE_PROT 29 /*!< CMD29 = 0x5D */
#define SD_CMD_SEND_WRITE_PROT 30 /*!< CMD30 = 0x5E */
#define SD_CMD_SD_ERASE_GRP_START 32 /*!< CMD32 = 0x60 */
#define SD_CMD_SD_ERASE_GRP_END 33 /*!< CMD33 = 0x61 */
#define SD_CMD_UNTAG_SECTOR 34 /*!< CMD34 = 0x62 */
#define SD_CMD_ERASE_GRP_START 35 /*!< CMD35 = 0x63 */
#define SD_CMD_ERASE_GRP_END 36 /*!< CMD36 = 0x64 */
#define SD_CMD_UNTAG_ERASE_GROUP 37 /*!< CMD37 = 0x65 */
#define SD_CMD_ERASE 38 /*!< CMD38 = 0x66 */
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Exported_Macros
* @{
*/
/**
* @brief Select SD Card: ChipSelect pin low
*/
#define SD_CS_LOW() GPIO_ResetBits(SD_CS_GPIO_PORT, SD_CS_PIN)
/**
* @brief Deselect SD Card: ChipSelect pin high
*/
#define SD_CS_HIGH() GPIO_SetBits(SD_CS_GPIO_PORT, SD_CS_PIN)
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Exported_Functions
* @{
*/
void SD_DeInit(void);
SD_Error SD_Init(void);
uint8_t SD_Detect(void);
SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo);
SD_Error SD_ReadBlock(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize);
SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
SD_Error SD_WriteBlock(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize);
SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
SD_Error SD_GetCSDRegister(SD_CSD* SD_csd);
SD_Error SD_GetCIDRegister(SD_CID* SD_cid);
void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc);
SD_Error SD_GetResponse(uint8_t Response);
uint8_t SD_GetDataResponse(void);
SD_Error SD_GoIdleState(void);
uint16_t SD_GetStatus(void);
uint8_t SD_WriteByte(uint8_t byte);
uint8_t SD_ReadByte(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_SPI_SD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_spi_sd.h
|
C
|
asf20
| 9,937
|
/**
******************************************************************************
* @file stm32_eval_i2c_tsensor.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the
* stm32_eval_i2c_tsensor firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_I2C_TSENSOR_H
#define __STM32_EVAL_I2C_TSENSOR_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_I2C_TSENSOR
* @{
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Exported_Constants
* @{
*/
/**
* @brief Block Size
*/
#define LM75_REG_TEMP 0x00 /*!< Temperature Register of LM75 */
#define LM75_REG_CONF 0x01 /*!< Configuration Register of LM75 */
#define LM75_REG_THYS 0x02 /*!< Temperature Register of LM75 */
#define LM75_REG_TOS 0x03 /*!< Over-temp Shutdown threshold Register of LM75 */
#define I2C_TIMEOUT ((uint32_t)0x3FFFF) /*!< I2C Time out */
#define LM75_ADDR 0x90 /*!< LM75 address */
#define LM75_I2C_SPEED 100000 /*!< I2C Speed */
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Exported_Functions
* @{
*/
void LM75_DeInit(void);
void LM75_Init(void);
ErrorStatus LM75_GetStatus(void);
uint16_t LM75_ReadTemp(void);
uint16_t LM75_ReadReg(uint8_t RegName);
void LM75_WriteReg(uint8_t RegName, uint16_t RegValue);
uint8_t LM75_ReadConfReg(void);
void LM75_WriteConfReg(uint8_t RegValue);
void LM75_ShutDown(FunctionalState NewState);
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_I2C_TSENSOR_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_i2c_tsensor.h
|
C
|
asf20
| 2,967
|
/**
******************************************************************************
* @file stm32_eval_i2c_ee.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to manage the I2C M24CXX
* EEPROM memory mounted on STM32xx-EVAL board (refer to stm32_eval.h
* to know about the boards supporting this memory).
* It implements a high level communication layer for read and write
* from/to this memory. The needed STM32 hardware resources (I2C and
* GPIO) are defined in stm32xx_eval.h file, and the initialization is
* performed in sEE_LowLevel_Init() function declared in stm32xx_eval.c
* file.
* You can easily tailor this driver to any other development board,
* by just adapting the defines for hardware resources and
* sEE_LowLevel_Init() function.
*
* @note In this driver, basic read and write functions (sEE_ReadBuffer()
* and sEE_WritePage()) use the DMA to perform the data transfer
* to/from EEPROM memory (except when number of requested data is
* equal to 1). Thus, after calling these two functions, user
* application may perform other tasks while DMA is transferring
* data. The application should then monitor the variable holding
* the number of data in order to determine when the transfer is
* completed (variable decremented to 0). Stopping transfer tasks
* are performed into DMA interrupt handlers (which are integrated
* into this driver).
*
* +-----------------------------------------------------------------+
* | Pin assignment |
* +---------------------------------------+-----------+-------------+
* | STM32 I2C Pins | sEE | Pin |
* +---------------------------------------+-----------+-------------+
* | . | E0(GND) | 1 (0V) |
* | . | E1(GND) | 2 (0V) |
* | . | E2(GND) | 3 (0V) |
* | . | E0(VSS) | 4 (0V) |
* | sEE_I2C_SDA_PIN/ SDA | SDA | 5 |
* | sEE_I2C_SCL_PIN/ SCL | SCL | 6 |
* | . | /WC(VDD)| 7 (3.3V) |
* | . | VDD | 8 (3.3V) |
* +---------------------------------------+-----------+-------------+
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval_i2c_ee.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_I2C_EE
* @brief This file includes the I2C EEPROM driver of STM32-EVAL boards.
* @{
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Variables
* @{
*/
__IO uint16_t sEEAddress = 0;
__IO uint32_t sEETimeout = sEE_TIMEOUT_MAX;
__IO uint16_t* sEEDataReadPointer;
__IO uint8_t* sEEDataWritePointer;
__IO uint8_t sEEDataNum;
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Private_Functions
* @{
*/
/**
* @brief DeInitializes peripherals used by the I2C EEPROM driver.
* @param None
* @retval None
*/
void sEE_DeInit(void)
{
sEE_LowLevel_DeInit();
}
/**
* @brief Initializes peripherals used by the I2C EEPROM driver.
* @param None
* @retval None
*/
void sEE_Init(void)
{
I2C_InitTypeDef I2C_InitStructure;
sEE_LowLevel_Init();
/*!< I2C configuration */
/* sEE_I2C configuration */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = I2C_SLAVE_ADDRESS7;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
/* sEE_I2C Peripheral Enable */
I2C_Cmd(sEE_I2C, ENABLE);
/* Apply sEE_I2C configuration after enabling it */
I2C_Init(sEE_I2C, &I2C_InitStructure);
/* Enable the sEE_I2C peripheral DMA requests */
I2C_DMACmd(sEE_I2C, ENABLE);
#if defined (sEE_M24C64_32)
/*!< Select the EEPROM address according to the state of E0, E1, E2 pins */
sEEAddress = sEE_HW_ADDRESS;
#elif defined (sEE_M24C08)
/*!< depending on the sEE Address selected in the i2c_ee.h file */
#ifdef sEE_Block0_ADDRESS
/*!< Select the sEE Block0 to write on */
sEEAddress = sEE_Block0_ADDRESS;
#endif
#ifdef sEE_Block1_ADDRESS
/*!< Select the sEE Block1 to write on */
sEEAddress = sEE_Block1_ADDRESS;
#endif
#ifdef sEE_Block2_ADDRESS
/*!< Select the sEE Block2 to write on */
sEEAddress = sEE_Block2_ADDRESS;
#endif
#ifdef sEE_Block3_ADDRESS
/*!< Select the sEE Block3 to write on */
sEEAddress = sEE_Block3_ADDRESS;
#endif
#endif /*!< sEE_M24C64_32 */
}
/**
* @brief Writes one byte to the I2C EEPROM.
* @param pBuffer : pointer to the buffer containing the data to be written
* to the EEPROM.
* @param WriteAddr : EEPROM's internal address to write to.
* @retval None
*/
void sEE_WriteByte(uint8_t* pBuffer, uint16_t WriteAddr)
{
/*!< Send STRAT condition */
I2C_GenerateSTART(sEE_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for write */
I2C_Send7bitAddress(sEE_I2C, sEEAddress, I2C_Direction_Transmitter);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
}
#ifdef sEE_M24C08
/*!< Send the EEPROM's internal address to write to : only one byte Address */
I2C_SendData(sEE_I2C, WriteAddr);
#elif defined(sEE_M24C64_32)
/*!< Send the EEPROM's internal address to write to : MSB of the address first */
I2C_SendData(sEE_I2C, (uint8_t)((WriteAddr & 0xFF00) >> 8));
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send the EEPROM's internal address to write to : LSB of the address */
I2C_SendData(sEE_I2C, (uint8_t)(WriteAddr & 0x00FF));
#endif /*!< sEE_M24C08 */
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send the byte to be written */
I2C_SendData(sEE_I2C, *pBuffer);
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send STOP condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
}
/**
* @brief Reads a block of data from the EEPROM.
* @param pBuffer : pointer to the buffer that receives the data read from
* the EEPROM.
* @param ReadAddr : EEPROM's internal address to read from.
* @param NumByteToRead : pointer to the variable holding number of bytes to
* read from the EEPROM.
*
* @note The variable pointed by NumByteToRead is reset to 0 when all the
* data are read from the EEPROM. Application should monitor this
* variable in order know when the transfer is complete.
*
* @note When number of data to be read is higher than 1, this function just
* configure the communication and enable the DMA channel to transfer data.
* Meanwhile, the user application may perform other tasks.
* When number of data to be read is 1, then the DMA is not used.
*
* @retval None
*/
void sEE_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint16_t* NumByteToRead)
{
/* Set the pointer to the Number of data to be read. This pointer will be used
by the DMA Transfer Completer interrupt Handler in order to reset the
variable to 0. User should check on this variable in order to know if the
DMA transfer has been complete or not. */
sEEDataReadPointer = NumByteToRead;
/*!< While the bus is busy */
while(I2C_GetFlagStatus(sEE_I2C, I2C_FLAG_BUSY))
{
}
/*!< Send START condition */
I2C_GenerateSTART(sEE_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for write */
I2C_Send7bitAddress(sEE_I2C, sEEAddress, I2C_Direction_Transmitter);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
}
#ifdef sEE_M24C08
/*!< Send the EEPROM's internal address to read from: Only one byte address */
I2C_SendData(sEE_I2C, ReadAddr);
#elif defined (sEE_M24C64_32)
/*!< Send the EEPROM's internal address to read from: MSB of the address first */
I2C_SendData(sEE_I2C, (uint8_t)((ReadAddr & 0xFF00) >> 8));
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send the EEPROM's internal address to read from: LSB of the address */
I2C_SendData(sEE_I2C, (uint8_t)(ReadAddr & 0x00FF));
#endif /*!< sEE_M24C08 */
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send STRAT condition a second time */
I2C_GenerateSTART(sEE_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for read */
I2C_Send7bitAddress(sEE_I2C, sEEAddress, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
}
/* If number of data to be read is 1, then DMA couldn't be used */
if ((uint16_t)(*NumByteToRead) < 2)
{
/*!< Disable Acknowledgement */
I2C_AcknowledgeConfig(sEE_I2C, DISABLE);
/*!< Send STOP Condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
/*!< Test on EV7 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
}
/*!< Read a byte from the EEPROM */
*pBuffer = I2C_ReceiveData(sEE_I2C);
/*!< Decrement the read bytes counter */
(uint16_t)(*NumByteToRead)--;
/*!< Enable Acknowledgement to be ready for another reception */
I2C_AcknowledgeConfig(sEE_I2C, ENABLE);
}
/* DMA could be used for number of data higher than 1 */
else
{
/* Configure the DMA Rx Channel with the buffer address and the buffer size */
sEE_LowLevel_DMAConfig((uint32_t)pBuffer, (uint16_t)(*NumByteToRead), sEE_DIRECTION_RX);
/* Inform the DMA that the next End Of Transfer Signal will be the last one */
I2C_DMALastTransferCmd(sEE_I2C, ENABLE);
/* Enable the DMA Rx Channel */
DMA_Cmd(sEE_I2C_DMA_CHANNEL_RX, ENABLE);
}
}
/**
* @brief Writes buffer of data to the I2C EEPROM.
* @param pBuffer : pointer to the buffer containing the data to be written
* to the EEPROM.
* @param WriteAddr : EEPROM's internal address to write to.
* @param NumByteToWrite : number of bytes to write to the EEPROM.
* @retval None
*/
void sEE_WriteBuffer(uint8_t* pBuffer, uint16_t WriteAddr, uint16_t NumByteToWrite)
{
uint8_t NumOfPage = 0, NumOfSingle = 0, count = 0;
uint16_t Addr = 0;
Addr = WriteAddr % sEE_PAGESIZE;
count = sEE_PAGESIZE - Addr;
NumOfPage = NumByteToWrite / sEE_PAGESIZE;
NumOfSingle = NumByteToWrite % sEE_PAGESIZE;
/*!< If WriteAddr is sEE_PAGESIZE aligned */
if(Addr == 0)
{
/*!< If NumByteToWrite < sEE_PAGESIZE */
if(NumOfPage == 0)
{
/* Store the number of data to be written */
sEEDataNum = NumOfSingle;
/* Start writing data */
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
}
/*!< If NumByteToWrite > sEE_PAGESIZE */
else
{
while(NumOfPage--)
{
/* Store the number of data to be written */
sEEDataNum = sEE_PAGESIZE;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
WriteAddr += sEE_PAGESIZE;
pBuffer += sEE_PAGESIZE;
}
if(NumOfSingle!=0)
{
/* Store the number of data to be written */
sEEDataNum = NumOfSingle;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
}
}
}
/*!< If WriteAddr is not sEE_PAGESIZE aligned */
else
{
/*!< If NumByteToWrite < sEE_PAGESIZE */
if(NumOfPage== 0)
{
/*!< If the number of data to be written is more than the remaining space
in the current page: */
if (NumByteToWrite > count)
{
/* Store the number of data to be written */
sEEDataNum = count;
/*!< Write the data conained in same page */
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
/* Store the number of data to be written */
sEEDataNum = (NumByteToWrite - count);
/*!< Write the remaining data in the following page */
sEE_WritePage((uint8_t*)(pBuffer + count), (WriteAddr + count), (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
}
else
{
/* Store the number of data to be written */
sEEDataNum = NumOfSingle;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
}
}
/*!< If NumByteToWrite > sEE_PAGESIZE */
else
{
NumByteToWrite -= count;
NumOfPage = NumByteToWrite / sEE_PAGESIZE;
NumOfSingle = NumByteToWrite % sEE_PAGESIZE;
if(count != 0)
{
/* Store the number of data to be written */
sEEDataNum = count;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
WriteAddr += count;
pBuffer += count;
}
while(NumOfPage--)
{
/* Store the number of data to be written */
sEEDataNum = sEE_PAGESIZE;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
WriteAddr += sEE_PAGESIZE;
pBuffer += sEE_PAGESIZE;
}
if(NumOfSingle != 0)
{
/* Store the number of data to be written */
sEEDataNum = NumOfSingle;
sEE_WritePage(pBuffer, WriteAddr, (uint8_t*)(&sEEDataNum));
/* Wait transfer through DMA to be complete */
sEETimeout = sEE_TIMEOUT_MAX;
while ((sEEDataNum > 0) && (sEETimeout-- >0))
{}
sEE_WaitEepromStandbyState();
}
}
}
}
/**
* @brief Writes more than one byte to the EEPROM with a single WRITE cycle.
* @note The number of byte can't exceed the EEPROM page size.
* @param pBuffer : pointer to the buffer containing the data to be written to
* the EEPROM.
* @param WriteAddr : EEPROM's internal address to write to.
* @param NumByteToWrite : pointer to the variable holding number of bytes to
* written to the EEPROM.
*
* @note The variable pointed by NumByteToWrite is reset to 0 when all the
* data are read from the EEPROM. Application should monitor this
* variable in order know when the transfer is complete.
*
* @note When number of data to be written is higher than 1, this function just
* configure the communication and enable the DMA channel to transfer data.
* Meanwhile, the user application may perform other tasks.
* When number of data to be written is 1, then the DMA is not used.
*
* @retval None
*/
void sEE_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint8_t* NumByteToWrite)
{
/* Set the pointer to the Number of data to be written. This pointer will be used
by the DMA Transfer Completer interrupt Handler in order to reset the
variable to 0. User should check on this variable in order to know if the
DMA transfer has been complete or not. */
sEEDataWritePointer = NumByteToWrite;
/*!< While the bus is busy */
while(I2C_GetFlagStatus(sEE_I2C, I2C_FLAG_BUSY))
{
}
/*!< Send START condition */
I2C_GenerateSTART(sEE_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for write */
I2C_Send7bitAddress(sEE_I2C, sEEAddress, I2C_Direction_Transmitter);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
}
#ifdef sEE_M24C08
/*!< Send the EEPROM's internal address to write to : only one byte Address */
I2C_SendData(sEE_I2C, WriteAddr);
#elif defined(sEE_M24C64_32)
/*!< Send the EEPROM's internal address to write to : MSB of the address first */
I2C_SendData(sEE_I2C, (uint8_t)((WriteAddr & 0xFF00) >> 8));
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send the EEPROM's internal address to write to : LSB of the address */
I2C_SendData(sEE_I2C, (uint8_t)(WriteAddr & 0x00FF));
#endif /*!< sEE_M24C08 */
/*!< Test on EV8 and clear it */
while(! I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/* If number of data to be written is 1, then DMA couldn't be used */
if ((uint16_t)(*NumByteToWrite) < 2)
{
/*!< Send the byte to be written */
I2C_SendData(sEE_I2C, *pBuffer);
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send STOP condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
(uint8_t)(*NumByteToWrite)--;
}
/* DMA could be used for number of data higher than 1 */
else
{
/* Configure the DMA Tx Channel with the buffer address and the buffer size */
sEE_LowLevel_DMAConfig((uint32_t)pBuffer, (uint8_t)(*NumByteToWrite), sEE_DIRECTION_TX);
/* Enable the DMA Tx Channel */
DMA_Cmd(sEE_I2C_DMA_CHANNEL_TX, ENABLE);
}
}
/**
* @brief Wait for EEPROM Standby state
* @param None
* @retval None
*/
void sEE_WaitEepromStandbyState(void)
{
__IO uint16_t SR1_Tmp = 0;
do
{
/*!< Send START condition */
I2C_GenerateSTART(sEE_I2C, ENABLE);
/*!< Read sEE SR1 register to clear pending flags */
SR1_Tmp = I2C_ReadRegister(sEE_I2C, I2C_Register_SR1);
/*!< Send EEPROM address for write */
I2C_Send7bitAddress(sEE_I2C, sEEAddress, I2C_Direction_Transmitter);
}while(!(I2C_ReadRegister(sEE_I2C, I2C_Register_SR1) & 0x0002));
/*!< Clear AF flag */
I2C_ClearFlag(sEE_I2C, I2C_FLAG_AF);
/*!< STOP condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
}
/**
* @}
*/
/**
* @brief This function handles the DMA Tx Channel interrupt Handler.
* @param None
* @retval None
*/
void sEE_I2C_DMA_TX_IRQHandler(void)
{
/* Check if the DMA transfer is complete */
if(DMA_GetFlagStatus(sEE_I2C_DMA_FLAG_TX_TC) != RESET)
{
/* Disable the DMA Tx Channel and Clear all its Flags */
DMA_Cmd(sEE_I2C_DMA_CHANNEL_TX, DISABLE);
DMA_ClearFlag(sEE_I2C_DMA_FLAG_TX_GL);
/*!< Wait till all data have been physically transferred on the bus */
while(!I2C_CheckEvent(sEE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send STOP condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
/* Reset the variable holding the number of data to be written */
*sEEDataWritePointer = 0;
}
}
/**
* @brief This function handles the DMA Rx Channel interrupt Handler.
* @param None
* @retval None
*/
void sEE_I2C_DMA_RX_IRQHandler(void)
{
/* Check if the DMA transfer is complete */
if(DMA_GetFlagStatus(sEE_I2C_DMA_FLAG_RX_TC) != RESET)
{
/*!< Send STOP Condition */
I2C_GenerateSTOP(sEE_I2C, ENABLE);
/* Disable the DMA Rx Channel and Clear all its Flags */
DMA_Cmd(sEE_I2C_DMA_CHANNEL_RX, DISABLE);
DMA_ClearFlag(sEE_I2C_DMA_FLAG_RX_GL);
/* Reset the variable holding the number of data to be read */
*sEEDataReadPointer = 0;
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_i2c_ee.c
|
C
|
asf20
| 23,820
|
/**
******************************************************************************
* @file stm32_eval_spi_flash.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to manage the SPI M25Pxxx
* FLASH memory mounted on STM32xx-EVAL board (refer to stm32_eval.h
* to know about the boards supporting this memory).
* It implements a high level communication layer for read and write
* from/to this memory. The needed STM32 hardware resources (SPI and
* GPIO) are defined in stm32xx_eval.h file, and the initialization is
* performed in sFLASH_LowLevel_Init() function declared in stm32xx_eval.c
* file.
* You can easily tailor this driver to any other development board,
* by just adapting the defines for hardware resources and
* sFLASH_LowLevel_Init() function.
*
* +-----------------------------------------------------------+
* | Pin assignment |
* +-----------------------------+---------------+-------------+
* | STM32 SPI Pins | sFLASH | Pin |
* +-----------------------------+---------------+-------------+
* | sFLASH_CS_PIN | ChipSelect(/S)| 1 |
* | sFLASH_SPI_MISO_PIN / MISO | DataOut(Q) | 2 |
* | | VCC | 3 (3.3 V)|
* | | GND | 4 (0 V) |
* | sFLASH_SPI_MOSI_PIN / MOSI | DataIn(D) | 5 |
* | sFLASH_SPI_SCK_PIN / SCLK | Clock(C) | 6 |
* | | VCC | 7 (3.3 V)|
* | | VCC | 8 (3.3 V)|
* +-----------------------------+---------------+-------------+
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval_spi_flash.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SPI_FLASH
* @brief This file includes the M25Pxxx SPI FLASH driver of STM32-EVAL boards.
* @{
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_FLASH_Private_Functions
* @{
*/
/**
* @brief DeInitializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_DeInit(void)
{
sFLASH_LowLevel_DeInit();
}
/**
* @brief Initializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_Init(void)
{
SPI_InitTypeDef SPI_InitStructure;
sFLASH_LowLevel_Init();
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
/*!< SPI configuration */
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(sFLASH_SPI, &SPI_InitStructure);
/*!< Enable the sFLASH_SPI */
SPI_Cmd(sFLASH_SPI, ENABLE);
}
/**
* @brief Erases the specified FLASH sector.
* @param SectorAddr: address of the sector to erase.
* @retval None
*/
void sFLASH_EraseSector(uint32_t SectorAddr)
{
/*!< Send write enable instruction */
sFLASH_WriteEnable();
/*!< Sector Erase */
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send Sector Erase instruction */
sFLASH_SendByte(sFLASH_CMD_SE);
/*!< Send SectorAddr high nibble address byte */
sFLASH_SendByte((SectorAddr & 0xFF0000) >> 16);
/*!< Send SectorAddr medium nibble address byte */
sFLASH_SendByte((SectorAddr & 0xFF00) >> 8);
/*!< Send SectorAddr low nibble address byte */
sFLASH_SendByte(SectorAddr & 0xFF);
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
/*!< Wait the end of Flash writing */
sFLASH_WaitForWriteEnd();
}
/**
* @brief Erases the entire FLASH.
* @param None
* @retval None
*/
void sFLASH_EraseBulk(void)
{
/*!< Send write enable instruction */
sFLASH_WriteEnable();
/*!< Bulk Erase */
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send Bulk Erase instruction */
sFLASH_SendByte(sFLASH_CMD_BE);
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
/*!< Wait the end of Flash writing */
sFLASH_WaitForWriteEnd();
}
/**
* @brief Writes more than one byte to the FLASH with a single WRITE cycle
* (Page WRITE sequence).
* @note The number of byte can't exceed the FLASH page size.
* @param pBuffer: pointer to the buffer containing the data to be written
* to the FLASH.
* @param WriteAddr: FLASH's internal address to write to.
* @param NumByteToWrite: number of bytes to write to the FLASH, must be equal
* or less than "sFLASH_PAGESIZE" value.
* @retval None
*/
void sFLASH_WritePage(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite)
{
/*!< Enable the write access to the FLASH */
sFLASH_WriteEnable();
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "Write to Memory " instruction */
sFLASH_SendByte(sFLASH_CMD_WRITE);
/*!< Send WriteAddr high nibble address byte to write to */
sFLASH_SendByte((WriteAddr & 0xFF0000) >> 16);
/*!< Send WriteAddr medium nibble address byte to write to */
sFLASH_SendByte((WriteAddr & 0xFF00) >> 8);
/*!< Send WriteAddr low nibble address byte to write to */
sFLASH_SendByte(WriteAddr & 0xFF);
/*!< while there is data to be written on the FLASH */
while (NumByteToWrite--)
{
/*!< Send the current byte */
sFLASH_SendByte(*pBuffer);
/*!< Point on the next byte to be written */
pBuffer++;
}
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
/*!< Wait the end of Flash writing */
sFLASH_WaitForWriteEnd();
}
/**
* @brief Writes block of data to the FLASH. In this function, the number of
* WRITE cycles are reduced, using Page WRITE sequence.
* @param pBuffer: pointer to the buffer containing the data to be written
* to the FLASH.
* @param WriteAddr: FLASH's internal address to write to.
* @param NumByteToWrite: number of bytes to write to the FLASH.
* @retval None
*/
void sFLASH_WriteBuffer(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite)
{
uint8_t NumOfPage = 0, NumOfSingle = 0, Addr = 0, count = 0, temp = 0;
Addr = WriteAddr % sFLASH_SPI_PAGESIZE;
count = sFLASH_SPI_PAGESIZE - Addr;
NumOfPage = NumByteToWrite / sFLASH_SPI_PAGESIZE;
NumOfSingle = NumByteToWrite % sFLASH_SPI_PAGESIZE;
if (Addr == 0) /*!< WriteAddr is sFLASH_PAGESIZE aligned */
{
if (NumOfPage == 0) /*!< NumByteToWrite < sFLASH_PAGESIZE */
{
sFLASH_WritePage(pBuffer, WriteAddr, NumByteToWrite);
}
else /*!< NumByteToWrite > sFLASH_PAGESIZE */
{
while (NumOfPage--)
{
sFLASH_WritePage(pBuffer, WriteAddr, sFLASH_SPI_PAGESIZE);
WriteAddr += sFLASH_SPI_PAGESIZE;
pBuffer += sFLASH_SPI_PAGESIZE;
}
sFLASH_WritePage(pBuffer, WriteAddr, NumOfSingle);
}
}
else /*!< WriteAddr is not sFLASH_PAGESIZE aligned */
{
if (NumOfPage == 0) /*!< NumByteToWrite < sFLASH_PAGESIZE */
{
if (NumOfSingle > count) /*!< (NumByteToWrite + WriteAddr) > sFLASH_PAGESIZE */
{
temp = NumOfSingle - count;
sFLASH_WritePage(pBuffer, WriteAddr, count);
WriteAddr += count;
pBuffer += count;
sFLASH_WritePage(pBuffer, WriteAddr, temp);
}
else
{
sFLASH_WritePage(pBuffer, WriteAddr, NumByteToWrite);
}
}
else /*!< NumByteToWrite > sFLASH_PAGESIZE */
{
NumByteToWrite -= count;
NumOfPage = NumByteToWrite / sFLASH_SPI_PAGESIZE;
NumOfSingle = NumByteToWrite % sFLASH_SPI_PAGESIZE;
sFLASH_WritePage(pBuffer, WriteAddr, count);
WriteAddr += count;
pBuffer += count;
while (NumOfPage--)
{
sFLASH_WritePage(pBuffer, WriteAddr, sFLASH_SPI_PAGESIZE);
WriteAddr += sFLASH_SPI_PAGESIZE;
pBuffer += sFLASH_SPI_PAGESIZE;
}
if (NumOfSingle != 0)
{
sFLASH_WritePage(pBuffer, WriteAddr, NumOfSingle);
}
}
}
}
/**
* @brief Reads a block of data from the FLASH.
* @param pBuffer: pointer to the buffer that receives the data read from the FLASH.
* @param ReadAddr: FLASH's internal address to read from.
* @param NumByteToRead: number of bytes to read from the FLASH.
* @retval None
*/
void sFLASH_ReadBuffer(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t NumByteToRead)
{
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "Read from Memory " instruction */
sFLASH_SendByte(sFLASH_CMD_READ);
/*!< Send ReadAddr high nibble address byte to read from */
sFLASH_SendByte((ReadAddr & 0xFF0000) >> 16);
/*!< Send ReadAddr medium nibble address byte to read from */
sFLASH_SendByte((ReadAddr& 0xFF00) >> 8);
/*!< Send ReadAddr low nibble address byte to read from */
sFLASH_SendByte(ReadAddr & 0xFF);
while (NumByteToRead--) /*!< while there is data to be read */
{
/*!< Read a byte from the FLASH */
*pBuffer = sFLASH_SendByte(sFLASH_DUMMY_BYTE);
/*!< Point to the next location where the byte read will be saved */
pBuffer++;
}
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
}
/**
* @brief Reads FLASH identification.
* @param None
* @retval FLASH identification
*/
uint32_t sFLASH_ReadID(void)
{
uint32_t Temp = 0, Temp0 = 0, Temp1 = 0, Temp2 = 0;
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "RDID " instruction */
sFLASH_SendByte(0x9F);
/*!< Read a byte from the FLASH */
Temp0 = sFLASH_SendByte(sFLASH_DUMMY_BYTE);
/*!< Read a byte from the FLASH */
Temp1 = sFLASH_SendByte(sFLASH_DUMMY_BYTE);
/*!< Read a byte from the FLASH */
Temp2 = sFLASH_SendByte(sFLASH_DUMMY_BYTE);
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
Temp = (Temp0 << 16) | (Temp1 << 8) | Temp2;
return Temp;
}
/**
* @brief Initiates a read data byte (READ) sequence from the Flash.
* This is done by driving the /CS line low to select the device, then the READ
* instruction is transmitted followed by 3 bytes address. This function exit
* and keep the /CS line low, so the Flash still being selected. With this
* technique the whole content of the Flash is read with a single READ instruction.
* @param ReadAddr: FLASH's internal address to read from.
* @retval None
*/
void sFLASH_StartReadSequence(uint32_t ReadAddr)
{
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "Read from Memory " instruction */
sFLASH_SendByte(sFLASH_CMD_READ);
/*!< Send the 24-bit address of the address to read from -------------------*/
/*!< Send ReadAddr high nibble address byte */
sFLASH_SendByte((ReadAddr & 0xFF0000) >> 16);
/*!< Send ReadAddr medium nibble address byte */
sFLASH_SendByte((ReadAddr& 0xFF00) >> 8);
/*!< Send ReadAddr low nibble address byte */
sFLASH_SendByte(ReadAddr & 0xFF);
}
/**
* @brief Reads a byte from the SPI Flash.
* @note This function must be used only if the Start_Read_Sequence function
* has been previously called.
* @param None
* @retval Byte Read from the SPI Flash.
*/
uint8_t sFLASH_ReadByte(void)
{
return (sFLASH_SendByte(sFLASH_DUMMY_BYTE));
}
/**
* @brief Sends a byte through the SPI interface and return the byte received
* from the SPI bus.
* @param byte: byte to send.
* @retval The value of the received byte.
*/
uint8_t sFLASH_SendByte(uint8_t byte)
{
/*!< Loop while DR register in not emplty */
while (SPI_I2S_GetFlagStatus(sFLASH_SPI, SPI_I2S_FLAG_TXE) == RESET);
/*!< Send byte through the SPI1 peripheral */
SPI_I2S_SendData(sFLASH_SPI, byte);
/*!< Wait to receive a byte */
while (SPI_I2S_GetFlagStatus(sFLASH_SPI, SPI_I2S_FLAG_RXNE) == RESET);
/*!< Return the byte read from the SPI bus */
return SPI_I2S_ReceiveData(sFLASH_SPI);
}
/**
* @brief Sends a Half Word through the SPI interface and return the Half Word
* received from the SPI bus.
* @param HalfWord: Half Word to send.
* @retval The value of the received Half Word.
*/
uint16_t sFLASH_SendHalfWord(uint16_t HalfWord)
{
/*!< Loop while DR register in not emplty */
while (SPI_I2S_GetFlagStatus(sFLASH_SPI, SPI_I2S_FLAG_TXE) == RESET);
/*!< Send Half Word through the sFLASH peripheral */
SPI_I2S_SendData(sFLASH_SPI, HalfWord);
/*!< Wait to receive a Half Word */
while (SPI_I2S_GetFlagStatus(sFLASH_SPI, SPI_I2S_FLAG_RXNE) == RESET);
/*!< Return the Half Word read from the SPI bus */
return SPI_I2S_ReceiveData(sFLASH_SPI);
}
/**
* @brief Enables the write access to the FLASH.
* @param None
* @retval None
*/
void sFLASH_WriteEnable(void)
{
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "Write Enable" instruction */
sFLASH_SendByte(sFLASH_CMD_WREN);
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
}
/**
* @brief Polls the status of the Write In Progress (WIP) flag in the FLASH's
* status register and loop until write opertaion has completed.
* @param None
* @retval None
*/
void sFLASH_WaitForWriteEnd(void)
{
uint8_t flashstatus = 0;
/*!< Select the FLASH: Chip Select low */
sFLASH_CS_LOW();
/*!< Send "Read Status Register" instruction */
sFLASH_SendByte(sFLASH_CMD_RDSR);
/*!< Loop as long as the memory is busy with a write cycle */
do
{
/*!< Send a dummy byte to generate the clock needed by the FLASH
and put the value of the status register in FLASH_Status variable */
flashstatus = sFLASH_SendByte(sFLASH_DUMMY_BYTE);
}
while ((flashstatus & sFLASH_WIP_FLAG) == SET); /* Write in progress */
/*!< Deselect the FLASH: Chip Select high */
sFLASH_CS_HIGH();
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_spi_flash.c
|
C
|
asf20
| 16,245
|
/**
******************************************************************************
* @file stm32_eval_i2c_tsensor.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to manage the I2C LM75
* temperature sensor mounted on STM32xx-EVAL board (refer to stm32_eval.h
* to know about the boards supporting this sensor).
* It implements a high level communication layer for read and write
* from/to this sensor. The needed STM32 hardware resources (I2C and
* GPIO) are defined in stm32xx_eval.h file, and the initialization is
* performed in LM75_LowLevel_Init() function declared in stm32xx_eval.c
* file.
* You can easily tailor this driver to any other development board,
* by just adapting the defines for hardware resources and
* LM75_LowLevel_Init() function.
*
* +-----------------------------------------------------------------+
* | Pin assignment |
* +---------------------------------------+-----------+-------------+
* | STM32 I2C Pins | STLM75 | Pin |
* +---------------------------------------+-----------+-------------+
* | LM75_I2C_SDA_PIN/ SDA | SDA | 1 |
* | LM75_I2C_SCL_PIN/ SCL | SCL | 2 |
* | LM75_I2C_SMBUSALERT_PIN/ SMBUS ALERT | OS/INT | 3 |
* | . | GND | 4 (0V) |
* | . | GND | 5 (0V) |
* | . | GND | 6 (0V) |
* | . | GND | 7 (0V) |
* | . | VDD | 8 (3.3V)|
* +---------------------------------------+-----------+-------------+
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval_i2c_tsensor.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_I2C_TSENSOR
* @brief This file includes the LM75 Temperature Sensor driver of
* STM32-EVAL boards.
* @{
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Defines
* @{
*/
#define LM75_SD_SET 0x01 /*!< Set SD bit in the configuration register */
#define LM75_SD_RESET 0xFE /*!< Reset SD bit in the configuration register */
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_TSENSOR_Private_Functions
* @{
*/
/**
* @brief DeInitializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_DeInit(void)
{
LM75_LowLevel_DeInit();
}
/**
* @brief Initializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_Init(void)
{
I2C_InitTypeDef I2C_InitStructure;
LM75_LowLevel_Init();
I2C_DeInit(LM75_I2C);
/*!< LM75_I2C Init */
I2C_InitStructure.I2C_Mode = I2C_Mode_SMBusHost;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = LM75_I2C_SPEED;
I2C_Init(LM75_I2C, &I2C_InitStructure);
/*!< Enable SMBus Alert interrupt */
I2C_ITConfig(LM75_I2C, I2C_IT_ERR, ENABLE);
/*!< LM75_I2C Init */
I2C_Cmd(LM75_I2C, ENABLE);
}
/**
* @brief Checks the LM75 status.
* @param None
* @retval ErrorStatus: LM75 Status (ERROR or SUCCESS).
*/
ErrorStatus LM75_GetStatus(void)
{
uint32_t I2C_TimeOut = I2C_TIMEOUT;
/*!< Clear the LM75_I2C AF flag */
I2C_ClearFlag(LM75_I2C, I2C_FLAG_AF);
/*!< Enable LM75_I2C acknowledgement if it is already disabled by other function */
I2C_AcknowledgeConfig(LM75_I2C, ENABLE);
/*---------------------------- Transmission Phase ---------------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while ((!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) && I2C_TimeOut) /*!< EV5 */
{
I2C_TimeOut--;
}
if (I2C_TimeOut == 0)
{
return ERROR;
}
I2C_TimeOut = I2C_TIMEOUT;
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
while ((!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) && I2C_TimeOut)/* EV6 */
{
I2C_TimeOut--;
}
if ((I2C_GetFlagStatus(LM75_I2C, I2C_FLAG_AF) != 0x00) || (I2C_TimeOut == 0))
{
return ERROR;
}
else
{
return SUCCESS;
}
}
/**
* @brief Read the specified register from the LM75.
* @param RegName: specifies the LM75 register to be read.
* This member can be one of the following values:
* - LM75_REG_TEMP: temperature register
* - LM75_REG_TOS: Over-limit temperature register
* - LM75_REG_THYS: Hysteresis temperature register
* @retval LM75 register value.
*/
uint16_t LM75_ReadReg(uint8_t RegName)
{
__IO uint16_t RegValue = 0;
/*!< Enable LM75_I2C acknowledgement if it is already disabled by other function */
I2C_AcknowledgeConfig(LM75_I2C, ENABLE);
/*--------------------------- Transmission Phase ----------------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the specified register data pointer */
I2C_SendData(LM75_I2C, RegName);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*------------------------------ Reception Phase ----------------------------*/
/*!< Send Re-STRAT condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for read */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Test on EV7 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED)) /*!< EV7 */
{
}
/*!< Store LM75_I2C received data */
RegValue = (uint16_t)(I2C_ReceiveData(LM75_I2C) << 8);
/*!< Disable LM75_I2C acknowledgement */
I2C_AcknowledgeConfig(LM75_I2C, DISABLE);
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
/*!< Test on RXNE flag */
while (I2C_GetFlagStatus(LM75_I2C, I2C_FLAG_RXNE) == RESET)
{
}
/*!< Store LM75_I2C received data */
RegValue |= I2C_ReceiveData(LM75_I2C);
/*!< Return register value */
return (RegValue);
}
/**
* @brief Write to the specified register of the LM75.
* @param RegName: specifies the LM75 register to be written.
* This member can be one of the following values:
* - LM75_REG_TOS: Over-limit temperature register
* - LM75_REG_THYS: Hysteresis temperature register
* @param RegValue: value to be written to LM75 register.
* @retval None
*/
void LM75_WriteReg(uint8_t RegName, uint16_t RegValue)
{
/*-------------------------------- Transmission Phase -----------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the specified register data pointer */
I2C_SendData(LM75_I2C, RegName);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C data */
I2C_SendData(LM75_I2C, (uint8_t)(RegValue >> 8));
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C data */
I2C_SendData(LM75_I2C, (uint8_t)RegValue);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
}
/**
* @brief Read Temperature register of LM75: double temperature value.
* @param None
* @retval LM75 measured temperature value.
*/
uint16_t LM75_ReadTemp(void)
{
__IO uint16_t RegValue = 0;
/*!< Enable LM75_I2C acknowledgement if it is already disabled by other function */
I2C_AcknowledgeConfig(LM75_I2C, ENABLE);
/*------------------------------------- Transmission Phase ------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the temperature register data pointer */
I2C_SendData(LM75_I2C, LM75_REG_TEMP);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*-------------------------------- Reception Phase --------------------------*/
/*!< Send Re-STRAT condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for read */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Test on EV7 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED)) /*!< EV7 */
{
}
/*!< Store LM75_I2C received data */
RegValue = I2C_ReceiveData(LM75_I2C) << 8;
/*!< Disable LM75_I2C acknowledgement */
I2C_AcknowledgeConfig(LM75_I2C, DISABLE);
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
/*!< Test on RXNE flag */
while (I2C_GetFlagStatus(LM75_I2C, I2C_FLAG_RXNE) == RESET)
{
}
/*!< Store LM75_I2C received data */
RegValue |= I2C_ReceiveData(LM75_I2C);
/*!< Return Temperature value */
return (RegValue >> 7);
}
/**
* @brief Read the configuration register from the LM75.
* @param None
* @retval LM75 configuration register value.
*/
uint8_t LM75_ReadConfReg(void)
{
__IO uint8_t RegValue = 0;
/*!< Enable LM75_I2C acknowledgement if it is already disabled by other function */
I2C_AcknowledgeConfig(LM75_I2C, ENABLE);
/*----------------------------- Transmission Phase --------------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the configuration register data pointer */
I2C_SendData(LM75_I2C, LM75_REG_CONF);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*----------------------------- Reception Phase -----------------------------*/
/*!< Send Re-STRAT condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for read */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Disable LM75_I2C acknowledgement */
I2C_AcknowledgeConfig(LM75_I2C, DISABLE);
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
/*!< Test on RXNE flag */
while (I2C_GetFlagStatus(LM75_I2C, I2C_FLAG_RXNE) == RESET);
/*!< Store LM75_I2C received data */
RegValue = I2C_ReceiveData(LM75_I2C);
/*!< Return configuration register value */
return (RegValue);
}
/**
* @brief Write to the configuration register of the LM75.
* @param RegValue: sepecifies the value to be written to LM75 configuration
* register.
* @retval None
*/
void LM75_WriteConfReg(uint8_t RegValue)
{
/*-------------------------------- Transmission Phase -----------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the configuration register data pointer */
I2C_SendData(LM75_I2C, LM75_REG_CONF);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C data */
I2C_SendData(LM75_I2C, RegValue);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
}
/**
* @brief Enables or disables the LM75.
* @param NewState: specifies the LM75 new status. This parameter can be ENABLE
* or DISABLE.
* @retval None
*/
void LM75_ShutDown(FunctionalState NewState)
{
__IO uint8_t RegValue = 0;
/*---------------------------- Transmission Phase ---------------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the configuration register data pointer */
I2C_SendData(LM75_I2C, LM75_REG_CONF);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*-------------------------------- Reception Phase --------------------------*/
/*!< Send Re-STRAT condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for read */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Disable LM75_I2C acknowledgement */
I2C_AcknowledgeConfig(LM75_I2C, DISABLE);
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
/*!< Test on RXNE flag */
while (I2C_GetFlagStatus(LM75_I2C, I2C_FLAG_RXNE) == RESET);
/*!< Store LM75_I2C received data */
RegValue = I2C_ReceiveData(LM75_I2C);
/*------------------------------------ Transmission Phase -------------------*/
/*!< Send LM75_I2C START condition */
I2C_GenerateSTART(LM75_I2C, ENABLE);
/*!< Test on LM75_I2C EV5 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_MODE_SELECT)) /*!< EV5 */
{
}
/*!< Send STLM75 slave address for write */
I2C_Send7bitAddress(LM75_I2C, LM75_ADDR, I2C_Direction_Transmitter);
/*!< Test on LM75_I2C EV6 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) /*!< EV6 */
{
}
/*!< Send the configuration register data pointer */
I2C_SendData(LM75_I2C, LM75_REG_CONF);
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Enable or disable SD bit */
if (NewState != DISABLE)
{
/*!< Enable LM75 */
I2C_SendData(LM75_I2C, RegValue & LM75_SD_RESET);
}
else
{
/*!< Disable LM75 */
I2C_SendData(LM75_I2C, RegValue | LM75_SD_SET);
}
/*!< Test on LM75_I2C EV8 and clear it */
while (!I2C_CheckEvent(LM75_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) /*!< EV8 */
{
}
/*!< Send LM75_I2C STOP Condition */
I2C_GenerateSTOP(LM75_I2C, ENABLE);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_i2c_tsensor.c
|
C
|
asf20
| 19,788
|
/**
******************************************************************************
* @file fonts.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief Header for fonts.c
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __FONTS_H
#define __FONTS_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include <stdint.h>
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup FONTS
* @{
*/
/** @defgroup FONTS_Exported_Types
* @{
*/
typedef struct _tFont
{
const uint16_t *table;
uint16_t Width;
uint16_t Height;
} sFONT;
extern sFONT Font16x24;
extern sFONT Font12x12;
extern sFONT Font8x12;
extern sFONT Font8x8;
/**
* @}
*/
/** @defgroup FONTS_Exported_Constants
* @{
*/
#define LINE(x) ((x) * (((sFONT *)LCD_GetFont())->Height))
/**
* @}
*/
/** @defgroup FONTS_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup FONTS_Exported_Functions
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __FONTS_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/fonts.h
|
C
|
asf20
| 2,151
|
/**
******************************************************************************
* @file stm32_eval_spi_sd.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to manage the SPI SD
* Card memory mounted on STM32xx-EVAL board (refer to stm32_eval.h
* to know about the boards supporting this memory).
* It implements a high level communication layer for read and write
* from/to this memory. The needed STM32 hardware resources (SPI and
* GPIO) are defined in stm32xx_eval.h file, and the initialization is
* performed in SD_LowLevel_Init() function declared in stm32xx_eval.c
* file.
* You can easily tailor this driver to any other development board,
* by just adapting the defines for hardware resources and
* SD_LowLevel_Init() function.
*
* +-------------------------------------------------------+
* | Pin assignment |
* +-------------------------+---------------+-------------+
* | STM32 SPI Pins | SD | Pin |
* +-------------------------+---------------+-------------+
* | SD_SPI_CS_PIN | ChipSelect | 1 |
* | SD_SPI_MOSI_PIN / MOSI | DataIn | 2 |
* | | GND | 3 (0 V) |
* | | VDD | 4 (3.3 V)|
* | SD_SPI_SCK_PIN / SCLK | Clock | 5 |
* | | GND | 6 (0 V) |
* | SD_SPI_MISO_PIN / MISO | DataOut | 7 |
* +-------------------------+---------------+-------------+
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval_spi_sd.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SPI_SD
* @brief This file includes the SD card driver of STM32-EVAL boards.
* @{
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Function_Prototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SPI_SD_Private_Functions
* @{
*/
/**
* @brief DeInitializes the SD/SD communication.
* @param None
* @retval None
*/
void SD_DeInit(void)
{
SD_LowLevel_DeInit();
}
/**
* @brief Initializes the SD/SD communication.
* @param None
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_Init(void)
{
uint32_t i = 0;
/*!< Initialize SD_SPI */
SD_LowLevel_Init();
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte 0xFF, 10 times with CS high */
/*!< Rise CS and MOSI for 80 clocks cycles */
for (i = 0; i <= 9; i++)
{
/*!< Send dummy byte 0xFF */
SD_WriteByte(SD_DUMMY_BYTE);
}
/*------------Put SD in SPI mode--------------*/
/*!< SD initialized and set to SPI mode properly */
return (SD_GoIdleState());
}
/**
* @brief Detect if SD card is correctly plugged in the memory slot.
* @param None
* @retval Return if SD is detected or not
*/
uint8_t SD_Detect(void)
{
__IO uint8_t status = SD_PRESENT;
/*!< Check GPIO to detect SD */
if (GPIO_ReadInputData(SD_DETECT_GPIO_PORT) & SD_DETECT_PIN)
{
status = SD_NOT_PRESENT;
}
return status;
}
/**
* @brief Returns information about specific card.
* @param cardinfo: pointer to a SD_CardInfo structure that contains all SD
* card information.
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo)
{
SD_Error status = SD_RESPONSE_FAILURE;
status = SD_GetCSDRegister(&(cardinfo->SD_csd));
status = SD_GetCIDRegister(&(cardinfo->SD_cid));
cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) ;
cardinfo->CardCapacity *= (1 << (cardinfo->SD_csd.DeviceSizeMul + 2));
cardinfo->CardBlockSize = 1 << (cardinfo->SD_csd.RdBlockLen);
cardinfo->CardCapacity *= cardinfo->CardBlockSize;
/*!< Returns the reponse */
return status;
}
/**
* @brief Reads a block of data from the SD.
* @param pBuffer: pointer to the buffer that receives the data read from the
* SD.
* @param ReadAddr: SD's internal address to read from.
* @param BlockSize: the SD card Data block size.
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_ReadBlock(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize)
{
uint32_t i = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */
SD_SendCmd(SD_CMD_READ_SINGLE_BLOCK, ReadAddr, 0xFF);
/*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */
if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
/*!< Now look for the data token to signify the start of the data */
if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
{
/*!< Read the SD block data : read NumByteToRead data */
for (i = 0; i < BlockSize; i++)
{
/*!< Save the received data */
*pBuffer = SD_ReadByte();
*
/*!< Point to the next location where the byte read will be saved */
pBuffer++;
}
/*!< Get CRC bytes (not really needed by us, but required by SD) */
SD_ReadByte();
SD_ReadByte();
/*!< Set response value to success */
rvalue = SD_RESPONSE_NO_ERROR;
}
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Returns the reponse */
return rvalue;
}
/**
* @brief Reads multiple block of data from the SD.
* @param pBuffer: pointer to the buffer that receives the data read from the
* SD.
* @param ReadAddr: SD's internal address to read from.
* @param BlockSize: the SD card Data block size.
* @param NumberOfBlocks: number of blocks to be read.
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_ReadMultiBlocks(uint8_t* pBuffer, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
{
uint32_t i = 0, Offset = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
/*!< SD chip select low */
SD_CS_LOW();
/*!< Data transfer */
while (NumberOfBlocks--)
{
/*!< Send CMD17 (SD_CMD_READ_SINGLE_BLOCK) to read one block */
SD_SendCmd (SD_CMD_READ_SINGLE_BLOCK, ReadAddr + Offset, 0xFF);
/*!< Check if the SD acknowledged the read block command: R1 response (0x00: no errors) */
if (SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
return SD_RESPONSE_FAILURE;
}
/*!< Now look for the data token to signify the start of the data */
if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
{
/*!< Read the SD block data : read NumByteToRead data */
for (i = 0; i < BlockSize; i++)
{
/*!< Read the pointed data */
*pBuffer = SD_ReadByte();
/*!< Point to the next location where the byte read will be saved */
pBuffer++;
}
/*!< Set next read address*/
Offset += 512;
/*!< get CRC bytes (not really needed by us, but required by SD) */
SD_ReadByte();
SD_ReadByte();
/*!< Set response value to success */
rvalue = SD_RESPONSE_NO_ERROR;
}
else
{
/*!< Set response value to failure */
rvalue = SD_RESPONSE_FAILURE;
}
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Returns the reponse */
return rvalue;
}
/**
* @brief Writes a block on the SD
* @param pBuffer: pointer to the buffer containing the data to be written on
* the SD.
* @param WriteAddr: address to write on.
* @param BlockSize: the SD card Data block size.
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_WriteBlock(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize)
{
uint32_t i = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write multiple block */
SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr, 0xFF);
/*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */
if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
/*!< Send a dummy byte */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Send the data token to signify the start of the data */
SD_WriteByte(0xFE);
/*!< Write the block data to SD : write count data by block */
for (i = 0; i < BlockSize; i++)
{
/*!< Send the pointed byte */
SD_WriteByte(*pBuffer);
/*!< Point to the next location where the byte read will be saved */
pBuffer++;
}
/*!< Put CRC bytes (not really needed by us, but required by SD) */
SD_ReadByte();
SD_ReadByte();
/*!< Read data response */
if (SD_GetDataResponse() == SD_DATA_OK)
{
rvalue = SD_RESPONSE_NO_ERROR;
}
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Returns the reponse */
return rvalue;
}
/**
* @brief Writes many blocks on the SD
* @param pBuffer: pointer to the buffer containing the data to be written on
* the SD.
* @param WriteAddr: address to write on.
* @param BlockSize: the SD card Data block size.
* @param NumberOfBlocks: number of blocks to be written.
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_WriteMultiBlocks(uint8_t* pBuffer, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
{
uint32_t i = 0, Offset = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
/*!< SD chip select low */
SD_CS_LOW();
/*!< Data transfer */
while (NumberOfBlocks--)
{
/*!< Send CMD24 (SD_CMD_WRITE_SINGLE_BLOCK) to write blocks */
SD_SendCmd(SD_CMD_WRITE_SINGLE_BLOCK, WriteAddr + Offset, 0xFF);
/*!< Check if the SD acknowledged the write block command: R1 response (0x00: no errors) */
if (SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
return SD_RESPONSE_FAILURE;
}
/*!< Send dummy byte */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Send the data token to signify the start of the data */
SD_WriteByte(SD_START_DATA_SINGLE_BLOCK_WRITE);
/*!< Write the block data to SD : write count data by block */
for (i = 0; i < BlockSize; i++)
{
/*!< Send the pointed byte */
SD_WriteByte(*pBuffer);
/*!< Point to the next location where the byte read will be saved */
pBuffer++;
}
/*!< Set next write address */
Offset += 512;
/*!< Put CRC bytes (not really needed by us, but required by SD) */
SD_ReadByte();
SD_ReadByte();
/*!< Read data response */
if (SD_GetDataResponse() == SD_DATA_OK)
{
/*!< Set response value to success */
rvalue = SD_RESPONSE_NO_ERROR;
}
else
{
/*!< Set response value to failure */
rvalue = SD_RESPONSE_FAILURE;
}
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Returns the reponse */
return rvalue;
}
/**
* @brief Read the CSD card register.
* Reading the contents of the CSD register in SPI mode is a simple
* read-block transaction.
* @param SD_csd: pointer on an SCD register structure
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_GetCSDRegister(SD_CSD* SD_csd)
{
uint32_t i = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
uint8_t CSD_Tab[16];
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD9 (CSD register) or CMD10(CSD register) */
SD_SendCmd(SD_CMD_SEND_CSD, 0, 0xFF);
/*!< Wait for response in the R1 format (0x00 is no errors) */
if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
{
for (i = 0; i < 16; i++)
{
/*!< Store CSD register value on CSD_Tab */
CSD_Tab[i] = SD_ReadByte();
}
}
/*!< Get CRC bytes (not really needed by us, but required by SD) */
SD_WriteByte(SD_DUMMY_BYTE);
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Set response value to success */
rvalue = SD_RESPONSE_NO_ERROR;
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Byte 0 */
SD_csd->CSDStruct = (CSD_Tab[0] & 0xC0) >> 6;
SD_csd->SysSpecVersion = (CSD_Tab[0] & 0x3C) >> 2;
SD_csd->Reserved1 = CSD_Tab[0] & 0x03;
/*!< Byte 1 */
SD_csd->TAAC = CSD_Tab[1];
/*!< Byte 2 */
SD_csd->NSAC = CSD_Tab[2];
/*!< Byte 3 */
SD_csd->MaxBusClkFrec = CSD_Tab[3];
/*!< Byte 4 */
SD_csd->CardComdClasses = CSD_Tab[4] << 4;
/*!< Byte 5 */
SD_csd->CardComdClasses |= (CSD_Tab[5] & 0xF0) >> 4;
SD_csd->RdBlockLen = CSD_Tab[5] & 0x0F;
/*!< Byte 6 */
SD_csd->PartBlockRead = (CSD_Tab[6] & 0x80) >> 7;
SD_csd->WrBlockMisalign = (CSD_Tab[6] & 0x40) >> 6;
SD_csd->RdBlockMisalign = (CSD_Tab[6] & 0x20) >> 5;
SD_csd->DSRImpl = (CSD_Tab[6] & 0x10) >> 4;
SD_csd->Reserved2 = 0; /*!< Reserved */
SD_csd->DeviceSize = (CSD_Tab[6] & 0x03) << 10;
/*!< Byte 7 */
SD_csd->DeviceSize |= (CSD_Tab[7]) << 2;
/*!< Byte 8 */
SD_csd->DeviceSize |= (CSD_Tab[8] & 0xC0) >> 6;
SD_csd->MaxRdCurrentVDDMin = (CSD_Tab[8] & 0x38) >> 3;
SD_csd->MaxRdCurrentVDDMax = (CSD_Tab[8] & 0x07);
/*!< Byte 9 */
SD_csd->MaxWrCurrentVDDMin = (CSD_Tab[9] & 0xE0) >> 5;
SD_csd->MaxWrCurrentVDDMax = (CSD_Tab[9] & 0x1C) >> 2;
SD_csd->DeviceSizeMul = (CSD_Tab[9] & 0x03) << 1;
/*!< Byte 10 */
SD_csd->DeviceSizeMul |= (CSD_Tab[10] & 0x80) >> 7;
SD_csd->EraseGrSize = (CSD_Tab[10] & 0x40) >> 6;
SD_csd->EraseGrMul = (CSD_Tab[10] & 0x3F) << 1;
/*!< Byte 11 */
SD_csd->EraseGrMul |= (CSD_Tab[11] & 0x80) >> 7;
SD_csd->WrProtectGrSize = (CSD_Tab[11] & 0x7F);
/*!< Byte 12 */
SD_csd->WrProtectGrEnable = (CSD_Tab[12] & 0x80) >> 7;
SD_csd->ManDeflECC = (CSD_Tab[12] & 0x60) >> 5;
SD_csd->WrSpeedFact = (CSD_Tab[12] & 0x1C) >> 2;
SD_csd->MaxWrBlockLen = (CSD_Tab[12] & 0x03) << 2;
/*!< Byte 13 */
SD_csd->MaxWrBlockLen |= (CSD_Tab[13] & 0xC0) >> 6;
SD_csd->WriteBlockPaPartial = (CSD_Tab[13] & 0x20) >> 5;
SD_csd->Reserved3 = 0;
SD_csd->ContentProtectAppli = (CSD_Tab[13] & 0x01);
/*!< Byte 14 */
SD_csd->FileFormatGrouop = (CSD_Tab[14] & 0x80) >> 7;
SD_csd->CopyFlag = (CSD_Tab[14] & 0x40) >> 6;
SD_csd->PermWrProtect = (CSD_Tab[14] & 0x20) >> 5;
SD_csd->TempWrProtect = (CSD_Tab[14] & 0x10) >> 4;
SD_csd->FileFormat = (CSD_Tab[14] & 0x0C) >> 2;
SD_csd->ECC = (CSD_Tab[14] & 0x03);
/*!< Byte 15 */
SD_csd->CSD_CRC = (CSD_Tab[15] & 0xFE) >> 1;
SD_csd->Reserved4 = 1;
/*!< Return the reponse */
return rvalue;
}
/**
* @brief Read the CID card register.
* Reading the contents of the CID register in SPI mode is a simple
* read-block transaction.
* @param SD_cid: pointer on an CID register structure
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_GetCIDRegister(SD_CID* SD_cid)
{
uint32_t i = 0;
SD_Error rvalue = SD_RESPONSE_FAILURE;
uint8_t CID_Tab[16];
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD10 (CID register) */
SD_SendCmd(SD_CMD_SEND_CID, 0, 0xFF);
/*!< Wait for response in the R1 format (0x00 is no errors) */
if (!SD_GetResponse(SD_RESPONSE_NO_ERROR))
{
if (!SD_GetResponse(SD_START_DATA_SINGLE_BLOCK_READ))
{
/*!< Store CID register value on CID_Tab */
for (i = 0; i < 16; i++)
{
CID_Tab[i] = SD_ReadByte();
}
}
/*!< Get CRC bytes (not really needed by us, but required by SD) */
SD_WriteByte(SD_DUMMY_BYTE);
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Set response value to success */
rvalue = SD_RESPONSE_NO_ERROR;
}
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte: 8 Clock pulses of delay */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< Byte 0 */
SD_cid->ManufacturerID = CID_Tab[0];
/*!< Byte 1 */
SD_cid->OEM_AppliID = CID_Tab[1] << 8;
/*!< Byte 2 */
SD_cid->OEM_AppliID |= CID_Tab[2];
/*!< Byte 3 */
SD_cid->ProdName1 = CID_Tab[3] << 24;
/*!< Byte 4 */
SD_cid->ProdName1 |= CID_Tab[4] << 16;
/*!< Byte 5 */
SD_cid->ProdName1 |= CID_Tab[5] << 8;
/*!< Byte 6 */
SD_cid->ProdName1 |= CID_Tab[6];
/*!< Byte 7 */
SD_cid->ProdName2 = CID_Tab[7];
/*!< Byte 8 */
SD_cid->ProdRev = CID_Tab[8];
/*!< Byte 9 */
SD_cid->ProdSN = CID_Tab[9] << 24;
/*!< Byte 10 */
SD_cid->ProdSN |= CID_Tab[10] << 16;
/*!< Byte 11 */
SD_cid->ProdSN |= CID_Tab[11] << 8;
/*!< Byte 12 */
SD_cid->ProdSN |= CID_Tab[12];
/*!< Byte 13 */
SD_cid->Reserved1 |= (CID_Tab[13] & 0xF0) >> 4;
SD_cid->ManufactDate = (CID_Tab[13] & 0x0F) << 8;
/*!< Byte 14 */
SD_cid->ManufactDate |= CID_Tab[14];
/*!< Byte 15 */
SD_cid->CID_CRC = (CID_Tab[15] & 0xFE) >> 1;
SD_cid->Reserved2 = 1;
/*!< Return the reponse */
return rvalue;
}
/**
* @brief Send 5 bytes command to the SD card.
* @param Cmd: The user expected command to send to SD card.
* @param Arg: The command argument.
* @param Crc: The CRC.
* @retval None
*/
void SD_SendCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc)
{
uint32_t i = 0x00;
uint8_t Frame[6];
Frame[0] = (Cmd | 0x40); /*!< Construct byte 1 */
Frame[1] = (uint8_t)(Arg >> 24); /*!< Construct byte 2 */
Frame[2] = (uint8_t)(Arg >> 16); /*!< Construct byte 3 */
Frame[3] = (uint8_t)(Arg >> 8); /*!< Construct byte 4 */
Frame[4] = (uint8_t)(Arg); /*!< Construct byte 5 */
Frame[5] = (Crc); /*!< Construct CRC: byte 6 */
for (i = 0; i < 6; i++)
{
SD_WriteByte(Frame[i]); /*!< Send the Cmd bytes */
}
}
/**
* @brief Get SD card data response.
* @param None
* @retval The SD status: Read data response xxx0<status>1
* - status 010: Data accecpted
* - status 101: Data rejected due to a crc error
* - status 110: Data rejected due to a Write error.
* - status 111: Data rejected due to other error.
*/
uint8_t SD_GetDataResponse(void)
{
uint32_t i = 0;
uint8_t response, rvalue;
while (i <= 64)
{
/*!< Read resonse */
response = SD_ReadByte();
/*!< Mask unused bits */
response &= 0x1F;
switch (response)
{
case SD_DATA_OK:
{
rvalue = SD_DATA_OK;
break;
}
case SD_DATA_CRC_ERROR:
return SD_DATA_CRC_ERROR;
case SD_DATA_WRITE_ERROR:
return SD_DATA_WRITE_ERROR;
default:
{
rvalue = SD_DATA_OTHER_ERROR;
break;
}
}
/*!< Exit loop in case of data ok */
if (rvalue == SD_DATA_OK)
break;
/*!< Increment loop counter */
i++;
}
/*!< Wait null data */
while (SD_ReadByte() == 0);
/*!< Return response */
return response;
}
/**
* @brief Returns the SD response.
* @param None
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_GetResponse(uint8_t Response)
{
uint32_t Count = 0xFFF;
/*!< Check if response is got or a timeout is happen */
while ((SD_ReadByte() != Response) && Count)
{
Count--;
}
if (Count == 0)
{
/*!< After time out */
return SD_RESPONSE_FAILURE;
}
else
{
/*!< Right response got */
return SD_RESPONSE_NO_ERROR;
}
}
/**
* @brief Returns the SD status.
* @param None
* @retval The SD status.
*/
uint16_t SD_GetStatus(void)
{
uint16_t Status = 0;
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD13 (SD_SEND_STATUS) to get SD status */
SD_SendCmd(SD_CMD_SEND_STATUS, 0, 0xFF);
Status = SD_ReadByte();
Status |= (uint16_t)(SD_ReadByte() << 8);
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte 0xFF */
SD_WriteByte(SD_DUMMY_BYTE);
return Status;
}
/**
* @brief Put SD in Idle state.
* @param None
* @retval The SD Response:
* - SD_RESPONSE_FAILURE: Sequence failed
* - SD_RESPONSE_NO_ERROR: Sequence succeed
*/
SD_Error SD_GoIdleState(void)
{
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD0 (SD_CMD_GO_IDLE_STATE) to put SD in SPI mode */
SD_SendCmd(SD_CMD_GO_IDLE_STATE, 0, 0x95);
/*!< Wait for In Idle State Response (R1 Format) equal to 0x01 */
if (SD_GetResponse(SD_IN_IDLE_STATE))
{
/*!< No Idle State Response: return response failue */
return SD_RESPONSE_FAILURE;
}
/*----------Activates the card initialization process-----------*/
do
{
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send Dummy byte 0xFF */
SD_WriteByte(SD_DUMMY_BYTE);
/*!< SD chip select low */
SD_CS_LOW();
/*!< Send CMD1 (Activates the card process) until response equal to 0x0 */
SD_SendCmd(SD_CMD_SEND_OP_COND, 0, 0xFF);
/*!< Wait for no error Response (R1 Format) equal to 0x00 */
}
while (SD_GetResponse(SD_RESPONSE_NO_ERROR));
/*!< SD chip select high */
SD_CS_HIGH();
/*!< Send dummy byte 0xFF */
SD_WriteByte(SD_DUMMY_BYTE);
return SD_RESPONSE_NO_ERROR;
}
/**
* @brief Write a byte on the SD.
* @param Data: byte to send.
* @retval None
*/
uint8_t SD_WriteByte(uint8_t Data)
{
/*!< Wait until the transmit buffer is empty */
while(SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_TXE) == RESET)
{
}
/*!< Send the byte */
SPI_I2S_SendData(SD_SPI, Data);
/*!< Wait to receive a byte*/
while(SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_RXNE) == RESET)
{
}
/*!< Return the byte read from the SPI bus */
return SPI_I2S_ReceiveData(SD_SPI);
}
/**
* @brief Read a byte from the SD.
* @param None
* @retval The received byte.
*/
uint8_t SD_ReadByte(void)
{
uint8_t Data = 0;
/*!< Wait until the transmit buffer is empty */
while (SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_TXE) == RESET)
{
}
/*!< Send the byte */
SPI_I2S_SendData(SD_SPI, SD_DUMMY_BYTE);
/*!< Wait until a data is received */
while (SPI_I2S_GetFlagStatus(SD_SPI, SPI_I2S_FLAG_RXNE) == RESET)
{
}
/*!< Get the received data */
Data = SPI_I2S_ReceiveData(SD_SPI);
/*!< Return the shifted data */
return Data;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_spi_sd.c
|
C
|
asf20
| 25,282
|
/**
******************************************************************************
* @file stm32_eval_sdio_sd.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides a set of functions needed to manage the SDIO SD
* Card memory mounted on STM32xx-EVAL board (refer to stm32_eval.h
* to know about the boards supporting this memory).
* It implements a high level communication layer for read and write
* from/to this memory. The needed STM32 hardware resources (SDIO and
* GPIO) are defined in stm32xx_eval.h file, and the initialization is
* performed in SD_LowLevel_Init() function declared in stm32xx_eval.c
* file.
* You can easily tailor this driver to any other development board,
* by just adapting the defines for hardware resources and
* SD_LowLevel_Init() function.
*
* +-----------------------------------------------------------+
* | Pin assignment |
* +-----------------------------+---------------+-------------+
* | STM32 SDIO Pins | SD | Pin |
* +-----------------------------+---------------+-------------+
* | SDIO D2 | D2 | 1 |
* | SDIO D3 | D3 | 2 |
* | SDIO CMD | CMD | 3 |
* | | VCC | 4 (3.3 V)|
* | SDIO CLK | CLK | 5 |
* | | GND | 6 (0 V) |
* | SDIO D0 | D0 | 7 |
* | SDIO D1 | D1 | 8 |
* +-----------------------------+---------------+-------------+
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval_sdio_sd.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SDIO_SD
* @brief This file provides all the SD Card driver firmware functions.
* @{
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Defines
* @{
*/
/**
* @brief SDIO Static flags, TimeOut, FIFO Address
*/
#define NULL 0
#define SDIO_STATIC_FLAGS ((uint32_t)0x000005FF)
#define SDIO_CMD0TIMEOUT ((uint32_t)0x00010000)
/**
* @brief Mask for errors Card Status R1 (OCR Register)
*/
#define SD_OCR_ADDR_OUT_OF_RANGE ((uint32_t)0x80000000)
#define SD_OCR_ADDR_MISALIGNED ((uint32_t)0x40000000)
#define SD_OCR_BLOCK_LEN_ERR ((uint32_t)0x20000000)
#define SD_OCR_ERASE_SEQ_ERR ((uint32_t)0x10000000)
#define SD_OCR_BAD_ERASE_PARAM ((uint32_t)0x08000000)
#define SD_OCR_WRITE_PROT_VIOLATION ((uint32_t)0x04000000)
#define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000)
#define SD_OCR_COM_CRC_FAILED ((uint32_t)0x00800000)
#define SD_OCR_ILLEGAL_CMD ((uint32_t)0x00400000)
#define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000)
#define SD_OCR_CC_ERROR ((uint32_t)0x00100000)
#define SD_OCR_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00080000)
#define SD_OCR_STREAM_READ_UNDERRUN ((uint32_t)0x00040000)
#define SD_OCR_STREAM_WRITE_OVERRUN ((uint32_t)0x00020000)
#define SD_OCR_CID_CSD_OVERWRIETE ((uint32_t)0x00010000)
#define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000)
#define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000)
#define SD_OCR_ERASE_RESET ((uint32_t)0x00002000)
#define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008)
#define SD_OCR_ERRORBITS ((uint32_t)0xFDFFE008)
/**
* @brief Masks for R6 Response
*/
#define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000)
#define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000)
#define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000)
#define SD_VOLTAGE_WINDOW_SD ((uint32_t)0x80100000)
#define SD_HIGH_CAPACITY ((uint32_t)0x40000000)
#define SD_STD_CAPACITY ((uint32_t)0x00000000)
#define SD_CHECK_PATTERN ((uint32_t)0x000001AA)
#define SD_MAX_VOLT_TRIAL ((uint32_t)0x0000FFFF)
#define SD_ALLZERO ((uint32_t)0x00000000)
#define SD_WIDE_BUS_SUPPORT ((uint32_t)0x00040000)
#define SD_SINGLE_BUS_SUPPORT ((uint32_t)0x00010000)
#define SD_CARD_LOCKED ((uint32_t)0x02000000)
#define SD_DATATIMEOUT ((uint32_t)0x000FFFFF)
#define SD_0TO7BITS ((uint32_t)0x000000FF)
#define SD_8TO15BITS ((uint32_t)0x0000FF00)
#define SD_16TO23BITS ((uint32_t)0x00FF0000)
#define SD_24TO31BITS ((uint32_t)0xFF000000)
#define SD_MAX_DATA_LENGTH ((uint32_t)0x01FFFFFF)
#define SD_HALFFIFO ((uint32_t)0x00000008)
#define SD_HALFFIFOBYTES ((uint32_t)0x00000020)
/**
* @brief Command Class Supported
*/
#define SD_CCCC_LOCK_UNLOCK ((uint32_t)0x00000080)
#define SD_CCCC_WRITE_PROT ((uint32_t)0x00000040)
#define SD_CCCC_ERASE ((uint32_t)0x00000020)
/**
* @brief Following commands are SD Card Specific commands.
* SDIO_APP_CMD should be sent before sending these commands.
*/
#define SDIO_SEND_IF_COND ((uint32_t)0x00000008)
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Variables
* @{
*/
static uint32_t CardType = SDIO_STD_CAPACITY_SD_CARD_V1_1;
static uint32_t CSD_Tab[4], CID_Tab[4], RCA = 0;
static uint32_t DeviceMode = SD_POLLING_MODE;
static uint32_t TotalNumberOfBytes = 0, StopCondition = 0;
uint32_t *SrcBuffer, *DestBuffer;
__IO SD_Error TransferError = SD_OK;
__IO uint32_t TransferEnd = 0;
__IO uint32_t NumberOfBytes = 0;
SDIO_InitTypeDef SDIO_InitStructure;
SDIO_CmdInitTypeDef SDIO_CmdInitStructure;
SDIO_DataInitTypeDef SDIO_DataInitStructure;
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Function_Prototypes
* @{
*/
static SD_Error CmdError(void);
static SD_Error CmdResp1Error(uint8_t cmd);
static SD_Error CmdResp7Error(void);
static SD_Error CmdResp3Error(void);
static SD_Error CmdResp2Error(void);
static SD_Error CmdResp6Error(uint8_t cmd, uint16_t *prca);
static SD_Error SDEnWideBus(FunctionalState NewState);
static SD_Error IsCardProgramming(uint8_t *pstatus);
static SD_Error FindSCR(uint16_t rca, uint32_t *pscr);
static uint8_t convert_from_bytes_to_power_of_two(uint16_t NumberOfBytes);
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Private_Functions
* @{
*/
/**
* @brief DeInitializes the SDIO interface.
* @param None
* @retval None
*/
void SD_DeInit(void)
{
SD_LowLevel_DeInit();
}
/**
* @brief Initializes the SD Card and put it into StandBy State (Ready for data
* transfer).
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_Init(void)
{
SD_Error errorstatus = SD_OK;
SD_CardInfo sdcardinfo;
/* SDIO Peripheral Low Level Init */
SD_LowLevel_Init();
SDIO_DeInit();
errorstatus = SD_PowerON();
if (errorstatus != SD_OK)
{
/*!< CMD Response TimeOut (wait for CMDSENT flag) */
return(errorstatus);
}
errorstatus = SD_InitializeCards();
if (errorstatus != SD_OK)
{
/*!< CMD Response TimeOut (wait for CMDSENT flag) */
return(errorstatus);
}
/*!< Configure the SDIO peripheral */
/*!< SDIOCLK = HCLK, SDIO_CK = HCLK/(2 + SDIO_TRANSFER_CLK_DIV) */
SDIO_InitStructure.SDIO_ClockDiv = SDIO_TRANSFER_CLK_DIV;
SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
SDIO_Init(&SDIO_InitStructure);
if (errorstatus == SD_OK)
{
/*----------------- Read CSD/CID MSD registers ------------------*/
errorstatus = SD_GetCardInfo(&sdcardinfo);
}
if (errorstatus == SD_OK)
{
/*----------------- Select Card --------------------------------*/
errorstatus = SD_SelectDeselect((uint32_t) (sdcardinfo.RCA << 16));
}
if (errorstatus == SD_OK)
{
errorstatus = SD_EnableWideBusOperation(SDIO_BusWide_4b);
}
/* Set Device Transfer Mode to DMA */
if (errorstatus == SD_OK)
{
errorstatus = SD_SetDeviceMode(SD_DMA_MODE);
}
return(errorstatus);
}
/**
* @brief Gets the cuurent sd card data transfer status.
* @param None
* @retval SDTransferState: Data Transfer state.
* This value can be:
* - SD_TRANSFER_OK: No data transfer is acting
* - SD_TRANSFER_BUSY: Data transfer is acting
*/
SDTransferState SD_GetStatus(void)
{
SDCardState cardstate = SD_CARD_TRANSFER;
cardstate = SD_GetState();
if (cardstate == SD_CARD_TRANSFER)
{
return(SD_TRANSFER_OK);
}
else if(cardstate == SD_CARD_ERROR)
{
return (SD_TRANSFER_ERROR);
}
else
{
return(SD_TRANSFER_BUSY);
}
}
/**
* @brief Returns the current card's state.
* @param None
* @retval SDCardState: SD Card Error or SD Card Current State.
*/
SDCardState SD_GetState(void)
{
uint32_t resp1 = 0;
if(SD_Detect()== SD_PRESENT)
{
if (SD_SendStatus(&resp1) != SD_OK)
{
return SD_CARD_ERROR;
}
else
{
return (SDCardState)((resp1 >> 9) & 0x0F);
}
}
else
{
return SD_CARD_ERROR;
}
}
/**
* @brief Detect if SD card is correctly plugged in the memory slot.
* @param None
* @retval Return if SD is detected or not
*/
uint8_t SD_Detect(void)
{
__IO uint8_t status = SD_PRESENT;
/*!< Check GPIO to detect SD */
if (GPIO_ReadInputDataBit(SD_DETECT_GPIO_PORT, SD_DETECT_PIN) != Bit_RESET)
{
status = SD_NOT_PRESENT;
}
return status;
}
/**
* @brief Enquires cards about their operating voltage and configures
* clock controls.
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_PowerON(void)
{
SD_Error errorstatus = SD_OK;
uint32_t response = 0, count = 0;
bool validvoltage = FALSE;
uint32_t SDType = SD_STD_CAPACITY;
/*!< Power ON Sequence -----------------------------------------------------*/
/*!< Configure the SDIO peripheral */
/*!< SDIOCLK = HCLK, SDIO_CK = HCLK/(2 + SDIO_INIT_CLK_DIV) */
/*!< SDIO_CK for initialization should not exceed 400 KHz */
SDIO_InitStructure.SDIO_ClockDiv = SDIO_INIT_CLK_DIV;
SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
SDIO_Init(&SDIO_InitStructure);
/*!< Set Power State to ON */
SDIO_SetPowerState(SDIO_PowerState_ON);
/*!< Enable SDIO Clock */
SDIO_ClockCmd(ENABLE);
/*!< CMD0: GO_IDLE_STATE ---------------------------------------------------*/
/*!< No CMD response required */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_GO_IDLE_STATE;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_No;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdError();
if (errorstatus != SD_OK)
{
/*!< CMD Response TimeOut (wait for CMDSENT flag) */
return(errorstatus);
}
/*!< CMD8: SEND_IF_COND ----------------------------------------------------*/
/*!< Send CMD8 to verify SD card interface operating condition */
/*!< Argument: - [31:12]: Reserved (shall be set to '0')
- [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
- [7:0]: Check Pattern (recommended 0xAA) */
/*!< CMD Response: R7 */
SDIO_CmdInitStructure.SDIO_Argument = SD_CHECK_PATTERN;
SDIO_CmdInitStructure.SDIO_CmdIndex = SDIO_SEND_IF_COND;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp7Error();
if (errorstatus == SD_OK)
{
CardType = SDIO_STD_CAPACITY_SD_CARD_V2_0; /*!< SD Card 2.0 */
SDType = SD_HIGH_CAPACITY;
}
else
{
/*!< CMD55 */
SDIO_CmdInitStructure.SDIO_Argument = 0x00;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
}
/*!< CMD55 */
SDIO_CmdInitStructure.SDIO_Argument = 0x00;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
/*!< If errorstatus is Command TimeOut, it is a MMC card */
/*!< If errorstatus is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch)
or SD card 1.x */
if (errorstatus == SD_OK)
{
/*!< SD CARD */
/*!< Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
while ((!validvoltage) && (count < SD_MAX_VOLT_TRIAL))
{
/*!< SEND CMD55 APP_CMD with RCA as 0 */
SDIO_CmdInitStructure.SDIO_Argument = 0x00;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
SDIO_CmdInitStructure.SDIO_Argument = SD_VOLTAGE_WINDOW_SD | SDType;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_APP_OP_COND;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp3Error();
if (errorstatus != SD_OK)
{
return(errorstatus);
}
response = SDIO_GetResponse(SDIO_RESP1);
validvoltage = (bool) (((response >> 31) == 1) ? 1 : 0);
count++;
}
if (count >= SD_MAX_VOLT_TRIAL)
{
errorstatus = SD_INVALID_VOLTRANGE;
return(errorstatus);
}
if (response &= SD_HIGH_CAPACITY)
{
CardType = SDIO_HIGH_CAPACITY_SD_CARD;
}
}/*!< else MMC Card */
return(errorstatus);
}
/**
* @brief Turns the SDIO output signals off.
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_PowerOFF(void)
{
SD_Error errorstatus = SD_OK;
/*!< Set Power State to OFF */
SDIO_SetPowerState(SDIO_PowerState_OFF);
return(errorstatus);
}
/**
* @brief Intialises all cards or single card as the case may be Card(s) come
* into standby state.
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_InitializeCards(void)
{
SD_Error errorstatus = SD_OK;
uint16_t rca = 0x01;
if (SDIO_GetPowerState() == SDIO_PowerState_OFF)
{
errorstatus = SD_REQUEST_NOT_APPLICABLE;
return(errorstatus);
}
if (SDIO_SECURE_DIGITAL_IO_CARD != CardType)
{
/*!< Send CMD2 ALL_SEND_CID */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_ALL_SEND_CID;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Long;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp2Error();
if (SD_OK != errorstatus)
{
return(errorstatus);
}
CID_Tab[0] = SDIO_GetResponse(SDIO_RESP1);
CID_Tab[1] = SDIO_GetResponse(SDIO_RESP2);
CID_Tab[2] = SDIO_GetResponse(SDIO_RESP3);
CID_Tab[3] = SDIO_GetResponse(SDIO_RESP4);
}
if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) || (SDIO_SECURE_DIGITAL_IO_COMBO_CARD == CardType)
|| (SDIO_HIGH_CAPACITY_SD_CARD == CardType))
{
/*!< Send CMD3 SET_REL_ADDR with argument 0 */
/*!< SD Card publishes its RCA. */
SDIO_CmdInitStructure.SDIO_Argument = 0x00;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_REL_ADDR;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp6Error(SD_CMD_SET_REL_ADDR, &rca);
if (SD_OK != errorstatus)
{
return(errorstatus);
}
}
if (SDIO_SECURE_DIGITAL_IO_CARD != CardType)
{
RCA = rca;
/*!< Send CMD9 SEND_CSD with argument as card's RCA */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)(rca << 16);
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_CSD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Long;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp2Error();
if (SD_OK != errorstatus)
{
return(errorstatus);
}
CSD_Tab[0] = SDIO_GetResponse(SDIO_RESP1);
CSD_Tab[1] = SDIO_GetResponse(SDIO_RESP2);
CSD_Tab[2] = SDIO_GetResponse(SDIO_RESP3);
CSD_Tab[3] = SDIO_GetResponse(SDIO_RESP4);
}
errorstatus = SD_OK; /*!< All cards get intialized */
return(errorstatus);
}
/**
* @brief Returns information about specific card.
* @param cardinfo: pointer to a SD_CardInfo structure that contains all SD card
* information.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo)
{
SD_Error errorstatus = SD_OK;
uint8_t tmp = 0;
cardinfo->CardType = (uint8_t)CardType;
cardinfo->RCA = (uint16_t)RCA;
/*!< Byte 0 */
tmp = (uint8_t)((CSD_Tab[0] & 0xFF000000) >> 24);
cardinfo->SD_csd.CSDStruct = (tmp & 0xC0) >> 6;
cardinfo->SD_csd.SysSpecVersion = (tmp & 0x3C) >> 2;
cardinfo->SD_csd.Reserved1 = tmp & 0x03;
/*!< Byte 1 */
tmp = (uint8_t)((CSD_Tab[0] & 0x00FF0000) >> 16);
cardinfo->SD_csd.TAAC = tmp;
/*!< Byte 2 */
tmp = (uint8_t)((CSD_Tab[0] & 0x0000FF00) >> 8);
cardinfo->SD_csd.NSAC = tmp;
/*!< Byte 3 */
tmp = (uint8_t)(CSD_Tab[0] & 0x000000FF);
cardinfo->SD_csd.MaxBusClkFrec = tmp;
/*!< Byte 4 */
tmp = (uint8_t)((CSD_Tab[1] & 0xFF000000) >> 24);
cardinfo->SD_csd.CardComdClasses = tmp << 4;
/*!< Byte 5 */
tmp = (uint8_t)((CSD_Tab[1] & 0x00FF0000) >> 16);
cardinfo->SD_csd.CardComdClasses |= (tmp & 0xF0) >> 4;
cardinfo->SD_csd.RdBlockLen = tmp & 0x0F;
/*!< Byte 6 */
tmp = (uint8_t)((CSD_Tab[1] & 0x0000FF00) >> 8);
cardinfo->SD_csd.PartBlockRead = (tmp & 0x80) >> 7;
cardinfo->SD_csd.WrBlockMisalign = (tmp & 0x40) >> 6;
cardinfo->SD_csd.RdBlockMisalign = (tmp & 0x20) >> 5;
cardinfo->SD_csd.DSRImpl = (tmp & 0x10) >> 4;
cardinfo->SD_csd.Reserved2 = 0; /*!< Reserved */
if ((CardType == SDIO_STD_CAPACITY_SD_CARD_V1_1) || (CardType == SDIO_STD_CAPACITY_SD_CARD_V2_0))
{
cardinfo->SD_csd.DeviceSize = (tmp & 0x03) << 10;
/*!< Byte 7 */
tmp = (uint8_t)(CSD_Tab[1] & 0x000000FF);
cardinfo->SD_csd.DeviceSize |= (tmp) << 2;
/*!< Byte 8 */
tmp = (uint8_t)((CSD_Tab[2] & 0xFF000000) >> 24);
cardinfo->SD_csd.DeviceSize |= (tmp & 0xC0) >> 6;
cardinfo->SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38) >> 3;
cardinfo->SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07);
/*!< Byte 9 */
tmp = (uint8_t)((CSD_Tab[2] & 0x00FF0000) >> 16);
cardinfo->SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0) >> 5;
cardinfo->SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1C) >> 2;
cardinfo->SD_csd.DeviceSizeMul = (tmp & 0x03) << 1;
/*!< Byte 10 */
tmp = (uint8_t)((CSD_Tab[2] & 0x0000FF00) >> 8);
cardinfo->SD_csd.DeviceSizeMul |= (tmp & 0x80) >> 7;
cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) ;
cardinfo->CardCapacity *= (1 << (cardinfo->SD_csd.DeviceSizeMul + 2));
cardinfo->CardBlockSize = 1 << (cardinfo->SD_csd.RdBlockLen);
cardinfo->CardCapacity *= cardinfo->CardBlockSize;
}
else if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
/*!< Byte 7 */
tmp = (uint8_t)(CSD_Tab[1] & 0x000000FF);
cardinfo->SD_csd.DeviceSize = (tmp & 0x3F) << 16;
/*!< Byte 8 */
tmp = (uint8_t)((CSD_Tab[2] & 0xFF000000) >> 24);
cardinfo->SD_csd.DeviceSize |= (tmp << 8);
/*!< Byte 9 */
tmp = (uint8_t)((CSD_Tab[2] & 0x00FF0000) >> 16);
cardinfo->SD_csd.DeviceSize |= (tmp);
/*!< Byte 10 */
tmp = (uint8_t)((CSD_Tab[2] & 0x0000FF00) >> 8);
cardinfo->CardCapacity = (cardinfo->SD_csd.DeviceSize + 1) * 512 * 1024;
cardinfo->CardBlockSize = 512;
}
cardinfo->SD_csd.EraseGrSize = (tmp & 0x40) >> 6;
cardinfo->SD_csd.EraseGrMul = (tmp & 0x3F) << 1;
/*!< Byte 11 */
tmp = (uint8_t)(CSD_Tab[2] & 0x000000FF);
cardinfo->SD_csd.EraseGrMul |= (tmp & 0x80) >> 7;
cardinfo->SD_csd.WrProtectGrSize = (tmp & 0x7F);
/*!< Byte 12 */
tmp = (uint8_t)((CSD_Tab[3] & 0xFF000000) >> 24);
cardinfo->SD_csd.WrProtectGrEnable = (tmp & 0x80) >> 7;
cardinfo->SD_csd.ManDeflECC = (tmp & 0x60) >> 5;
cardinfo->SD_csd.WrSpeedFact = (tmp & 0x1C) >> 2;
cardinfo->SD_csd.MaxWrBlockLen = (tmp & 0x03) << 2;
/*!< Byte 13 */
tmp = (uint8_t)((CSD_Tab[3] & 0x00FF0000) >> 16);
cardinfo->SD_csd.MaxWrBlockLen |= (tmp & 0xC0) >> 6;
cardinfo->SD_csd.WriteBlockPaPartial = (tmp & 0x20) >> 5;
cardinfo->SD_csd.Reserved3 = 0;
cardinfo->SD_csd.ContentProtectAppli = (tmp & 0x01);
/*!< Byte 14 */
tmp = (uint8_t)((CSD_Tab[3] & 0x0000FF00) >> 8);
cardinfo->SD_csd.FileFormatGrouop = (tmp & 0x80) >> 7;
cardinfo->SD_csd.CopyFlag = (tmp & 0x40) >> 6;
cardinfo->SD_csd.PermWrProtect = (tmp & 0x20) >> 5;
cardinfo->SD_csd.TempWrProtect = (tmp & 0x10) >> 4;
cardinfo->SD_csd.FileFormat = (tmp & 0x0C) >> 2;
cardinfo->SD_csd.ECC = (tmp & 0x03);
/*!< Byte 15 */
tmp = (uint8_t)(CSD_Tab[3] & 0x000000FF);
cardinfo->SD_csd.CSD_CRC = (tmp & 0xFE) >> 1;
cardinfo->SD_csd.Reserved4 = 1;
/*!< Byte 0 */
tmp = (uint8_t)((CID_Tab[0] & 0xFF000000) >> 24);
cardinfo->SD_cid.ManufacturerID = tmp;
/*!< Byte 1 */
tmp = (uint8_t)((CID_Tab[0] & 0x00FF0000) >> 16);
cardinfo->SD_cid.OEM_AppliID = tmp << 8;
/*!< Byte 2 */
tmp = (uint8_t)((CID_Tab[0] & 0x000000FF00) >> 8);
cardinfo->SD_cid.OEM_AppliID |= tmp;
/*!< Byte 3 */
tmp = (uint8_t)(CID_Tab[0] & 0x000000FF);
cardinfo->SD_cid.ProdName1 = tmp << 24;
/*!< Byte 4 */
tmp = (uint8_t)((CID_Tab[1] & 0xFF000000) >> 24);
cardinfo->SD_cid.ProdName1 |= tmp << 16;
/*!< Byte 5 */
tmp = (uint8_t)((CID_Tab[1] & 0x00FF0000) >> 16);
cardinfo->SD_cid.ProdName1 |= tmp << 8;
/*!< Byte 6 */
tmp = (uint8_t)((CID_Tab[1] & 0x0000FF00) >> 8);
cardinfo->SD_cid.ProdName1 |= tmp;
/*!< Byte 7 */
tmp = (uint8_t)(CID_Tab[1] & 0x000000FF);
cardinfo->SD_cid.ProdName2 = tmp;
/*!< Byte 8 */
tmp = (uint8_t)((CID_Tab[2] & 0xFF000000) >> 24);
cardinfo->SD_cid.ProdRev = tmp;
/*!< Byte 9 */
tmp = (uint8_t)((CID_Tab[2] & 0x00FF0000) >> 16);
cardinfo->SD_cid.ProdSN = tmp << 24;
/*!< Byte 10 */
tmp = (uint8_t)((CID_Tab[2] & 0x0000FF00) >> 8);
cardinfo->SD_cid.ProdSN |= tmp << 16;
/*!< Byte 11 */
tmp = (uint8_t)(CID_Tab[2] & 0x000000FF);
cardinfo->SD_cid.ProdSN |= tmp << 8;
/*!< Byte 12 */
tmp = (uint8_t)((CID_Tab[3] & 0xFF000000) >> 24);
cardinfo->SD_cid.ProdSN |= tmp;
/*!< Byte 13 */
tmp = (uint8_t)((CID_Tab[3] & 0x00FF0000) >> 16);
cardinfo->SD_cid.Reserved1 |= (tmp & 0xF0) >> 4;
cardinfo->SD_cid.ManufactDate = (tmp & 0x0F) << 8;
/*!< Byte 14 */
tmp = (uint8_t)((CID_Tab[3] & 0x0000FF00) >> 8);
cardinfo->SD_cid.ManufactDate |= tmp;
/*!< Byte 15 */
tmp = (uint8_t)(CID_Tab[3] & 0x000000FF);
cardinfo->SD_cid.CID_CRC = (tmp & 0xFE) >> 1;
cardinfo->SD_cid.Reserved2 = 1;
return(errorstatus);
}
/**
* @brief Enables wide bus opeartion for the requeseted card if supported by
* card.
* @param WideMode: Specifies the SD card wide bus mode.
* This parameter can be one of the following values:
* @arg SDIO_BusWide_8b: 8-bit data transfer (Only for MMC)
* @arg SDIO_BusWide_4b: 4-bit data transfer
* @arg SDIO_BusWide_1b: 1-bit data transfer
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_EnableWideBusOperation(uint32_t WideMode)
{
SD_Error errorstatus = SD_OK;
/*!< MMC Card doesn't support this feature */
if (SDIO_MULTIMEDIA_CARD == CardType)
{
errorstatus = SD_UNSUPPORTED_FEATURE;
return(errorstatus);
}
else if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) || (SDIO_HIGH_CAPACITY_SD_CARD == CardType))
{
if (SDIO_BusWide_8b == WideMode)
{
errorstatus = SD_UNSUPPORTED_FEATURE;
return(errorstatus);
}
else if (SDIO_BusWide_4b == WideMode)
{
errorstatus = SDEnWideBus(ENABLE);
if (SD_OK == errorstatus)
{
/*!< Configure the SDIO peripheral */
SDIO_InitStructure.SDIO_ClockDiv = SDIO_TRANSFER_CLK_DIV;
SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_4b;
#ifdef USE_STM3210E_EVAL
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
#else
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Enable;
#endif
SDIO_Init(&SDIO_InitStructure);
}
}
else
{
errorstatus = SDEnWideBus(DISABLE);
if (SD_OK == errorstatus)
{
/*!< Configure the SDIO peripheral */
SDIO_InitStructure.SDIO_ClockDiv = SDIO_TRANSFER_CLK_DIV;
SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;
#ifdef USE_STM3210E_EVAL
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
#else
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Enable;
#endif
SDIO_Init(&SDIO_InitStructure);
}
}
}
return(errorstatus);
}
/**
* @brief Sets device mode whether to operate in Polling, Interrupt or DMA mode.
* @param Mode: Specifies the Data Transfer mode.
* This parameter can be one of the following values:
* @arg SD_DMA_MODE: Data transfer using DMA.
* @arg SD_INTERRUPT_MODE: Data transfer using interrupts.
* @arg SD_POLLING_MODE: Data transfer using flags.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_SetDeviceMode(uint32_t Mode)
{
SD_Error errorstatus = SD_OK;
if ((Mode == SD_DMA_MODE) || (Mode == SD_INTERRUPT_MODE) || (Mode == SD_POLLING_MODE))
{
DeviceMode = Mode;
}
else
{
errorstatus = SD_INVALID_PARAMETER;
}
return(errorstatus);
}
/**
* @brief Selects od Deselects the corresponding card.
* @param addr: Address of the Card to be selected.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_SelectDeselect(uint32_t addr)
{
SD_Error errorstatus = SD_OK;
/*!< Send CMD7 SDIO_SEL_DESEL_CARD */
SDIO_CmdInitStructure.SDIO_Argument = addr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEL_DESEL_CARD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SEL_DESEL_CARD);
return(errorstatus);
}
/**
* @brief Allows to read one block from a specified address in a card.
* @param readbuff: pointer to the buffer that will contain the received data
* @param ReadAddr: Address from where data are to be read.
* @param BlockSize: the SD card Data block size.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_ReadBlock(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize)
{
SD_Error errorstatus = SD_OK;
uint32_t count = 0, *tempbuff = (uint32_t *)readbuff;
uint8_t power = 0;
if (NULL == readbuff)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
TransferError = SD_OK;
TransferEnd = 0;
TotalNumberOfBytes = 0;
/*!< Clear all DPSM configuration */
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 0;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_1b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Disable;
SDIO_DataConfig(&SDIO_DataInitStructure);
SDIO_DMACmd(DISABLE);
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
BlockSize = 512;
ReadAddr /= 512;
}
if ((BlockSize > 0) && (BlockSize <= 2048) && ((BlockSize & (BlockSize - 1)) == 0))
{
power = convert_from_bytes_to_power_of_two(BlockSize);
/*!< Set Block Size for Card */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) BlockSize;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (SD_OK != errorstatus)
{
return(errorstatus);
}
}
else
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = BlockSize;
SDIO_DataInitStructure.SDIO_DataBlockSize = (uint32_t) power << 4;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToSDIO;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
TotalNumberOfBytes = BlockSize;
StopCondition = 0;
DestBuffer = (uint32_t *)readbuff;
/*!< Send CMD17 READ_SINGLE_BLOCK */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)ReadAddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_READ_SINGLE_BLOCK;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_READ_SINGLE_BLOCK);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< In case of single block transfer, no need of stop transfer at all.*/
if (DeviceMode == SD_POLLING_MODE)
{
/*!< Polling mode */
while (!(SDIO->STA &(SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_RXFIFOHF) != RESET)
{
for (count = 0; count < 8; count++)
{
*(tempbuff + count) = SDIO_ReadData();
}
tempbuff += 8;
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_RXOVERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_RXOVERR);
errorstatus = SD_RX_OVERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
while (SDIO_GetFlagStatus(SDIO_FLAG_RXDAVL) != RESET)
{
*tempbuff = SDIO_ReadData();
tempbuff++;
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
}
else if (DeviceMode == SD_INTERRUPT_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_RXOVERR | SDIO_IT_RXFIFOHF | SDIO_IT_STBITERR, ENABLE);
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
else if (DeviceMode == SD_DMA_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_RXOVERR | SDIO_IT_STBITERR, ENABLE);
SDIO_DMACmd(ENABLE);
SD_LowLevel_DMA_RxConfig((uint32_t *)readbuff, BlockSize);
SD_WaitForDMAEndOfTransfer();
}
return(errorstatus);
}
/**
* @brief Allows to read blocks from a specified address in a card.
* @param readbuff: pointer to the buffer that will contain the received data.
* @param ReadAddr: Address from where data are to be read.
* @param BlockSize: the SD card Data block size.
* @param NumberOfBlocks: number of blocks to be read.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_ReadMultiBlocks(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
{
SD_Error errorstatus = SD_OK;
uint32_t count = 0, *tempbuff = (uint32_t *)readbuff;
uint8_t power = 0;
if (NULL == readbuff)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
TransferError = SD_OK;
TransferEnd = 0;
TotalNumberOfBytes = 0;
/*!< Clear all DPSM configuration */
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 0;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_1b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Disable;
SDIO_DataConfig(&SDIO_DataInitStructure);
SDIO_DMACmd(DISABLE);
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
BlockSize = 512;
ReadAddr /= 512;
}
if ((BlockSize > 0) && (BlockSize <= 2048) && (0 == (BlockSize & (BlockSize - 1))))
{
power = convert_from_bytes_to_power_of_two(BlockSize);
/*!< Set Block Size for Card */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) BlockSize;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (SD_OK != errorstatus)
{
return(errorstatus);
}
}
else
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
if (NumberOfBlocks > 1)
{
/*!< Common to all modes */
if (NumberOfBlocks * BlockSize > SD_MAX_DATA_LENGTH)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
TotalNumberOfBytes = NumberOfBlocks * BlockSize;
StopCondition = 1;
DestBuffer = (uint32_t *)readbuff;
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = NumberOfBlocks * BlockSize;
SDIO_DataInitStructure.SDIO_DataBlockSize = (uint32_t) power << 4;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToSDIO;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
/*!< Send CMD18 READ_MULT_BLOCK with argument data address */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)ReadAddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_READ_MULT_BLOCK;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_READ_MULT_BLOCK);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
if (DeviceMode == SD_POLLING_MODE)
{
/*!< Polling mode */
while (!(SDIO->STA &(SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DATAEND | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_RXFIFOHF) != RESET)
{
for (count = 0; count < SD_HALFFIFO; count++)
{
*(tempbuff + count) = SDIO_ReadData();
}
tempbuff += SD_HALFFIFO;
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_RXOVERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_RXOVERR);
errorstatus = SD_RX_OVERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
while (SDIO_GetFlagStatus(SDIO_FLAG_RXDAVL) != RESET)
{
*tempbuff = SDIO_ReadData();
tempbuff++;
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DATAEND) != RESET)
{
/*!< In Case Of SD-CARD Send Command STOP_TRANSMISSION */
if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_HIGH_CAPACITY_SD_CARD == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType))
{
/*!< Send CMD12 STOP_TRANSMISSION */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_STOP_TRANSMISSION;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_STOP_TRANSMISSION);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
}
else if (DeviceMode == SD_INTERRUPT_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_RXOVERR | SDIO_IT_RXFIFOHF | SDIO_IT_STBITERR, ENABLE);
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
else if (DeviceMode == SD_DMA_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_RXOVERR | SDIO_IT_STBITERR, ENABLE);
SDIO_DMACmd(ENABLE);
SD_LowLevel_DMA_RxConfig((uint32_t *)readbuff, (NumberOfBlocks * BlockSize));
SD_WaitForDMAEndOfTransfer();
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
}
return(errorstatus);
}
/**
* @brief Allows to write one block starting from a specified address in a card.
* @param writebuff: pointer to the buffer that contain the data to be transferred.
* @param WriteAddr: Address from where data are to be read.
* @param BlockSize: the SD card Data block size.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_WriteBlock(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize)
{
SD_Error errorstatus = SD_OK;
uint8_t power = 0, cardstate = 0;
uint32_t timeout = 0, bytestransferred = 0;
uint32_t cardstatus = 0, count = 0, restwords = 0;
uint32_t *tempbuff = (uint32_t *)writebuff;
if (writebuff == NULL)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
TransferError = SD_OK;
TransferEnd = 0;
TotalNumberOfBytes = 0;
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 0;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_1b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Disable;
SDIO_DataConfig(&SDIO_DataInitStructure);
SDIO_DMACmd(DISABLE);
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
BlockSize = 512;
WriteAddr /= 512;
}
/*!< Set the block size, both on controller and card */
if ((BlockSize > 0) && (BlockSize <= 2048) && ((BlockSize & (BlockSize - 1)) == 0))
{
power = convert_from_bytes_to_power_of_two(BlockSize);
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) BlockSize;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
else
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
/*!< Wait till card is ready for data Added */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) (RCA << 16);
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_STATUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SEND_STATUS);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
cardstatus = SDIO_GetResponse(SDIO_RESP1);
timeout = SD_DATATIMEOUT;
while (((cardstatus & 0x00000100) == 0) && (timeout > 0))
{
timeout--;
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) (RCA << 16);
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_STATUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SEND_STATUS);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
cardstatus = SDIO_GetResponse(SDIO_RESP1);
}
if (timeout == 0)
{
return(SD_ERROR);
}
/*!< Send CMD24 WRITE_SINGLE_BLOCK */
SDIO_CmdInitStructure.SDIO_Argument = WriteAddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_WRITE_SINGLE_BLOCK);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
TotalNumberOfBytes = BlockSize;
StopCondition = 0;
SrcBuffer = (uint32_t *)writebuff;
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = BlockSize;
SDIO_DataInitStructure.SDIO_DataBlockSize = (uint32_t) power << 4;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
/*!< In case of single data block transfer no need of stop command at all */
if (DeviceMode == SD_POLLING_MODE)
{
while (!(SDIO->STA & (SDIO_FLAG_DBCKEND | SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_TXFIFOHE) != RESET)
{
if ((TotalNumberOfBytes - bytestransferred) < 32)
{
restwords = ((TotalNumberOfBytes - bytestransferred) % 4 == 0) ? ((TotalNumberOfBytes - bytestransferred) / 4) : (( TotalNumberOfBytes - bytestransferred) / 4 + 1);
for (count = 0; count < restwords; count++, tempbuff++, bytestransferred += 4)
{
SDIO_WriteData(*tempbuff);
}
}
else
{
for (count = 0; count < 8; count++)
{
SDIO_WriteData(*(tempbuff + count));
}
tempbuff += 8;
bytestransferred += 32;
}
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_TXUNDERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_TXUNDERR);
errorstatus = SD_TX_UNDERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
}
else if (DeviceMode == SD_INTERRUPT_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR, ENABLE);
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
else if (DeviceMode == SD_DMA_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR, ENABLE);
SD_LowLevel_DMA_TxConfig((uint32_t *)writebuff, BlockSize);
SDIO_DMACmd(ENABLE);
SD_WaitForDMAEndOfTransfer();
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
/*!< Wait till the card is in programming state */
errorstatus = IsCardProgramming(&cardstate);
while ((errorstatus == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
{
errorstatus = IsCardProgramming(&cardstate);
}
return(errorstatus);
}
/**
* @brief Allows to write blocks starting from a specified address in a card.
* @param WriteAddr: Address from where data are to be read.
* @param writebuff: pointer to the buffer that contain the data to be transferred.
* @param BlockSize: the SD card Data block size.
* @param NumberOfBlocks: number of blocks to be written.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_WriteMultiBlocks(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks)
{
SD_Error errorstatus = SD_OK;
uint8_t power = 0, cardstate = 0;
uint32_t bytestransferred = 0;
uint32_t count = 0, restwords = 0;
uint32_t *tempbuff = (uint32_t *)writebuff;
if (writebuff == NULL)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
TransferError = SD_OK;
TransferEnd = 0;
TotalNumberOfBytes = 0;
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 0;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_1b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Disable;
SDIO_DataConfig(&SDIO_DataInitStructure);
SDIO_DMACmd(DISABLE);
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
BlockSize = 512;
WriteAddr /= 512;
}
/*!< Set the block size, both on controller and card */
if ((BlockSize > 0) && (BlockSize <= 2048) && ((BlockSize & (BlockSize - 1)) == 0))
{
power = convert_from_bytes_to_power_of_two(BlockSize);
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) BlockSize;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
else
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
/*!< Wait till card is ready for data Added */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) (RCA << 16);
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_STATUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SEND_STATUS);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
if (NumberOfBlocks > 1)
{
/*!< Common to all modes */
if (NumberOfBlocks * BlockSize > SD_MAX_DATA_LENGTH)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) || (SDIO_HIGH_CAPACITY_SD_CARD == CardType))
{
/*!< To improve performance */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) (RCA << 16);
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< To improve performance */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)NumberOfBlocks;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCK_COUNT;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCK_COUNT);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
/*!< Send CMD25 WRITE_MULT_BLOCK with argument data address */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)WriteAddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_WRITE_MULT_BLOCK;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_WRITE_MULT_BLOCK);
if (SD_OK != errorstatus)
{
return(errorstatus);
}
TotalNumberOfBytes = NumberOfBlocks * BlockSize;
StopCondition = 1;
SrcBuffer = (uint32_t *)writebuff;
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = NumberOfBlocks * BlockSize;
SDIO_DataInitStructure.SDIO_DataBlockSize = (uint32_t) power << 4;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToCard;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
if (DeviceMode == SD_POLLING_MODE)
{
while (!(SDIO->STA & (SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DATAEND | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_TXFIFOHE) != RESET)
{
if (!((TotalNumberOfBytes - bytestransferred) < SD_HALFFIFOBYTES))
{
for (count = 0; count < SD_HALFFIFO; count++)
{
SDIO_WriteData(*(tempbuff + count));
}
tempbuff += SD_HALFFIFO;
bytestransferred += SD_HALFFIFOBYTES;
}
else
{
restwords = ((TotalNumberOfBytes - bytestransferred) % 4 == 0) ? ((TotalNumberOfBytes - bytestransferred) / 4) :
((TotalNumberOfBytes - bytestransferred) / 4 + 1);
for (count = 0; count < restwords; count++, tempbuff++, bytestransferred += 4)
{
SDIO_WriteData(*tempbuff);
}
}
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_TXUNDERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_TXUNDERR);
errorstatus = SD_TX_UNDERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DATAEND) != RESET)
{
if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) || (SDIO_HIGH_CAPACITY_SD_CARD == CardType))
{
/*!< Send CMD12 STOP_TRANSMISSION */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_STOP_TRANSMISSION;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_STOP_TRANSMISSION);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
}
}
else if (DeviceMode == SD_INTERRUPT_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_TXFIFOHE | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR, ENABLE);
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
else if (DeviceMode == SD_DMA_MODE)
{
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR, ENABLE);
SDIO_DMACmd(ENABLE);
SD_LowLevel_DMA_TxConfig((uint32_t *)writebuff, (NumberOfBlocks * BlockSize));
SD_WaitForDMAEndOfTransfer();
while ((TransferEnd == 0) && (TransferError == SD_OK))
{}
if (TransferError != SD_OK)
{
return(TransferError);
}
}
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
/*!< Wait till the card is in programming state */
errorstatus = IsCardProgramming(&cardstate);
while ((errorstatus == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
{
errorstatus = IsCardProgramming(&cardstate);
}
return(errorstatus);
}
/**
* @brief Gets the cuurent data transfer state.
* @param None
* @retval SDTransferState: Data Transfer state.
* This value can be:
* - SD_TRANSFER_OK: No data transfer is acting
* - SD_TRANSFER_BUSY: Data transfer is acting
*/
SDTransferState SD_GetTransferState(void)
{
if (SDIO->STA & (SDIO_FLAG_TXACT | SDIO_FLAG_RXACT))
{
return(SD_TRANSFER_BUSY);
}
else
{
return(SD_TRANSFER_OK);
}
}
/**
* @brief Aborts an ongoing data transfer.
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_StopTransfer(void)
{
SD_Error errorstatus = SD_OK;
/*!< Send CMD12 STOP_TRANSMISSION */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_STOP_TRANSMISSION;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_STOP_TRANSMISSION);
return(errorstatus);
}
/**
* @brief Allows to erase memory area specified for the given card.
* @param startaddr: the start address.
* @param endaddr: the end address.
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_Erase(uint32_t startaddr, uint32_t endaddr)
{
SD_Error errorstatus = SD_OK;
uint32_t delay = 0;
__IO uint32_t maxdelay = 0;
uint8_t cardstate = 0;
/*!< Check if the card coomnd class supports erase command */
if (((CSD_Tab[1] >> 20) & SD_CCCC_ERASE) == 0)
{
errorstatus = SD_REQUEST_NOT_APPLICABLE;
return(errorstatus);
}
maxdelay = 120000 / ((SDIO->CLKCR & 0xFF) + 2);
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
if (CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
startaddr /= 512;
endaddr /= 512;
}
/*!< According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
if ((SDIO_STD_CAPACITY_SD_CARD_V1_1 == CardType) || (SDIO_STD_CAPACITY_SD_CARD_V2_0 == CardType) || (SDIO_HIGH_CAPACITY_SD_CARD == CardType))
{
/*!< Send CMD32 SD_ERASE_GRP_START with argument as addr */
SDIO_CmdInitStructure.SDIO_Argument = startaddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_ERASE_GRP_START;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SD_ERASE_GRP_START);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< Send CMD33 SD_ERASE_GRP_END with argument as addr */
SDIO_CmdInitStructure.SDIO_Argument = endaddr;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_ERASE_GRP_END;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SD_ERASE_GRP_END);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
}
/*!< Send CMD38 ERASE */
SDIO_CmdInitStructure.SDIO_Argument = 0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_ERASE;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_ERASE);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
for (delay = 0; delay < maxdelay; delay++)
{}
/*!< Wait till the card is in programming state */
errorstatus = IsCardProgramming(&cardstate);
while ((errorstatus == SD_OK) && ((SD_CARD_PROGRAMMING == cardstate) || (SD_CARD_RECEIVING == cardstate)))
{
errorstatus = IsCardProgramming(&cardstate);
}
return(errorstatus);
}
/**
* @brief Returns the current card's status.
* @param pcardstatus: pointer to the buffer that will contain the SD card
* status (Card Status register).
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_SendStatus(uint32_t *pcardstatus)
{
SD_Error errorstatus = SD_OK;
if (pcardstatus == NULL)
{
errorstatus = SD_INVALID_PARAMETER;
return(errorstatus);
}
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_STATUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SEND_STATUS);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
*pcardstatus = SDIO_GetResponse(SDIO_RESP1);
return(errorstatus);
}
/**
* @brief Returns the current SD card's status.
* @param psdstatus: pointer to the buffer that will contain the SD card status
* (SD Status register).
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_SendSDStatus(uint32_t *psdstatus)
{
SD_Error errorstatus = SD_OK;
uint32_t count = 0;
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
/*!< Set block size for card if it is not equal to current block size for card. */
SDIO_CmdInitStructure.SDIO_Argument = 64;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< CMD55 */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 64;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_64b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToSDIO;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
/*!< Send ACMD13 SD_APP_STAUS with argument as card's RCA.*/
SDIO_CmdInitStructure.SDIO_Argument = 0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_APP_STAUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SD_APP_STAUS);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
while (!(SDIO->STA &(SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_RXFIFOHF) != RESET)
{
for (count = 0; count < 8; count++)
{
*(psdstatus + count) = SDIO_ReadData();
}
psdstatus += 8;
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_RXOVERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_RXOVERR);
errorstatus = SD_RX_OVERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
while (SDIO_GetFlagStatus(SDIO_FLAG_RXDAVL) != RESET)
{
*psdstatus = SDIO_ReadData();
psdstatus++;
}
/*!< Clear all the static status flags*/
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
psdstatus -= 16;
for (count = 0; count < 16; count++)
{
psdstatus[count] = ((psdstatus[count] & SD_0TO7BITS) << 24) |((psdstatus[count] & SD_8TO15BITS) << 8) |
((psdstatus[count] & SD_16TO23BITS) >> 8) |((psdstatus[count] & SD_24TO31BITS) >> 24);
}
return(errorstatus);
}
/**
* @brief Allows to process all the interrupts that are high.
* @param None
* @retval SD_Error: SD Card Error code.
*/
SD_Error SD_ProcessIRQSrc(void)
{
uint32_t count = 0, restwords = 0;
if (DeviceMode == SD_INTERRUPT_MODE)
{
if (SDIO_GetITStatus(SDIO_IT_RXFIFOHF) != RESET)
{
for (count = 0; count < SD_HALFFIFO; count++)
{
*(DestBuffer + count) = SDIO_ReadData();
}
DestBuffer += SD_HALFFIFO;
NumberOfBytes += SD_HALFFIFOBYTES;
}
else if (SDIO_GetITStatus(SDIO_IT_TXFIFOHE) != RESET)
{
if ((TotalNumberOfBytes - NumberOfBytes) < SD_HALFFIFOBYTES)
{
restwords = ((TotalNumberOfBytes - NumberOfBytes) % 4 == 0) ?
((TotalNumberOfBytes - NumberOfBytes) / 4) :
((TotalNumberOfBytes - NumberOfBytes) / 4 + 1);
for (count = 0; count < restwords; count++, SrcBuffer++, NumberOfBytes += 4)
{
SDIO_WriteData(*SrcBuffer);
}
}
else
{
for (count = 0; count < SD_HALFFIFO; count++)
{
SDIO_WriteData(*(SrcBuffer + count));
}
SrcBuffer += SD_HALFFIFO;
NumberOfBytes += SD_HALFFIFOBYTES;
}
}
}
if (SDIO_GetITStatus(SDIO_IT_DATAEND) != RESET)
{
if (DeviceMode != SD_DMA_MODE)
{
while ((SDIO_GetFlagStatus(SDIO_FLAG_RXDAVL) != RESET) && (NumberOfBytes < TotalNumberOfBytes))
{
*DestBuffer = SDIO_ReadData();
DestBuffer++;
NumberOfBytes += 4;
}
}
if (StopCondition == 1)
{
TransferError = SD_StopTransfer();
}
else
{
TransferError = SD_OK;
}
SDIO_ClearITPendingBit(SDIO_IT_DATAEND);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
TransferEnd = 1;
NumberOfBytes = 0;
return(TransferError);
}
if (SDIO_GetITStatus(SDIO_IT_DCRCFAIL) != RESET)
{
SDIO_ClearITPendingBit(SDIO_IT_DCRCFAIL);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
NumberOfBytes = 0;
TransferError = SD_DATA_CRC_FAIL;
return(SD_DATA_CRC_FAIL);
}
if (SDIO_GetITStatus(SDIO_IT_DTIMEOUT) != RESET)
{
SDIO_ClearITPendingBit(SDIO_IT_DTIMEOUT);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
NumberOfBytes = 0;
TransferError = SD_DATA_TIMEOUT;
return(SD_DATA_TIMEOUT);
}
if (SDIO_GetITStatus(SDIO_IT_RXOVERR) != RESET)
{
SDIO_ClearITPendingBit(SDIO_IT_RXOVERR);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
NumberOfBytes = 0;
TransferError = SD_RX_OVERRUN;
return(SD_RX_OVERRUN);
}
if (SDIO_GetITStatus(SDIO_IT_TXUNDERR) != RESET)
{
SDIO_ClearITPendingBit(SDIO_IT_TXUNDERR);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
NumberOfBytes = 0;
TransferError = SD_TX_UNDERRUN;
return(SD_TX_UNDERRUN);
}
if (SDIO_GetITStatus(SDIO_IT_STBITERR) != RESET)
{
SDIO_ClearITPendingBit(SDIO_IT_STBITERR);
SDIO_ITConfig(SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |
SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |
SDIO_IT_RXOVERR | SDIO_IT_STBITERR, DISABLE);
NumberOfBytes = 0;
TransferError = SD_START_BIT_ERR;
return(SD_START_BIT_ERR);
}
return(SD_OK);
}
/**
* @brief Checks for error conditions for CMD0.
* @param None
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdError(void)
{
SD_Error errorstatus = SD_OK;
uint32_t timeout;
timeout = SDIO_CMD0TIMEOUT; /*!< 10000 */
while ((timeout > 0) && (SDIO_GetFlagStatus(SDIO_FLAG_CMDSENT) == RESET))
{
timeout--;
}
if (timeout == 0)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
return(errorstatus);
}
/**
* @brief Checks for error conditions for R7 response.
* @param None
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdResp7Error(void)
{
SD_Error errorstatus = SD_OK;
uint32_t status;
uint32_t timeout = SDIO_CMD0TIMEOUT;
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) && (timeout > 0))
{
timeout--;
status = SDIO->STA;
}
if ((timeout == 0) || (status & SDIO_FLAG_CTIMEOUT))
{
/*!< Card is not V2.0 complient or card does not support the set voltage range */
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
if (status & SDIO_FLAG_CMDREND)
{
/*!< Card is SD V2.0 compliant */
errorstatus = SD_OK;
SDIO_ClearFlag(SDIO_FLAG_CMDREND);
return(errorstatus);
}
return(errorstatus);
}
/**
* @brief Checks for error conditions for R1 response.
* @param cmd: The sent command index.
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdResp1Error(uint8_t cmd)
{
SD_Error errorstatus = SD_OK;
uint32_t status;
uint32_t response_r1;
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)))
{
status = SDIO->STA;
}
if (status & SDIO_FLAG_CTIMEOUT)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
else if (status & SDIO_FLAG_CCRCFAIL)
{
errorstatus = SD_CMD_CRC_FAIL;
SDIO_ClearFlag(SDIO_FLAG_CCRCFAIL);
return(errorstatus);
}
/*!< Check response received is of desired command */
if (SDIO_GetCommandResponse() != cmd)
{
errorstatus = SD_ILLEGAL_CMD;
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
/*!< We have received response, retrieve it for analysis */
response_r1 = SDIO_GetResponse(SDIO_RESP1);
if ((response_r1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
{
return(errorstatus);
}
if (response_r1 & SD_OCR_ADDR_OUT_OF_RANGE)
{
return(SD_ADDR_OUT_OF_RANGE);
}
if (response_r1 & SD_OCR_ADDR_MISALIGNED)
{
return(SD_ADDR_MISALIGNED);
}
if (response_r1 & SD_OCR_BLOCK_LEN_ERR)
{
return(SD_BLOCK_LEN_ERR);
}
if (response_r1 & SD_OCR_ERASE_SEQ_ERR)
{
return(SD_ERASE_SEQ_ERR);
}
if (response_r1 & SD_OCR_BAD_ERASE_PARAM)
{
return(SD_BAD_ERASE_PARAM);
}
if (response_r1 & SD_OCR_WRITE_PROT_VIOLATION)
{
return(SD_WRITE_PROT_VIOLATION);
}
if (response_r1 & SD_OCR_LOCK_UNLOCK_FAILED)
{
return(SD_LOCK_UNLOCK_FAILED);
}
if (response_r1 & SD_OCR_COM_CRC_FAILED)
{
return(SD_COM_CRC_FAILED);
}
if (response_r1 & SD_OCR_ILLEGAL_CMD)
{
return(SD_ILLEGAL_CMD);
}
if (response_r1 & SD_OCR_CARD_ECC_FAILED)
{
return(SD_CARD_ECC_FAILED);
}
if (response_r1 & SD_OCR_CC_ERROR)
{
return(SD_CC_ERROR);
}
if (response_r1 & SD_OCR_GENERAL_UNKNOWN_ERROR)
{
return(SD_GENERAL_UNKNOWN_ERROR);
}
if (response_r1 & SD_OCR_STREAM_READ_UNDERRUN)
{
return(SD_STREAM_READ_UNDERRUN);
}
if (response_r1 & SD_OCR_STREAM_WRITE_OVERRUN)
{
return(SD_STREAM_WRITE_OVERRUN);
}
if (response_r1 & SD_OCR_CID_CSD_OVERWRIETE)
{
return(SD_CID_CSD_OVERWRITE);
}
if (response_r1 & SD_OCR_WP_ERASE_SKIP)
{
return(SD_WP_ERASE_SKIP);
}
if (response_r1 & SD_OCR_CARD_ECC_DISABLED)
{
return(SD_CARD_ECC_DISABLED);
}
if (response_r1 & SD_OCR_ERASE_RESET)
{
return(SD_ERASE_RESET);
}
if (response_r1 & SD_OCR_AKE_SEQ_ERROR)
{
return(SD_AKE_SEQ_ERROR);
}
return(errorstatus);
}
/**
* @brief Checks for error conditions for R3 (OCR) response.
* @param None
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdResp3Error(void)
{
SD_Error errorstatus = SD_OK;
uint32_t status;
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)))
{
status = SDIO->STA;
}
if (status & SDIO_FLAG_CTIMEOUT)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
return(errorstatus);
}
/**
* @brief Checks for error conditions for R2 (CID or CSD) response.
* @param None
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdResp2Error(void)
{
SD_Error errorstatus = SD_OK;
uint32_t status;
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CTIMEOUT | SDIO_FLAG_CMDREND)))
{
status = SDIO->STA;
}
if (status & SDIO_FLAG_CTIMEOUT)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
else if (status & SDIO_FLAG_CCRCFAIL)
{
errorstatus = SD_CMD_CRC_FAIL;
SDIO_ClearFlag(SDIO_FLAG_CCRCFAIL);
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
return(errorstatus);
}
/**
* @brief Checks for error conditions for R6 (RCA) response.
* @param cmd: The sent command index.
* @param prca: pointer to the variable that will contain the SD card relative
* address RCA.
* @retval SD_Error: SD Card Error code.
*/
static SD_Error CmdResp6Error(uint8_t cmd, uint16_t *prca)
{
SD_Error errorstatus = SD_OK;
uint32_t status;
uint32_t response_r1;
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CTIMEOUT | SDIO_FLAG_CMDREND)))
{
status = SDIO->STA;
}
if (status & SDIO_FLAG_CTIMEOUT)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
else if (status & SDIO_FLAG_CCRCFAIL)
{
errorstatus = SD_CMD_CRC_FAIL;
SDIO_ClearFlag(SDIO_FLAG_CCRCFAIL);
return(errorstatus);
}
/*!< Check response received is of desired command */
if (SDIO_GetCommandResponse() != cmd)
{
errorstatus = SD_ILLEGAL_CMD;
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
/*!< We have received response, retrieve it. */
response_r1 = SDIO_GetResponse(SDIO_RESP1);
if (SD_ALLZERO == (response_r1 & (SD_R6_GENERAL_UNKNOWN_ERROR | SD_R6_ILLEGAL_CMD | SD_R6_COM_CRC_FAILED)))
{
*prca = (uint16_t) (response_r1 >> 16);
return(errorstatus);
}
if (response_r1 & SD_R6_GENERAL_UNKNOWN_ERROR)
{
return(SD_GENERAL_UNKNOWN_ERROR);
}
if (response_r1 & SD_R6_ILLEGAL_CMD)
{
return(SD_ILLEGAL_CMD);
}
if (response_r1 & SD_R6_COM_CRC_FAILED)
{
return(SD_COM_CRC_FAILED);
}
return(errorstatus);
}
/**
* @brief Enables or disables the SDIO wide bus mode.
* @param NewState: new state of the SDIO wide bus mode.
* This parameter can be: ENABLE or DISABLE.
* @retval SD_Error: SD Card Error code.
*/
static SD_Error SDEnWideBus(FunctionalState NewState)
{
SD_Error errorstatus = SD_OK;
uint32_t scr[2] = {0, 0};
if (SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED)
{
errorstatus = SD_LOCK_UNLOCK_FAILED;
return(errorstatus);
}
/*!< Get SCR Register */
errorstatus = FindSCR(RCA, scr);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< If wide bus operation to be enabled */
if (NewState == ENABLE)
{
/*!< If requested card supports wide bus operation */
if ((scr[1] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO)
{
/*!< Send CMD55 APP_CMD with argument as card's RCA.*/
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
SDIO_CmdInitStructure.SDIO_Argument = 0x2;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_SD_SET_BUSWIDTH);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
return(errorstatus);
}
else
{
errorstatus = SD_REQUEST_NOT_APPLICABLE;
return(errorstatus);
}
} /*!< If wide bus operation to be disabled */
else
{
/*!< If requested card supports 1 bit mode operation */
if ((scr[1] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO)
{
/*!< Send CMD55 APP_CMD with argument as card's RCA.*/
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
SDIO_CmdInitStructure.SDIO_Argument = 0x00;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_SD_SET_BUSWIDTH);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
return(errorstatus);
}
else
{
errorstatus = SD_REQUEST_NOT_APPLICABLE;
return(errorstatus);
}
}
}
/**
* @brief Checks if the SD card is in programming state.
* @param pstatus: pointer to the variable that will contain the SD card state.
* @retval SD_Error: SD Card Error code.
*/
static SD_Error IsCardProgramming(uint8_t *pstatus)
{
SD_Error errorstatus = SD_OK;
__IO uint32_t respR1 = 0, status = 0;
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SEND_STATUS;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
status = SDIO->STA;
while (!(status & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)))
{
status = SDIO->STA;
}
if (status & SDIO_FLAG_CTIMEOUT)
{
errorstatus = SD_CMD_RSP_TIMEOUT;
SDIO_ClearFlag(SDIO_FLAG_CTIMEOUT);
return(errorstatus);
}
else if (status & SDIO_FLAG_CCRCFAIL)
{
errorstatus = SD_CMD_CRC_FAIL;
SDIO_ClearFlag(SDIO_FLAG_CCRCFAIL);
return(errorstatus);
}
status = (uint32_t)SDIO_GetCommandResponse();
/*!< Check response received is of desired command */
if (status != SD_CMD_SEND_STATUS)
{
errorstatus = SD_ILLEGAL_CMD;
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
/*!< We have received response, retrieve it for analysis */
respR1 = SDIO_GetResponse(SDIO_RESP1);
/*!< Find out card status */
*pstatus = (uint8_t) ((respR1 >> 9) & 0x0000000F);
if ((respR1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
{
return(errorstatus);
}
if (respR1 & SD_OCR_ADDR_OUT_OF_RANGE)
{
return(SD_ADDR_OUT_OF_RANGE);
}
if (respR1 & SD_OCR_ADDR_MISALIGNED)
{
return(SD_ADDR_MISALIGNED);
}
if (respR1 & SD_OCR_BLOCK_LEN_ERR)
{
return(SD_BLOCK_LEN_ERR);
}
if (respR1 & SD_OCR_ERASE_SEQ_ERR)
{
return(SD_ERASE_SEQ_ERR);
}
if (respR1 & SD_OCR_BAD_ERASE_PARAM)
{
return(SD_BAD_ERASE_PARAM);
}
if (respR1 & SD_OCR_WRITE_PROT_VIOLATION)
{
return(SD_WRITE_PROT_VIOLATION);
}
if (respR1 & SD_OCR_LOCK_UNLOCK_FAILED)
{
return(SD_LOCK_UNLOCK_FAILED);
}
if (respR1 & SD_OCR_COM_CRC_FAILED)
{
return(SD_COM_CRC_FAILED);
}
if (respR1 & SD_OCR_ILLEGAL_CMD)
{
return(SD_ILLEGAL_CMD);
}
if (respR1 & SD_OCR_CARD_ECC_FAILED)
{
return(SD_CARD_ECC_FAILED);
}
if (respR1 & SD_OCR_CC_ERROR)
{
return(SD_CC_ERROR);
}
if (respR1 & SD_OCR_GENERAL_UNKNOWN_ERROR)
{
return(SD_GENERAL_UNKNOWN_ERROR);
}
if (respR1 & SD_OCR_STREAM_READ_UNDERRUN)
{
return(SD_STREAM_READ_UNDERRUN);
}
if (respR1 & SD_OCR_STREAM_WRITE_OVERRUN)
{
return(SD_STREAM_WRITE_OVERRUN);
}
if (respR1 & SD_OCR_CID_CSD_OVERWRIETE)
{
return(SD_CID_CSD_OVERWRITE);
}
if (respR1 & SD_OCR_WP_ERASE_SKIP)
{
return(SD_WP_ERASE_SKIP);
}
if (respR1 & SD_OCR_CARD_ECC_DISABLED)
{
return(SD_CARD_ECC_DISABLED);
}
if (respR1 & SD_OCR_ERASE_RESET)
{
return(SD_ERASE_RESET);
}
if (respR1 & SD_OCR_AKE_SEQ_ERROR)
{
return(SD_AKE_SEQ_ERROR);
}
return(errorstatus);
}
/**
* @brief Find the SD card SCR register value.
* @param rca: selected card address.
* @param pscr: pointer to the buffer that will contain the SCR value.
* @retval SD_Error: SD Card Error code.
*/
static SD_Error FindSCR(uint16_t rca, uint32_t *pscr)
{
uint32_t index = 0;
SD_Error errorstatus = SD_OK;
uint32_t tempscr[2] = {0, 0};
/*!< Set Block Size To 8 Bytes */
/*!< Send CMD55 APP_CMD with argument as card's RCA */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t)8;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SET_BLOCKLEN;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SET_BLOCKLEN);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
/*!< Send CMD55 APP_CMD with argument as card's RCA */
SDIO_CmdInitStructure.SDIO_Argument = (uint32_t) RCA << 16;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_APP_CMD;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_APP_CMD);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
SDIO_DataInitStructure.SDIO_DataTimeOut = SD_DATATIMEOUT;
SDIO_DataInitStructure.SDIO_DataLength = 8;
SDIO_DataInitStructure.SDIO_DataBlockSize = SDIO_DataBlockSize_8b;
SDIO_DataInitStructure.SDIO_TransferDir = SDIO_TransferDir_ToSDIO;
SDIO_DataInitStructure.SDIO_TransferMode = SDIO_TransferMode_Block;
SDIO_DataInitStructure.SDIO_DPSM = SDIO_DPSM_Enable;
SDIO_DataConfig(&SDIO_DataInitStructure);
/*!< Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
SDIO_CmdInitStructure.SDIO_Argument = 0x0;
SDIO_CmdInitStructure.SDIO_CmdIndex = SD_CMD_SD_APP_SEND_SCR;
SDIO_CmdInitStructure.SDIO_Response = SDIO_Response_Short;
SDIO_CmdInitStructure.SDIO_Wait = SDIO_Wait_No;
SDIO_CmdInitStructure.SDIO_CPSM = SDIO_CPSM_Enable;
SDIO_SendCommand(&SDIO_CmdInitStructure);
errorstatus = CmdResp1Error(SD_CMD_SD_APP_SEND_SCR);
if (errorstatus != SD_OK)
{
return(errorstatus);
}
while (!(SDIO->STA & (SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)))
{
if (SDIO_GetFlagStatus(SDIO_FLAG_RXDAVL) != RESET)
{
*(tempscr + index) = SDIO_ReadData();
index++;
}
}
if (SDIO_GetFlagStatus(SDIO_FLAG_DTIMEOUT) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DTIMEOUT);
errorstatus = SD_DATA_TIMEOUT;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_DCRCFAIL) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_DCRCFAIL);
errorstatus = SD_DATA_CRC_FAIL;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_RXOVERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_RXOVERR);
errorstatus = SD_RX_OVERRUN;
return(errorstatus);
}
else if (SDIO_GetFlagStatus(SDIO_FLAG_STBITERR) != RESET)
{
SDIO_ClearFlag(SDIO_FLAG_STBITERR);
errorstatus = SD_START_BIT_ERR;
return(errorstatus);
}
/*!< Clear all the static flags */
SDIO_ClearFlag(SDIO_STATIC_FLAGS);
*(pscr + 1) = ((tempscr[0] & SD_0TO7BITS) << 24) | ((tempscr[0] & SD_8TO15BITS) << 8) | ((tempscr[0] & SD_16TO23BITS) >> 8) | ((tempscr[0] & SD_24TO31BITS) >> 24);
*(pscr) = ((tempscr[1] & SD_0TO7BITS) << 24) | ((tempscr[1] & SD_8TO15BITS) << 8) | ((tempscr[1] & SD_16TO23BITS) >> 8) | ((tempscr[1] & SD_24TO31BITS) >> 24);
return(errorstatus);
}
/**
* @brief Converts the number of bytes in power of two and returns the power.
* @param NumberOfBytes: number of bytes.
* @retval None
*/
static uint8_t convert_from_bytes_to_power_of_two(uint16_t NumberOfBytes)
{
uint8_t count = 0;
while (NumberOfBytes != 1)
{
NumberOfBytes >>= 1;
count++;
}
return(count);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_sdio_sd.c
|
C
|
asf20
| 91,705
|
/**
******************************************************************************
* @file stm32_eval_i2c_ee.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm32_eval_i2c_ee
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_I2C_EE_H
#define __STM32_EVAL_I2C_EE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_I2C_EE
* @{
*/
/** @defgroup STM32_EVAL_I2C_EE_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Exported_Constants
* @{
*/
#if !defined (sEE_M24C08) && !defined (sEE_M24C64_32)
/* Use the defines below the choose the EEPROM type */
/*#define sEE_M24C08*/ /* Support the device: M24C08. */
/* note: Could support: M24C01, M24C02, M24C04 and M24C16 if the blocks and
HW address are correctly defined*/
#define sEE_M24C64_32 /* Support the devices: M24C32 and M24C64 */
#endif
#ifdef sEE_M24C64_32
/* For M24C32 and M24C64 devices, E0,E1 and E2 pins are all used for device
address selection (ne need for additional address lines). According to the
Harware connection on the board (on STM3210C-EVAL board E0 = E1 = E2 = 0) */
#define sEE_HW_ADDRESS 0xA0 /* E0 = E1 = E2 = 0 */
#elif defined (sEE_M24C08)
/* The M24C08W contains 4 blocks (128byte each) with the adresses below: E2 = 0
EEPROM Addresses defines */
#define sEE_Block0_ADDRESS 0xA0 /* E2 = 0 */
/*#define sEE_Block1_ADDRESS 0xA2*/ /* E2 = 0 */
/*#define sEE_Block2_ADDRESS 0xA4*/ /* E2 = 0 */
/*#define sEE_Block3_ADDRESS 0xA6*/ /* E2 = 0 */
#endif /* sEE_M24C64_32 */
#define I2C_SPEED 200000
#define I2C_SLAVE_ADDRESS7 0xA0
#if defined (sEE_M24C08)
#define sEE_PAGESIZE 16
#elif defined (sEE_M24C64_32)
#define sEE_PAGESIZE 32
#endif
/* Defintions for the state of the DMA transfer */
#define sEE_STATE_READY 0
#define sEE_STATE_BUSY 1
/* Maximum timeout value for counting before exiting waiting loop on DMA
Trasnfer Complete. This value depends directly on the maximum page size and
the sytem clock frequency. */
#define sEE_TIMEOUT_MAX 0x10000;
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_I2C_EE_Exported_Functions
* @{
*/
void sEE_DeInit(void);
void sEE_Init(void);
void sEE_WriteByte(uint8_t* pBuffer, uint16_t WriteAddr);
void sEE_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint8_t* NumByteToWrite);
void sEE_WriteBuffer(uint8_t* pBuffer, uint16_t WriteAddr, uint16_t NumByteToWrite);
void sEE_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint16_t* NumByteToRead);
void sEE_WaitEepromStandbyState(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_I2C_EE_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_i2c_ee.h
|
C
|
asf20
| 4,090
|
/**
******************************************************************************
* @file stm32_eval_sdio_sd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the SD Card
* stm32_eval_sdio_sd driver firmware library.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_SDIO_SD_H
#define __STM32_EVAL_SDIO_SD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup Common
* @{
*/
/** @addtogroup STM32_EVAL_SDIO_SD
* @{
*/
/** @defgroup STM32_EVAL_SDIO_SD_Exported_Types
* @{
*/
typedef enum
{
/**
* @brief SDIO specific error defines
*/
SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */
SD_DATA_CRC_FAIL = (2), /*!< Data bock sent/received (CRC check Failed) */
SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */
SD_DATA_TIMEOUT = (4), /*!< Data time out */
SD_TX_UNDERRUN = (5), /*!< Transmit FIFO under-run */
SD_RX_OVERRUN = (6), /*!< Receive FIFO over-run */
SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in widE bus mode */
SD_CMD_OUT_OF_RANGE = (8), /*!< CMD's argument was out of range.*/
SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */
SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */
SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs.*/
SD_BAD_ERASE_PARAM = (12), /*!< An Invalid selection for erase groups */
SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */
SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */
SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */
SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */
SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */
SD_CC_ERROR = (18), /*!< Internal card controller error */
SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or Unknown error */
SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */
SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */
SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */
SD_WP_ERASE_SKIP = (23), /*!< only partial address space was erased */
SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */
SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */
SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */
SD_INVALID_VOLTRANGE = (27),
SD_ADDR_OUT_OF_RANGE = (28),
SD_SWITCH_ERROR = (29),
SD_SDIO_DISABLED = (30),
SD_SDIO_FUNCTION_BUSY = (31),
SD_SDIO_FUNCTION_FAILED = (32),
SD_SDIO_UNKNOWN_FUNCTION = (33),
/**
* @brief Standard error defines
*/
SD_INTERNAL_ERROR,
SD_NOT_CONFIGURED,
SD_REQUEST_PENDING,
SD_REQUEST_NOT_APPLICABLE,
SD_INVALID_PARAMETER,
SD_UNSUPPORTED_FEATURE,
SD_UNSUPPORTED_HW,
SD_ERROR,
SD_OK
} SD_Error;
/**
* @brief SDIO Transfer state
*/
typedef enum
{
SD_TRANSFER_OK = 0,
SD_TRANSFER_BUSY = 1,
SD_TRANSFER_ERROR
} SDTransferState;
/**
* @brief SD Card States
*/
typedef enum
{
SD_CARD_READY = ((uint32_t)0x00000001),
SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002),
SD_CARD_STANDBY = ((uint32_t)0x00000003),
SD_CARD_TRANSFER = ((uint32_t)0x00000004),
SD_CARD_SENDING = ((uint32_t)0x00000005),
SD_CARD_RECEIVING = ((uint32_t)0x00000006),
SD_CARD_PROGRAMMING = ((uint32_t)0x00000007),
SD_CARD_DISCONNECTED = ((uint32_t)0x00000008),
SD_CARD_ERROR = ((uint32_t)0x000000FF)
}SDCardState;
/**
* @brief Card Specific Data: CSD Register
*/
typedef struct
{
__IO uint8_t CSDStruct; /*!< CSD structure */
__IO uint8_t SysSpecVersion; /*!< System specification version */
__IO uint8_t Reserved1; /*!< Reserved */
__IO uint8_t TAAC; /*!< Data read access-time 1 */
__IO uint8_t NSAC; /*!< Data read access-time 2 in CLK cycles */
__IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */
__IO uint16_t CardComdClasses; /*!< Card command classes */
__IO uint8_t RdBlockLen; /*!< Max. read data block length */
__IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */
__IO uint8_t WrBlockMisalign; /*!< Write block misalignment */
__IO uint8_t RdBlockMisalign; /*!< Read block misalignment */
__IO uint8_t DSRImpl; /*!< DSR implemented */
__IO uint8_t Reserved2; /*!< Reserved */
__IO uint32_t DeviceSize; /*!< Device Size */
__IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */
__IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */
__IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */
__IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */
__IO uint8_t DeviceSizeMul; /*!< Device size multiplier */
__IO uint8_t EraseGrSize; /*!< Erase group size */
__IO uint8_t EraseGrMul; /*!< Erase group size multiplier */
__IO uint8_t WrProtectGrSize; /*!< Write protect group size */
__IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */
__IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */
__IO uint8_t WrSpeedFact; /*!< Write speed factor */
__IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */
__IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */
__IO uint8_t Reserved3; /*!< Reserded */
__IO uint8_t ContentProtectAppli; /*!< Content protection application */
__IO uint8_t FileFormatGrouop; /*!< File format group */
__IO uint8_t CopyFlag; /*!< Copy flag (OTP) */
__IO uint8_t PermWrProtect; /*!< Permanent write protection */
__IO uint8_t TempWrProtect; /*!< Temporary write protection */
__IO uint8_t FileFormat; /*!< File Format */
__IO uint8_t ECC; /*!< ECC code */
__IO uint8_t CSD_CRC; /*!< CSD CRC */
__IO uint8_t Reserved4; /*!< always 1*/
} SD_CSD;
/**
* @brief Card Identification Data: CID Register
*/
typedef struct
{
__IO uint8_t ManufacturerID; /*!< ManufacturerID */
__IO uint16_t OEM_AppliID; /*!< OEM/Application ID */
__IO uint32_t ProdName1; /*!< Product Name part1 */
__IO uint8_t ProdName2; /*!< Product Name part2*/
__IO uint8_t ProdRev; /*!< Product Revision */
__IO uint32_t ProdSN; /*!< Product Serial Number */
__IO uint8_t Reserved1; /*!< Reserved1 */
__IO uint16_t ManufactDate; /*!< Manufacturing Date */
__IO uint8_t CID_CRC; /*!< CID CRC */
__IO uint8_t Reserved2; /*!< always 1 */
} SD_CID;
/**
* @brief SD Card information
*/
typedef struct
{
SD_CSD SD_csd;
SD_CID SD_cid;
uint32_t CardCapacity; /*!< Card Capacity */
uint32_t CardBlockSize; /*!< Card Block Size */
uint16_t RCA;
uint8_t CardType;
} SD_CardInfo;
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Exported_Constants
* @{
*/
/**
* @brief SDIO Commands Index
*/
#define SD_CMD_GO_IDLE_STATE ((uint8_t)0)
#define SD_CMD_SEND_OP_COND ((uint8_t)1)
#define SD_CMD_ALL_SEND_CID ((uint8_t)2)
#define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< SDIO_SEND_REL_ADDR for SD Card */
#define SD_CMD_SET_DSR ((uint8_t)4)
#define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5)
#define SD_CMD_HS_SWITCH ((uint8_t)6)
#define SD_CMD_SEL_DESEL_CARD ((uint8_t)7)
#define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8)
#define SD_CMD_SEND_CSD ((uint8_t)9)
#define SD_CMD_SEND_CID ((uint8_t)10)
#define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD Card doesn't support it */
#define SD_CMD_STOP_TRANSMISSION ((uint8_t)12)
#define SD_CMD_SEND_STATUS ((uint8_t)13)
#define SD_CMD_HS_BUSTEST_READ ((uint8_t)14)
#define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15)
#define SD_CMD_SET_BLOCKLEN ((uint8_t)16)
#define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17)
#define SD_CMD_READ_MULT_BLOCK ((uint8_t)18)
#define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19)
#define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< SD Card doesn't support it */
#define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< SD Card doesn't support it */
#define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24)
#define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25)
#define SD_CMD_PROG_CID ((uint8_t)26) /*!< reserved for manufacturers */
#define SD_CMD_PROG_CSD ((uint8_t)27)
#define SD_CMD_SET_WRITE_PROT ((uint8_t)28)
#define SD_CMD_CLR_WRITE_PROT ((uint8_t)29)
#define SD_CMD_SEND_WRITE_PROT ((uint8_t)30)
#define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< To set the address of the first write
block to be erased. (For SD card only) */
#define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< To set the address of the last write block of the
continuous range to be erased. (For SD card only) */
#define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< To set the address of the first write block to be erased.
(For MMC card only spec 3.31) */
#define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< To set the address of the last write block of the
continuous range to be erased. (For MMC card only spec 3.31) */
#define SD_CMD_ERASE ((uint8_t)38)
#define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD Card doesn't support it */
#define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD Card doesn't support it */
#define SD_CMD_LOCK_UNLOCK ((uint8_t)42)
#define SD_CMD_APP_CMD ((uint8_t)55)
#define SD_CMD_GEN_CMD ((uint8_t)56)
#define SD_CMD_NO_CMD ((uint8_t)64)
/**
* @brief Following commands are SD Card Specific commands.
* SDIO_APP_CMD should be sent before sending these commands.
*/
#define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< For SD Card only */
#define SD_CMD_SD_APP_STAUS ((uint8_t)13) /*!< For SD Card only */
#define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< For SD Card only */
#define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< For SD Card only */
#define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< For SD Card only */
#define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< For SD Card only */
#define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O Card only */
#define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O Card only */
/**
* @brief Following commands are SD Card Specific security commands.
* SDIO_APP_CMD should be sent before sending these commands.
*/
#define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD Card only */
#define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD Card only */
#define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD Card only */
#define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD Card only */
#define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD Card only */
#define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD Card only */
#define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD Card only */
#define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD Card only */
#define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD Card only */
#define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD Card only */
#define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD Card only */
#define SD_DMA_MODE ((uint32_t)0x00000000)
#define SD_INTERRUPT_MODE ((uint32_t)0x00000001)
#define SD_POLLING_MODE ((uint32_t)0x00000002)
/**
* @brief SD detection on its memory slot
*/
#define SD_PRESENT ((uint8_t)0x01)
#define SD_NOT_PRESENT ((uint8_t)0x00)
/**
* @brief Supported SD Memory Cards
*/
#define SDIO_STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000)
#define SDIO_STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001)
#define SDIO_HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002)
#define SDIO_MULTIMEDIA_CARD ((uint32_t)0x00000003)
#define SDIO_SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004)
#define SDIO_HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005)
#define SDIO_SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006)
#define SDIO_HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007)
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_SDIO_SD_Exported_Functions
* @{
*/
void SD_DeInit(void);
SD_Error SD_Init(void);
SDTransferState SD_GetStatus(void);
SDCardState SD_GetState(void);
uint8_t SD_Detect(void);
SD_Error SD_PowerON(void);
SD_Error SD_PowerOFF(void);
SD_Error SD_InitializeCards(void);
SD_Error SD_GetCardInfo(SD_CardInfo *cardinfo);
SD_Error SD_EnableWideBusOperation(uint32_t WideMode);
SD_Error SD_SetDeviceMode(uint32_t Mode);
SD_Error SD_SelectDeselect(uint32_t addr);
SD_Error SD_ReadBlock(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize);
SD_Error SD_ReadMultiBlocks(uint8_t *readbuff, uint32_t ReadAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
SD_Error SD_WriteBlock(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize);
SD_Error SD_WriteMultiBlocks(uint8_t *writebuff, uint32_t WriteAddr, uint16_t BlockSize, uint32_t NumberOfBlocks);
SDTransferState SD_GetTransferState(void);
SD_Error SD_StopTransfer(void);
SD_Error SD_Erase(uint32_t startaddr, uint32_t endaddr);
SD_Error SD_SendStatus(uint32_t *pcardstatus);
SD_Error SD_SendSDStatus(uint32_t *psdstatus);
SD_Error SD_ProcessIRQSrc(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_SDIO_SD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/Common/stm32_eval_sdio_sd.h
|
C
|
asf20
| 17,591
|
/**
******************************************************************************
* @file stm32_eval.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief Header file for stm32_eval.c module.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_EVAL_H
#define __STM32_EVAL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @defgroup STM32_EVAL_Abstraction_Layer
* @{
*/
/** @defgroup STM32_EVAL_HARDWARE_RESOURCES
* @{
*/
/**
@code
The table below gives an overview of the hardware resources supported by each
STM32 EVAL board.
- LCD: TFT Color LCD (Parallel (FSMC) and Serial (SPI))
- IOE: IO Expander on I2C
- sFLASH: serial SPI FLASH (M25Pxxx)
- sEE: serial I2C EEPROM (M24C08, M24C32, M24C64)
- TSENSOR: Temperature Sensor (LM75)
- SD: SD Card memory (SPI and SDIO (SD Card MODE))
=================================================================================================================+
STM32 EVAL | LED | Buttons | Com Ports | LCD | IOE | sFLASH | sEE | TSENSOR | SD (SPI) | SD(SDIO) |
=================================================================================================================+
STM3210B-EVAL | 4 | 8 | 2 | YES (SPI) | NO | YES | NO | YES | YES | NO |
-----------------------------------------------------------------------------------------------------------------+
STM3210E-EVAL | 4 | 8 | 2 | YES (FSMC)| NO | YES | NO | YES | NO | YES |
-----------------------------------------------------------------------------------------------------------------+
STM3210C-EVAL | 4 | 3 | 1 | YES (SPI) | YES | NO | YES | NO | YES | NO |
-----------------------------------------------------------------------------------------------------------------+
STM32100B-EVAL | 4 | 8 | 2 | YES (SPI) | NO | YES | NO | YES | YES | NO |
=================================================================================================================+
@endcode
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Exported_Types
* @{
*/
typedef enum
{
LED1 = 0,
LED2 = 1,
LED3 = 2,
LED4 = 3
} Led_TypeDef;
typedef enum
{
BUTTON_WAKEUP = 0,
BUTTON_TAMPER = 1,
BUTTON_KEY = 2,
BUTTON_RIGHT = 3,
BUTTON_LEFT = 4,
BUTTON_UP = 5,
BUTTON_DOWN = 6,
BUTTON_SEL = 7
} Button_TypeDef;
typedef enum
{
BUTTON_MODE_GPIO = 0,
BUTTON_MODE_EXTI = 1
} ButtonMode_TypeDef;
typedef enum
{
JOY_NONE = 0,
JOY_SEL = 1,
JOY_DOWN = 2,
JOY_LEFT = 3,
JOY_RIGHT = 4,
JOY_UP = 5
} JOYState_TypeDef
;
typedef enum
{
COM1 = 0,
COM2 = 1
} COM_TypeDef;
/**
* @}
*/
/** @defgroup STM32_EVAL_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line corresponding to the STMicroelectronics evaluation
* board used in your application.
*
* Tip: To avoid modifying this file each time you need to switch between these
* boards, you can define the board in your toolchain compiler preprocessor.
*/
#if !defined (USE_STM32100B_EVAL) && !defined (USE_STM3210B_EVAL) && !defined (USE_STM3210E_EVAL) && !defined (USE_STM3210C_EVAL)
//#define USE_STM32100B_EVAL
//#define USE_STM3210B_EVAL
//#define USE_STM3210E_EVAL
//#define USE_STM3210C_EVAL
#endif
#ifdef USE_STM32100B_EVAL
#include "stm32f10x.h"
#include "stm32100b_eval/stm32100b_eval.h"
#elif defined USE_STM3210B_EVAL
#include "stm32f10x.h"
#include "stm3210b_eval/stm3210b_eval.h"
#elif defined USE_STM3210E_EVAL
#include "stm32f10x.h"
#include "stm3210e_eval/stm3210e_eval.h"
#elif defined USE_STM3210C_EVAL
#include "stm32f10x.h"
#include "stm3210c_eval/stm3210c_eval.h"
#else
#error "Please select first the STM32 EVAL board to be used (in stm32_eval.h)"
#endif
/**
* @brief STM32 Button Defines Legacy
*/
#define Button_WAKEUP BUTTON_WAKEUP
#define Button_TAMPER BUTTON_TAMPER
#define Button_KEY BUTTON_KEY
#define Button_RIGHT BUTTON_RIGHT
#define Button_LEFT BUTTON_LEFT
#define Button_UP BUTTON_UP
#define Button_DOWN BUTTON_DOWN
#define Button_SEL BUTTON_SEL
#define Mode_GPIO BUTTON_MODE_GPIO
#define Mode_EXTI BUTTON_MODE_EXTI
#define Button_Mode_TypeDef ButtonMode_TypeDef
#define JOY_CENTER JOY_SEL
#define JOY_State_TypeDef JOYState_TypeDef
/**
* @brief LCD Defines Legacy
*/
#define LCD_RSNWR_GPIO_CLK LCD_NWR_GPIO_CLK
#define LCD_SPI_GPIO_PORT LCD_SPI_SCK_GPIO_PORT
#define LCD_SPI_GPIO_CLK LCD_SPI_SCK_GPIO_CLK
#define R0 LCD_REG_0
#define R1 LCD_REG_1
#define R2 LCD_REG_2
#define R3 LCD_REG_3
#define R4 LCD_REG_4
#define R5 LCD_REG_5
#define R6 LCD_REG_6
#define R7 LCD_REG_7
#define R8 LCD_REG_8
#define R9 LCD_REG_9
#define R10 LCD_REG_10
#define R12 LCD_REG_12
#define R13 LCD_REG_13
#define R14 LCD_REG_14
#define R15 LCD_REG_15
#define R16 LCD_REG_16
#define R17 LCD_REG_17
#define R18 LCD_REG_18
#define R19 LCD_REG_19
#define R20 LCD_REG_20
#define R21 LCD_REG_21
#define R22 LCD_REG_22
#define R23 LCD_REG_23
#define R24 LCD_REG_24
#define R25 LCD_REG_25
#define R26 LCD_REG_26
#define R27 LCD_REG_27
#define R28 LCD_REG_28
#define R29 LCD_REG_29
#define R30 LCD_REG_30
#define R31 LCD_REG_31
#define R32 LCD_REG_32
#define R33 LCD_REG_33
#define R34 LCD_REG_34
#define R36 LCD_REG_36
#define R37 LCD_REG_37
#define R40 LCD_REG_40
#define R41 LCD_REG_41
#define R43 LCD_REG_43
#define R45 LCD_REG_45
#define R48 LCD_REG_48
#define R49 LCD_REG_49
#define R50 LCD_REG_50
#define R51 LCD_REG_51
#define R52 LCD_REG_52
#define R53 LCD_REG_53
#define R54 LCD_REG_54
#define R55 LCD_REG_55
#define R56 LCD_REG_56
#define R57 LCD_REG_57
#define R59 LCD_REG_59
#define R60 LCD_REG_60
#define R61 LCD_REG_61
#define R62 LCD_REG_62
#define R63 LCD_REG_63
#define R64 LCD_REG_64
#define R65 LCD_REG_65
#define R66 LCD_REG_66
#define R67 LCD_REG_67
#define R68 LCD_REG_68
#define R69 LCD_REG_69
#define R70 LCD_REG_70
#define R71 LCD_REG_71
#define R72 LCD_REG_72
#define R73 LCD_REG_73
#define R74 LCD_REG_74
#define R75 LCD_REG_75
#define R76 LCD_REG_76
#define R77 LCD_REG_77
#define R78 LCD_REG_78
#define R79 LCD_REG_79
#define R80 LCD_REG_80
#define R81 LCD_REG_81
#define R82 LCD_REG_82
#define R83 LCD_REG_83
#define R96 LCD_REG_96
#define R97 LCD_REG_97
#define R106 LCD_REG_106
#define R118 LCD_REG_118
#define R128 LCD_REG_128
#define R129 LCD_REG_129
#define R130 LCD_REG_130
#define R131 LCD_REG_131
#define R132 LCD_REG_132
#define R133 LCD_REG_133
#define R134 LCD_REG_134
#define R135 LCD_REG_135
#define R136 LCD_REG_136
#define R137 LCD_REG_137
#define R139 LCD_REG_139
#define R140 LCD_REG_140
#define R141 LCD_REG_141
#define R143 LCD_REG_143
#define R144 LCD_REG_144
#define R145 LCD_REG_145
#define R146 LCD_REG_146
#define R147 LCD_REG_147
#define R148 LCD_REG_148
#define R149 LCD_REG_149
#define R150 LCD_REG_150
#define R151 LCD_REG_151
#define R152 LCD_REG_152
#define R153 LCD_REG_153
#define R154 LCD_REG_154
#define R157 LCD_REG_157
#define R192 LCD_REG_192
#define R193 LCD_REG_193
#define R227 LCD_REG_227
#define R229 LCD_REG_229
#define R231 LCD_REG_231
#define R239 LCD_REG_239
#define White LCD_COLOR_WHITE
#define Black LCD_COLOR_BLACK
#define Grey LCD_COLOR_GREY
#define Blue LCD_COLOR_BLUE
#define Blue2 LCD_COLOR_BLUE2
#define Red LCD_COLOR_RED
#define Magenta LCD_COLOR_MAGENTA
#define Green LCD_COLOR_GREEN
#define Cyan LCD_COLOR_CYAN
#define Yellow LCD_COLOR_YELLOW
#define Line0 LCD_LINE_0
#define Line1 LCD_LINE_1
#define Line2 LCD_LINE_2
#define Line3 LCD_LINE_3
#define Line4 LCD_LINE_4
#define Line5 LCD_LINE_5
#define Line6 LCD_LINE_6
#define Line7 LCD_LINE_7
#define Line8 LCD_LINE_8
#define Line9 LCD_LINE_9
#define Horizontal LCD_DIR_HORIZONTAL
#define Vertical LCD_DIR_VERTICAL
/**
* @}
*/
/** @defgroup STM32_EVAL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Exported_Functions
* @{
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32_EVAL_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/stm32_eval.h
|
C
|
asf20
| 11,584
|
/**
******************************************************************************
* @file stm32100b_eval_lcd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm32100b_eval_lcd
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32100B_EVAL_LCD_H
#define __STM32100B_EVAL_LCD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "../Common/fonts.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL_LCD
* @{
*/
/** @defgroup STM32100B_EVAL_LCD_Exported_Types
* @{
*/
typedef struct
{
int16_t X;
int16_t Y;
} Point, * pPoint;
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LCD_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line below if you want to use LCD_DrawBMP function to
* display a bitmap picture on the LCD. This function assumes that the bitmap
* file is loaded in the SPI Flash (mounted on STM32100B-EVAL board), however
* user can tailor it according to his application hardware requirement.
*/
/*#define USE_LCD_DrawBMP*/
/**
* @brief Uncomment the line below if you want to use user defined Delay function
* (for precise timing), otherwise default _delay_ function defined within
* this driver is used (less precise timing).
*/
/* #define USE_Delay */
#ifdef USE_Delay
#include "main.h"
#define _delay_ Delay /* !< User can provide more timing precise _delay_ function
(with 10ms time base), using SysTick for example */
#else
#define _delay_ delay /* !< Default _delay_ function with less precise timing */
#endif
/**
* @brief LCD Control pins
*/
#define LCD_NCS_PIN GPIO_Pin_2
#define LCD_NCS_GPIO_PORT GPIOB
#define LCD_NCS_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_NWR_PIN GPIO_Pin_15
#define LCD_NWR_GPIO_PORT GPIOD
#define LCD_NWR_GPIO_CLK RCC_APB2Periph_GPIOD
#define LCD_RS_PIN GPIO_Pin_7
#define LCD_RS_GPIO_PORT GPIOD
#define LCD_RS_GPIO_CLK RCC_APB2Periph_GPIOD
/**
* @brief LCD SPI Interface pins
*/
#define LCD_SPI SPI2
#define LCD_SPI_CLK RCC_APB1Periph_SPI2
#define LCD_SPI_SCK_PIN GPIO_Pin_13
#define LCD_SPI_SCK_GPIO_PORT GPIOB
#define LCD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_SPI_MISO_PIN GPIO_Pin_14
#define LCD_SPI_MISO_GPIO_PORT GPIOB
#define LCD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_SPI_MOSI_PIN GPIO_Pin_15
#define LCD_SPI_MOSI_GPIO_PORT GPIOB
#define LCD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @brief LCD Registers
*/
#define LCD_REG_0 0x00
#define LCD_REG_1 0x01
#define LCD_REG_2 0x02
#define LCD_REG_3 0x03
#define LCD_REG_4 0x04
#define LCD_REG_5 0x05
#define LCD_REG_6 0x06
#define LCD_REG_7 0x07
#define LCD_REG_8 0x08
#define LCD_REG_9 0x09
#define LCD_REG_10 0x0A
#define LCD_REG_12 0x0C
#define LCD_REG_13 0x0D
#define LCD_REG_14 0x0E
#define LCD_REG_15 0x0F
#define LCD_REG_16 0x10
#define LCD_REG_17 0x11
#define LCD_REG_18 0x12
#define LCD_REG_19 0x13
#define LCD_REG_20 0x14
#define LCD_REG_21 0x15
#define LCD_REG_22 0x16
#define LCD_REG_23 0x17
#define LCD_REG_24 0x18
#define LCD_REG_25 0x19
#define LCD_REG_26 0x1A
#define LCD_REG_27 0x1B
#define LCD_REG_28 0x1C
#define LCD_REG_29 0x1D
#define LCD_REG_30 0x1E
#define LCD_REG_31 0x1F
#define LCD_REG_32 0x20
#define LCD_REG_33 0x21
#define LCD_REG_34 0x22
#define LCD_REG_36 0x24
#define LCD_REG_37 0x25
#define LCD_REG_40 0x28
#define LCD_REG_41 0x29
#define LCD_REG_43 0x2B
#define LCD_REG_45 0x2D
#define LCD_REG_48 0x30
#define LCD_REG_49 0x31
#define LCD_REG_50 0x32
#define LCD_REG_51 0x33
#define LCD_REG_52 0x34
#define LCD_REG_53 0x35
#define LCD_REG_54 0x36
#define LCD_REG_55 0x37
#define LCD_REG_56 0x38
#define LCD_REG_57 0x39
#define LCD_REG_59 0x3B
#define LCD_REG_60 0x3C
#define LCD_REG_61 0x3D
#define LCD_REG_62 0x3E
#define LCD_REG_63 0x3F
#define LCD_REG_64 0x40
#define LCD_REG_65 0x41
#define LCD_REG_66 0x42
#define LCD_REG_67 0x43
#define LCD_REG_68 0x44
#define LCD_REG_69 0x45
#define LCD_REG_70 0x46
#define LCD_REG_71 0x47
#define LCD_REG_72 0x48
#define LCD_REG_73 0x49
#define LCD_REG_74 0x4A
#define LCD_REG_75 0x4B
#define LCD_REG_76 0x4C
#define LCD_REG_77 0x4D
#define LCD_REG_78 0x4E
#define LCD_REG_79 0x4F
#define LCD_REG_80 0x50
#define LCD_REG_81 0x51
#define LCD_REG_82 0x52
#define LCD_REG_83 0x53
#define LCD_REG_96 0x60
#define LCD_REG_97 0x61
#define LCD_REG_106 0x6A
#define LCD_REG_118 0x76
#define LCD_REG_128 0x80
#define LCD_REG_129 0x81
#define LCD_REG_130 0x82
#define LCD_REG_131 0x83
#define LCD_REG_132 0x84
#define LCD_REG_133 0x85
#define LCD_REG_134 0x86
#define LCD_REG_135 0x87
#define LCD_REG_136 0x88
#define LCD_REG_137 0x89
#define LCD_REG_139 0x8B
#define LCD_REG_140 0x8C
#define LCD_REG_141 0x8D
#define LCD_REG_143 0x8F
#define LCD_REG_144 0x90
#define LCD_REG_145 0x91
#define LCD_REG_146 0x92
#define LCD_REG_147 0x93
#define LCD_REG_148 0x94
#define LCD_REG_149 0x95
#define LCD_REG_150 0x96
#define LCD_REG_151 0x97
#define LCD_REG_152 0x98
#define LCD_REG_153 0x99
#define LCD_REG_154 0x9A
#define LCD_REG_157 0x9D
#define LCD_REG_192 0xC0
#define LCD_REG_193 0xC1
#define LCD_REG_227 0xE3
#define LCD_REG_229 0xE5
#define LCD_REG_231 0xE7
#define LCD_REG_239 0xEF
/**
* @brief LCD color
*/
#define LCD_COLOR_WHITE 0xFFFF
#define LCD_COLOR_BLACK 0x0000
#define LCD_COLOR_GREY 0xF7DE
#define LCD_COLOR_BLUE 0x001F
#define LCD_COLOR_BLUE2 0x051F
#define LCD_COLOR_RED 0xF800
#define LCD_COLOR_MAGENTA 0xF81F
#define LCD_COLOR_GREEN 0x07E0
#define LCD_COLOR_CYAN 0x7FFF
#define LCD_COLOR_YELLOW 0xFFE0
/**
* @brief LCD Lines depending on the chosen fonts.
*/
#define LCD_LINE_0 LINE(0)
#define LCD_LINE_1 LINE(1)
#define LCD_LINE_2 LINE(2)
#define LCD_LINE_3 LINE(3)
#define LCD_LINE_4 LINE(4)
#define LCD_LINE_5 LINE(5)
#define LCD_LINE_6 LINE(6)
#define LCD_LINE_7 LINE(7)
#define LCD_LINE_8 LINE(8)
#define LCD_LINE_9 LINE(9)
#define LCD_LINE_10 LINE(10)
#define LCD_LINE_11 LINE(11)
#define LCD_LINE_12 LINE(12)
#define LCD_LINE_13 LINE(13)
#define LCD_LINE_14 LINE(14)
#define LCD_LINE_15 LINE(15)
#define LCD_LINE_16 LINE(16)
#define LCD_LINE_17 LINE(17)
#define LCD_LINE_18 LINE(18)
#define LCD_LINE_19 LINE(19)
#define LCD_LINE_20 LINE(20)
#define LCD_LINE_21 LINE(21)
#define LCD_LINE_22 LINE(22)
#define LCD_LINE_23 LINE(23)
#define LCD_LINE_24 LINE(24)
#define LCD_LINE_25 LINE(25)
#define LCD_LINE_26 LINE(26)
#define LCD_LINE_27 LINE(27)
#define LCD_LINE_28 LINE(28)
#define LCD_LINE_29 LINE(29)
/**
* @brief LCD default font
*/
#define LCD_DEFAULT_FONT Font16x24
/**
* @brief LCD Direction
*/
#define LCD_DIR_HORIZONTAL 0x0000
#define LCD_DIR_VERTICAL 0x0001
/**
* @brief LCD Size (Width and Height)
*/
#define LCD_PIXEL_WIDTH 0x0140
#define LCD_PIXEL_HEIGHT 0x00F0
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LCD_Exported_Macros
* @{
*/
#define ASSEMBLE_RGB(R, G, B) ((((R)& 0xF8) << 8) | (((G) & 0xFC) << 3) | (((B) & 0xF8) >> 3))
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LCD_Exported_Functions
* @{
*/
void LCD_DeInit(void);
void LCD_Setup(void);
void STM32100B_LCD_Init(void);
void LCD_SetColors(__IO uint16_t _TextColor, __IO uint16_t _BackColor);
void LCD_GetColors(__IO uint16_t *_TextColor, __IO uint16_t *_BackColor);
void LCD_SetTextColor(__IO uint16_t Color);
void LCD_SetBackColor(__IO uint16_t Color);
void LCD_ClearLine(uint8_t Line);
void LCD_Clear(uint16_t Color);
void LCD_SetCursor(uint8_t Xpos, uint16_t Ypos);
void LCD_DrawChar(uint8_t Xpos, uint16_t Ypos, const uint16_t *c);
void LCD_DisplayChar(uint8_t Line, uint16_t Column, uint8_t Ascii);
void LCD_SetFont(sFONT *fonts);
sFONT *LCD_GetFont(void);
void LCD_DisplayStringLine(uint8_t Line, uint8_t *ptr);
void LCD_SetDisplayWindow(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_WindowModeDisable(void);
void LCD_DrawLine(uint8_t Xpos, uint16_t Ypos, uint16_t Length, uint8_t Direction);
void LCD_DrawRect(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_DrawCircle(uint8_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_DrawMonoPict(const uint32_t *Pict);
void LCD_DrawBMP(uint32_t BmpAddress);
void LCD_DrawUniLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
void LCD_DrawFullRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height);
void LCD_DrawFullCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_PolyLine(pPoint Points, uint16_t PointCount);
void LCD_PolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLine(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_FillPolyLine(pPoint Points, uint16_t PointCount);
void LCD_nCS_StartByte(uint8_t Start_Byte);
void LCD_WriteRegIndex(uint8_t LCD_Reg);
void LCD_WriteReg(uint8_t LCD_Reg, uint16_t LCD_RegValue);
void LCD_WriteRAM_Prepare(void);
void LCD_WriteRAMWord(uint16_t RGB_Code);
uint16_t LCD_ReadReg(uint8_t LCD_Reg);
void LCD_WriteRAM(uint16_t RGB_Code);
void LCD_PowerOn(void);
void LCD_DisplayOn(void);
void LCD_DisplayOff(void);
void LCD_CtrlLinesConfig(void);
void LCD_CtrlLinesWrite(GPIO_TypeDef* GPIOx, uint16_t CtrlPins, BitAction BitVal);
void LCD_SPIConfig(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32100B_EVAL_LCD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM32100B_EVAL/stm32100b_eval_lcd.h
|
C
|
asf20
| 12,907
|
/**
******************************************************************************
* @file stm32100b_eval.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains definitions for STM32100B_EVAL's Leds, push-buttons
* COM ports, SD Card on SPI, sFLASH on SPI and Temperature Sensor LM75 on I2C
* hardware resources.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32100B_EVAL_H
#define __STM32100B_EVAL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL
* @{
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Exported_Constants
* @{
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_LED
* @{
*/
#define LEDn 4
#define LED1_PIN GPIO_Pin_6
#define LED1_GPIO_PORT GPIOC
#define LED1_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED2_PIN GPIO_Pin_7
#define LED2_GPIO_PORT GPIOC
#define LED2_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED3_PIN GPIO_Pin_8
#define LED3_GPIO_PORT GPIOC
#define LED3_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED4_PIN GPIO_Pin_9
#define LED4_GPIO_PORT GPIOC
#define LED4_GPIO_CLK RCC_APB2Periph_GPIOC
/**
* @}
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_BUTTON
* @{
*/
#define BUTTONn 8
/**
* @brief Wakeup push-button
*/
#define WAKEUP_BUTTON_PIN GPIO_Pin_0
#define WAKEUP_BUTTON_GPIO_PORT GPIOA
#define WAKEUP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOA
#define WAKEUP_BUTTON_EXTI_LINE EXTI_Line0
#define WAKEUP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOA
#define WAKEUP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define WAKEUP_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Tamper push-button
*/
#define TAMPER_BUTTON_PIN GPIO_Pin_13
#define TAMPER_BUTTON_GPIO_PORT GPIOC
#define TAMPER_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOC
#define TAMPER_BUTTON_EXTI_LINE EXTI_Line13
#define TAMPER_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOC
#define TAMPER_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource13
#define TAMPER_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Key push-button
*/
#define KEY_BUTTON_PIN GPIO_Pin_9
#define KEY_BUTTON_GPIO_PORT GPIOB
#define KEY_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOB
#define KEY_BUTTON_EXTI_LINE EXTI_Line9
#define KEY_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOB
#define KEY_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource9
#define KEY_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @brief Joystick Right push-button
*/
#define RIGHT_BUTTON_PIN GPIO_Pin_1
#define RIGHT_BUTTON_GPIO_PORT GPIOE
#define RIGHT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOE
#define RIGHT_BUTTON_EXTI_LINE EXTI_Line1
#define RIGHT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOE
#define RIGHT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource1
#define RIGHT_BUTTON_EXTI_IRQn EXTI1_IRQn
/**
* @brief Joystick Left push-button
*/
#define LEFT_BUTTON_PIN GPIO_Pin_0
#define LEFT_BUTTON_GPIO_PORT GPIOE
#define LEFT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOE
#define LEFT_BUTTON_EXTI_LINE EXTI_Line0
#define LEFT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOE
#define LEFT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define LEFT_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Joystick Up push-button
*/
#define UP_BUTTON_PIN GPIO_Pin_8
#define UP_BUTTON_GPIO_PORT GPIOD
#define UP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define UP_BUTTON_EXTI_LINE EXTI_Line8
#define UP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define UP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource8
#define UP_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @brief Joystick Down push-button
*/
#define DOWN_BUTTON_PIN GPIO_Pin_14
#define DOWN_BUTTON_GPIO_PORT GPIOD
#define DOWN_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define DOWN_BUTTON_EXTI_LINE EXTI_Line14
#define DOWN_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define DOWN_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource14
#define DOWN_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Joystick Sel push-button
*/
#define SEL_BUTTON_PIN GPIO_Pin_12
#define SEL_BUTTON_GPIO_PORT GPIOD
#define SEL_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define SEL_BUTTON_EXTI_LINE EXTI_Line12
#define SEL_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define SEL_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource12
#define SEL_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @}
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_COM
* @{
*/
#define COMn 2
/**
* @brief Definition for COM port1, connected to USART1
*/
#define EVAL_COM1 USART1
#define EVAL_COM1_CLK RCC_APB2Periph_USART1
#define EVAL_COM1_TX_PIN GPIO_Pin_9
#define EVAL_COM1_TX_GPIO_PORT GPIOA
#define EVAL_COM1_TX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_RX_PIN GPIO_Pin_10
#define EVAL_COM1_RX_GPIO_PORT GPIOA
#define EVAL_COM1_RX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_IRQn USART1_IRQn
/**
* @brief Definition for COM port2, connected to USART2 (USART2 pins remapped on GPIOD)
*/
#define EVAL_COM2 USART2
#define EVAL_COM2_CLK RCC_APB1Periph_USART2
#define EVAL_COM2_TX_PIN GPIO_Pin_5
#define EVAL_COM2_TX_GPIO_PORT GPIOD
#define EVAL_COM2_TX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM2_RX_PIN GPIO_Pin_6
#define EVAL_COM2_RX_GPIO_PORT GPIOD
#define EVAL_COM2_RX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM2_IRQn USART2_IRQn
/**
* @}
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_SD_SPI
* @{
*/
/**
* @brief SD SPI Interface pins
*/
#define SD_SPI SPI1
#define SD_SPI_CLK RCC_APB2Periph_SPI1
#define SD_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */
#define SD_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */
#define SD_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */
#define SD_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_CS_PIN GPIO_Pin_12 /* PC.12 */
#define SD_CS_GPIO_PORT GPIOC /* GPIOC */
#define SD_CS_GPIO_CLK RCC_APB2Periph_GPIOC
#define SD_DETECT_PIN GPIO_Pin_7 /* PE.07 */
#define SD_DETECT_GPIO_PORT GPIOE /* GPIOE */
#define SD_DETECT_GPIO_CLK RCC_APB2Periph_GPIOE
/**
* @}
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_M25P_FLASH_SPI
* @{
*/
/**
* @brief M25P FLASH SPI Interface pins
*/
#define sFLASH_SPI SPI1
#define sFLASH_SPI_CLK RCC_APB2Periph_SPI1
#define sFLASH_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */
#define sFLASH_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */
#define sFLASH_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */
#define sFLASH_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_CS_PIN GPIO_Pin_9 /* PD.09 */
#define sFLASH_CS_GPIO_PORT GPIOD /* GPIOD */
#define sFLASH_CS_GPIO_CLK RCC_APB2Periph_GPIOD
/**
* @}
*/
/** @addtogroup STM32100B_EVAL_LOW_LEVEL_TSENSOR_I2C
* @{
*/
/**
* @brief LM75 Temperature Sensor I2C Interface pins
*/
#define LM75_I2C I2C1
#define LM75_I2C_CLK RCC_APB1Periph_I2C1
#define LM75_I2C_SCL_PIN GPIO_Pin_6 /* PB.06 */
#define LM75_I2C_SCL_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SCL_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SDA_PIN GPIO_Pin_7 /* PB.07 */
#define LM75_I2C_SDA_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SDA_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SMBUSALERT_PIN GPIO_Pin_5 /* PB.05 */
#define LM75_I2C_SMBUSALERT_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SMBUSALERT_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @}
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Exported_Functions
* @{
*/
void STM_EVAL_LEDInit(Led_TypeDef Led);
void STM_EVAL_LEDOn(Led_TypeDef Led);
void STM_EVAL_LEDOff(Led_TypeDef Led);
void STM_EVAL_LEDToggle(Led_TypeDef Led);
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode);
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button);
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct);
void SD_LowLevel_DeInit(void);
void SD_LowLevel_Init(void);
void sFLASH_LowLevel_DeInit(void);
void sFLASH_LowLevel_Init(void);
void LM75_LowLevel_DeInit(void);
void LM75_LowLevel_Init(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32100B_EVAL_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM32100B_EVAL/stm32100b_eval.h
|
C
|
asf20
| 11,995
|
/**
******************************************************************************
* @file stm32100b_eval_cec.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm32100b_eval_cec
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32100B_EVAL_CEC_H
#define __STM32100B_EVAL_CEC_H
#ifdef __cplusplus
extern "C"
{
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL
* @{
*/
/** @defgroup STM32100B_EVAL_CEC
* @{
*/
/** @defgroup STM32100B_EVAL_CEC_Exported_Types
* @{
*/
typedef enum
{
HDMI_CEC_BIT_TIMING = (1), /*!< CEC Bit Timing Error */
HDMI_CEC_BIT_PERIOD = (2), /*!< CEC Bit Period Error */
HDMI_CEC_RX_BLOCK_FINISHED = (3), /*!< CEC Receive Block finished Error */
HDMI_CEC_START_BIT = (4), /*!< CEC Start Bit Error */
HDMI_CEC_BLOCK_ACKNOWLEDGE = (5), /*!< CEC Block Acknowledge Error */
HDMI_CEC_LINE = (6), /*!< CEC Line Error */
HDMI_CEC_TX_BLOCK_FINISHED = (7), /*!< CEC Transmit Block Transfer finished Error */
HDMI_CEC_DEVICE_UNREGISTRED = (8), /*!< CEC Device Unregistred */
HDMI_CEC_TIMEOUT = (9), /*!< CEC TimeOut */
HDMI_CEC_OK = (10) /*!< CEC OK */
}HDMI_CEC_Error;
typedef struct
{
__IO uint8_t PhysicalAddress_A;
__IO uint8_t PhysicalAddress_B;
__IO uint8_t PhysicalAddress_C;
__IO uint8_t PhysicalAddress_D;
__IO uint8_t LogicalAddress;
__IO uint8_t DeviceType;
}HDMI_CEC_Map;
#define HDMI_CEC_TX_MESSAGE_LENGTH_MAX ((uint32_t)0x0000000E)
#define HDMI_CEC_TIMEOUT_VALUE ((uint32_t)0x001FFFFF)
/**
* @brief CEC Init Structure definition
*/
typedef struct
{
__IO uint8_t Header;
__IO uint8_t Opcode;
__IO uint8_t Operande[HDMI_CEC_TX_MESSAGE_LENGTH_MAX];
__IO uint8_t TxMessageLength;
__IO uint8_t RxMessageLength;
}HDMI_CEC_Message;
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Exported_Constants
* @{
*/
/**
* @brief CEC device types
*/
#define HDMI_CEC_TV 0x00
#define HDMI_CEC_RECORDING 0x01
#define HDMI_CEC_TUNER 0x03
#define HDMI_CEC_PLAYBACK 0x04
#define HDMI_CEC_AUDIOSYSTEM 0x05
/**
* @brief HDMI CEC I2C Interface pins
*/
#define HDMI_CEC_I2C_SCL_PIN GPIO_Pin_10
#define HDMI_CEC_I2C_SDA_PIN GPIO_Pin_11
#define HDMI_CEC_I2C_GPIO_PORT GPIOB
#define HDMI_CEC_I2C_GPIO_CLK RCC_APB2Periph_GPIOB
#define HDMI_CEC_I2C I2C2
#define HDMI_CEC_I2C_CLK RCC_APB1Periph_I2C2
/**
* @brief HDMI CEC HPD (Hot Plug Detect) Interface pin
*/
#define HDMI_CEC_HPD_PIN GPIO_Pin_12
#define HDMI_CEC_HPD_GPIO_PORT GPIOB
#define HDMI_CEC_HPD_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @brief HDMI CEC Interface pin
*/
#define HDMI_CEC_LINE_PIN GPIO_Pin_8
#define HDMI_CEC_LINE_GPIO_PORT GPIOB
#define HDMI_CEC_LINE_GPIO_CLK RCC_APB2Periph_GPIOB
#define HDMI_CEC_I2C_SLAVE_ADDRESS7 0xA0
#define HDMI_CEC_I2C_CLOCK_SPEED 100000
/**
* @brief HDMI CEC Root (Mainly for TV with a fixed physical address (0.0.0.0))
* If you want to configure the STM32100B-EVAL board as CEC Root (Sink)
* change the following define to 0x1
*/
#define HDMI_CEC_ROOT 0x00
/**
* @brief To select if the DDC Channel will be used for physical address discovery
* or not. To use the DDC Channel to read the EDID structure uncomment
* the following line.
* If the device is configured as HMDI source it should read his own physical
* address from the sink that is connected to.
*/
/* #define HDMI_CEC_USE_DDC */
/**
* @brief CEC version: V1.3a
*/
#define HDMI_CEC_VERSION 0x04
/**
* @brief Reason for Abort feature
*/
#define HDMI_CEC_UNRECOGNIZED_OPCODE 0x00
#define HDMI_CEC_NOT_CORRECT_MODETORESPOND 0x01
#define HDMI_CEC_CANNOTPROVIDE_SOURCE 0x02
#define HDMI_CEC_INVALID_OPERAND 0x03
#define HDMI_CEC_REFUSED 0x04
/**
* @brief HDMI CEC specific commands
*/
#define HDMI_CEC_OPCODE_ACTIVE_SOURCE ((uint8_t) 0x82)
#define HDMI_CEC_OPCODE_IMAGE_VIEW_ON ((uint8_t) 0x04)
#define HDMI_CEC_OPCODE_TEXT_VIEW_ON ((uint8_t) 0x0D)
#define HDMI_CEC_OPCODE_INACTIVE_SOURCE ((uint8_t) 0x9D)
#define HDMI_CEC_OPCODE_REQUEST_ACTIVE_SOURCE ((uint8_t) 0x85)
#define HDMI_CEC_OPCODE_ROUTING_CHANGE ((uint8_t) 0x80)
#define HDMI_CEC_OPCODE_ROUTING_INFORMATION ((uint8_t) 0x81)
#define HDMI_CEC_OPCODE_SET_STREAM_PATH ((uint8_t) 0x86)
#define HDMI_CEC_OPCODE_STANDBY ((uint8_t) 0x36)
#define HDMI_CEC_OPCODE_RECORD_OFF ((uint8_t) 0x0B)
#define HDMI_CEC_OPCODE_RECORD_ON ((uint8_t) 0x09)
#define HDMI_CEC_OPCODE_RECORD_STATUS ((uint8_t) 0x0A)
#define HDMI_CEC_OPCODE_RECORD_TV_SCREEN ((uint8_t) 0x0F)
#define HDMI_CEC_OPCODE_CLEAR_ANALOGUE_TIMER ((uint8_t) 0x33)
#define HDMI_CEC_OPCODE_CLEAR_DIGITAL_TIMER ((uint8_t) 0x99)
#define HDMI_CEC_OPCODE_CLEAR_EXTERNAL_TIMER ((uint8_t) 0xA1)
#define HDMI_CEC_OPCODE_SET_ANALOGUE_TIMER ((uint8_t) 0x34)
#define HDMI_CEC_OPCODE_SET_DIGITAL_TIMER ((uint8_t) 0x97)
#define HDMI_CEC_OPCODE_SET_EXTERNAL_TIMER ((uint8_t) 0xA2)
#define HDMI_CEC_OPCODE_SET_TIMER_PROGRAM_TITLE ((uint8_t) 0x67)
#define HDMI_CEC_OPCODE_TIMER_CLEARED_STATUS ((uint8_t) 0x43)
#define HDMI_CEC_OPCODE_TIMER_STATUS ((uint8_t) 0x35)
#define HDMI_CEC_OPCODE_CEC_VERSION ((uint8_t) 0x9E)
#define HDMI_CEC_OPCODE_GET_CEC_VERSION ((uint8_t) 0x9F)
#define HDMI_CEC_OPCODE_GIVE_PHYSICAL_ADDRESS ((uint8_t) 0x83)
#define HDMI_CEC_OPCODE_GET_MENU_LANGUAGE ((uint8_t) 0x91)
#define HDMI_CEC_OPCODE_REPORT_PHYSICAL_ADDRESS ((uint8_t) 0x84)
#define HDMI_CEC_OPCODE_SET_MENU_LANGUAGE ((uint8_t) 0x32)
#define HDMI_CEC_OPCODE_DECK_CONTROL ((uint8_t) 0x42)
#define HDMI_CEC_OPCODE_DECK_STATUS ((uint8_t) 0x1B)
#define HDMI_CEC_OPCODE_GIVE_DECK_STATUS ((uint8_t) 0x1A)
#define HDMI_CEC_OPCODE_PLAY ((uint8_t) 0x41)
#define HDMI_CEC_OPCODE_GIVE_TUNER_DEVICE_STATUS ((uint8_t) 0x08)
#define HDMI_CEC_OPCODE_SELECT_ANALOGUE_SERVICE ((uint8_t) 0x92)
#define HDMI_CEC_OPCODE_SELECT_DIGITAL_SERVICE ((uint8_t) 0x93)
#define HDMI_CEC_OPCODE_TUNER_DEVICE_STATUS ((uint8_t) 0x07)
#define HDMI_CEC_OPCODE_TUNER_STEP_DECREMENT ((uint8_t) 0x06)
#define HDMI_CEC_OPCODE_TUNER_STEP_INCREMENT ((uint8_t) 0x05)
#define HDMI_CEC_OPCODE_DEVICE_VENDOR_ID ((uint8_t) 0x87)
#define HDMI_CEC_OPCODE_GIVE_DEVICE_VENDOR_ID ((uint8_t) 0x8C)
#define HDMI_CEC_OPCODE_VENDOR_COMMAND ((uint8_t) 0x89)
#define HDMI_CEC_OPCODE_VENDOR_COMMAND_WITH_ID ((uint8_t) 0xA0)
#define HDMI_CEC_OPCODE_VENDOR_REMOTE_BUTTON_DOWN ((uint8_t) 0x8A)
#define HDMI_CEC_OPCODE_VENDOR_REMOTE_BUTTON_UP ((uint8_t) 0x8B)
#define HDMI_CEC_OPCODE_SET_OSD_STRING ((uint8_t) 0x64)
#define HDMI_CEC_OPCODE_GIVE_OSD_NAME ((uint8_t) 0x46)
#define HDMI_CEC_OPCODE_SET_OSD_NAME ((uint8_t) 0x47)
#define HDMI_CEC_OPCODE_MENU_REQUEST ((uint8_t) 0x8D)
#define HDMI_CEC_OPCODE_MENU_STATUS ((uint8_t) 0x8E)
#define HDMI_CEC_OPCODE_USER_CONTROL_PRESSED ((uint8_t) 0x44)
#define HDMI_CEC_OPCODE_USER_CONTROL_RELEASED ((uint8_t) 0x45)
#define HDMI_CEC_OPCODE_GIVE_DEVICE_POWER_STATUS ((uint8_t) 0x8F)
#define HDMI_CEC_OPCODE_REPORT_POWER_STATUS ((uint8_t) 0x90)
#define HDMI_CEC_OPCODE_FEATURE_ABORT ((uint8_t) 0x00)
#define HDMI_CEC_OPCODE_ABORT ((uint8_t) 0xFF)
#define HDMI_CEC_OPCODE_GIVE_AUDIO_STATUS ((uint8_t) 0x71)
#define HDMI_CEC_OPCODE_GIVE_SYSTEM_AUDIO_MODE_STATUS ((uint8_t) 0x7D)
#define HDMI_CEC_OPCODE_REPORT_AUDIO_STATUS ((uint8_t) 0x7A)
#define HDMI_CEC_OPCODE_SET_SYSTEM_AUDIO_MODE ((uint8_t) 0x72)
#define HDMI_CEC_OPCODE_SYSTEM_AUDIO_MODE_REQUEST ((uint8_t) 0x70)
#define HDMI_CEC_OPCODE_SYSTEM_AUDIO_MODE_STATUS ((uint8_t) 0x7E)
#define HDMI_CEC_OPCODE_SET_AUDIO_RATE ((uint8_t) 0x9A)
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Exported_Macros
* @{
*/
/* HDMI_CEC_HPD: HDMI HPD pin low */
#define HDMI_CEC_HPD_LOW() GPIO_ResetBits(HDMI_CEC_HPD_GPIO_PORT, HDMI_CEC_HPD_PIN)
/* HDMI_CEC_HPD: HDMI HPD pin high */
#define HDMI_CEC_HPD_HIGH() GPIO_SetBits(HDMI_CEC_HPD_GPIO_PORT, HDMI_CEC_HPD_PIN)
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Exported_Functions
* @{
*/
HDMI_CEC_Error HDMI_CEC_Init(void);
HDMI_CEC_Error HDMI_CEC_TransmitMessage(HDMI_CEC_Message *HDMI_CEC_TX_MessageStructure);
HDMI_CEC_Error HDMI_CEC_GetErrorStatus (void);
void HDMI_CEC_ProcessIRQSrc(void);
HDMI_CEC_Error HDMI_CEC_ReportPhysicalAddress(void);
void HDMI_CEC_CommandCallBack(void);
HDMI_CEC_Error HDMI_CEC_CheckConnectedDevices(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32100B_EVAL_CEC_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM32100B_EVAL/stm32100b_eval_cec.h
|
C
|
asf20
| 11,762
|
/**
******************************************************************************
* @file stm32100b_eval_cec.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides all the STM32100B-EVAL HDMI-CEC firmware functions.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32100b_eval_cec.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL
* @{
*/
/** @defgroup STM32100B_EVAL_CEC
* @brief This file includes the CEC Stack driver for HDMI-CEC Module
* of STM32100B-EVAL board.
* @{
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Variables
* @{
*/
__IO uint32_t ReceivedFrame = 0;
__IO uint32_t SendFrame = 0;
__IO uint32_t BufferCount = 0, TxCounter = 0, RxCounter = 0;
__IO uint8_t BufferPointer[15];
__IO uint32_t ReceiveStatus = 0;
__IO uint32_t SendStatus = 0;
__IO uint8_t TransErrorCode = 0;
__IO uint8_t RecepErrorCode = 0;
__IO uint8_t MyLogicalAddress = 0;
__IO uint16_t MyPhysicalAddress = 0;
__IO uint8_t DeviceType = 0;
#ifdef HDMI_CEC_USE_DDC
__IO uint8_t pBuffer[256];
__IO uint16_t NumByteToRead = 255;
#endif
__IO uint8_t CECDevicesNumber = 0;
HDMI_CEC_Message HDMI_CEC_TX_MessageStructPrivate;
HDMI_CEC_Message HDMI_CEC_RX_MessageStructPrivate;
HDMI_CEC_Message HDMI_CEC_TX_MessageStructure;
__IO uint8_t FeatureOpcode = 0;
__IO uint8_t AbortReason = 0;
__IO uint8_t DeviceCount = 0;
HDMI_CEC_Map HDMI_CEC_MapStruct;
HDMI_CEC_Map HDMI_CEC_DeviceMap[14];
/* CEC follower addresses */
uint8_t* HDMI_CEC_Follower_String[13][2] =
{
{" TV ", "0"},
{"Recording Device 1 ", "0"},
{"Recording Device 2 ", "0"},
{" Tuner 1 ", "0"},
{" Playback Device 1 ", "0"},
{" Audio System ", "0"},
{" Tuner 2 ", "0"},
{" Tuner 3 ", "0"},
{" Playback Device 2 ", "0"},
{"Recording Device 3 ", "0"},
{" Tuner 4 ", "0"},
{" Playback Device 3 ", "0"},
{" Broadcast ", "1"}
};
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Function_Prototypes
* @{
*/
static HDMI_CEC_Error PhysicalAddressDiscovery(void);
static HDMI_CEC_Error LogicalAddressAllocation(void);
/**
* @}
*/
/** @defgroup STM32100B_EVAL_CEC_Private_Functions
* @{
*/
/**
* @brief Initializes the HDMI CEC.
* @param None
* @retval HDMI_CEC_Error: CEC Error code
*/
HDMI_CEC_Error HDMI_CEC_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
CEC_InitTypeDef CEC_InitStructure;
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
uint8_t sendcount = 0;
#ifdef HDMI_CEC_USE_DDC
I2C_InitTypeDef I2C_InitStructure;
/* Enable CEC_I2C clocks */
RCC_APB1PeriphClockCmd(HDMI_CEC_I2C_CLK, ENABLE);
/* Enable CEC_I2C_GPIO and CEC_HPD_GPIO clocks */
RCC_APB2PeriphClockCmd(HDMI_CEC_I2C_GPIO_CLK | HDMI_CEC_HPD_GPIO_CLK, ENABLE);
#endif
/* Enable CEC clocks */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CEC, ENABLE);
/* Enable CEC_LINE_GPIO clocks */
RCC_APB2PeriphClockCmd(HDMI_CEC_LINE_GPIO_CLK, ENABLE);
/* Configure CEC_LINE_GPIO as Output open drain */
GPIO_InitStructure.GPIO_Pin = HDMI_CEC_LINE_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(HDMI_CEC_LINE_GPIO_PORT, &GPIO_InitStructure);
#ifdef HDMI_CEC_USE_DDC
/* Configure CEC_I2C_SCL_PIN and CEC_I2C_SDA_PIN as Output open drain */
GPIO_InitStructure.GPIO_Pin = HDMI_CEC_I2C_SCL_PIN | HDMI_CEC_I2C_SDA_PIN;
GPIO_Init(HDMI_CEC_I2C_GPIO_PORT, &GPIO_InitStructure);
/* This configuration is only when the HDMI CEC is configured as source.
The HDMI source has to provide the +5V Power signal to the sink.
On STM32100B-EVAL borad, you have to solder the SB4 Solder bridge.
Then, the source will wait for HPD signal to be asserted from the sink.
Once the HPD signal is detected the source shall read the EDID structure
throuhgh the DDC channel. */
/* Configure CEC_HPD_GPIO as Input pull down */
GPIO_InitStructure.GPIO_Pin = HDMI_CEC_HPD_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(HDMI_CEC_HPD_GPIO_PORT, &GPIO_InitStructure);
/* This configuration is only when the HDMI CEC is configured as sink.
The HDMI sink has to wait for the +5V Power signal from the source.
On STM32100B-EVAL borad, SB4 Solder bridge should be open (default configuration).
Then, the sink will assert the HPD signal to inform the source that the EDID
is ready for read through DDC channel. In this implementation, the EDID structure
is not implemented. */
/* GPIO_InitStructure.GPIO_Pin = HDMI_CEC_HPD_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(HDMI_CEC_HPD_GPIO_PORT, &GPIO_InitStructure);
HDMI_CEC_HPD_HIGH(); // Set the Hot plug detect signal */
/* Enable CEC_I2C */
I2C_Cmd(HDMI_CEC_I2C, ENABLE);
/* I2C configuration */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = HDMI_CEC_I2C_SLAVE_ADDRESS7;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = HDMI_CEC_I2C_CLOCK_SPEED;
I2C_Init(HDMI_CEC_I2C, &I2C_InitStructure);
#endif
/* Physical Address discovery */
errorstatus = PhysicalAddressDiscovery();
if (errorstatus != HDMI_CEC_OK)
{
/* Device not connected (Physical Address lost) */
return(errorstatus);
}
/* CEC DeInit */
CEC_DeInit();
/* Configure CEC */
CEC_InitStructure.CEC_BitTimingMode = CEC_BitTimingStdMode;
CEC_InitStructure.CEC_BitPeriodMode = CEC_BitPeriodStdMode;
CEC_Init(&CEC_InitStructure);
/* Set Prescaler value for APB1 clock = 24MHz */
CEC_SetPrescaler(0x4AF);
/* Enable CEC */
CEC_Cmd(ENABLE);
/* Logical Address Allocation */
sendcount = 0;
errorstatus = LogicalAddressAllocation();
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = LogicalAddressAllocation();
}
if (errorstatus != HDMI_CEC_OK)
{
/* Device Unregistred */
return(errorstatus);
}
HDMI_CEC_CheckConnectedDevices();
/* Set the CEC initiator address */
CEC_OwnAddressConfig(MyLogicalAddress);
/* Activate CEC interrupts associated to the set of RBTF,RERR, TBTF, TERR flags */
CEC_ITConfig(ENABLE);
/* Report physical address*/
errorstatus = HDMI_CEC_ReportPhysicalAddress();
sendcount = 0;
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = HDMI_CEC_ReportPhysicalAddress();
}
if (errorstatus != HDMI_CEC_OK)
{
/* Device Unregistred */
return(errorstatus);
}
return errorstatus;
}
/**
* @brief Transmit message by taking data from typedef struct CEC_Meassage
* @param CEC_TX_MessageStructure: pointer to an CEC_Message structure that contains
* the message to be sent.
* @retval HDMI_CEC_Error: CEC Error code
*/
HDMI_CEC_Error HDMI_CEC_TransmitMessage(HDMI_CEC_Message *HDMI_CEC_TX_MessageStructure)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
__IO uint32_t count = 0, j = 0;
SendFrame = 0;
SendStatus = 0;
TxCounter = 0;
BufferCount = 0;
HDMI_CEC_TX_MessageStructPrivate = *HDMI_CEC_TX_MessageStructure;
/* Initialize BufferPointer */
for (j = 0; j < 15; j++)
{
BufferPointer[j] = 0;
}
BufferPointer[0] = HDMI_CEC_TX_MessageStructPrivate.Opcode;
for (BufferCount = 1; BufferCount < HDMI_CEC_TX_MessageStructPrivate.TxMessageLength + 1; BufferCount++)
{
BufferPointer[BufferCount] = HDMI_CEC_TX_MessageStructPrivate.Operande[BufferCount-1];
}
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
/* Write single Data in the TX Buffer to Transmit through the CEC peripheral */
CEC_SendDataByte(HDMI_CEC_TX_MessageStructPrivate.Header);
/* Initiate Message Transmission */
CEC_StartOfMessage();
while ((SendFrame == 0) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
if (SendStatus == 0)
{
errorstatus = (HDMI_CEC_Error) TransErrorCode;
}
return errorstatus;
}
/**
* @brief Get the ESR register status.
* @param None
* @retval HDMI_CEC_Error: CEC Error code
*/
HDMI_CEC_Error HDMI_CEC_GetErrorStatus (void)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
/* Bit timing error case*/
if (CEC_GetFlagStatus(CEC_FLAG_BTE) != RESET)
{
errorstatus = HDMI_CEC_BIT_TIMING;
}
/* Bit period error case */
if (CEC_GetFlagStatus(CEC_FLAG_BPE) != RESET)
{
errorstatus = HDMI_CEC_BIT_PERIOD;
}
/* Recieve error case */
if (CEC_GetFlagStatus(CEC_FLAG_RBTFE) != RESET)
{
errorstatus = HDMI_CEC_RX_BLOCK_FINISHED;
}
/* Start bit error case*/
if (CEC_GetFlagStatus(CEC_FLAG_SBE) != RESET)
{
errorstatus = HDMI_CEC_START_BIT;
}
/* Acknowledge error case*/
if (CEC_GetFlagStatus(CEC_FLAG_ACKE) != RESET)
{
errorstatus = HDMI_CEC_BLOCK_ACKNOWLEDGE;
}
/* Line error case */
if (CEC_GetFlagStatus(CEC_FLAG_LINE) != RESET)
{
errorstatus = HDMI_CEC_LINE;
}
/* Transfert error case*/
if (CEC_GetFlagStatus(CEC_FLAG_TBTFE) != RESET)
{
errorstatus = HDMI_CEC_TX_BLOCK_FINISHED;
}
/* Clear All errors */
CEC_ClearFlag(CEC_FLAG_RERR);
CEC_ClearFlag(CEC_FLAG_TERR);
return errorstatus;
}
/**
* @brief Allows to process all the interrupts that are high.
* @param None
* @retval None
*/
void HDMI_CEC_ProcessIRQSrc(void)
{
/********************** Reception *********************************************/
/* Check if a reception error occured */
if (CEC_GetFlagStatus(CEC_FLAG_RERR))
{
/* Set receive status bit (Error) */
ReceiveStatus = 0;
ReceivedFrame = 1;
RecepErrorCode = HDMI_CEC_GetErrorStatus();
CEC_ClearFlag(CEC_FLAG_RERR | CEC_FLAG_RSOM | CEC_FLAG_REOM | CEC_FLAG_RBTF);
}
else if (CEC_GetFlagStatus(CEC_FLAG_RBTF))
{
/* Check if the byte received is the last one of the message */
if (CEC_GetFlagStatus(CEC_FLAG_REOM))
{
HDMI_CEC_RX_MessageStructPrivate.Operande[RxCounter-1] = CEC_ReceiveDataByte();
HDMI_CEC_RX_MessageStructPrivate.RxMessageLength = RxCounter;
ReceiveStatus = SUCCESS;
ReceivedFrame = 1;
}
/* Check if the byte received is a Header */
else if (CEC_GetFlagStatus(CEC_FLAG_RSOM))
{
ReceiveStatus = 0;
HDMI_CEC_RX_MessageStructPrivate.Header = CEC_ReceiveDataByte();
RxCounter = 0;
}
/* Receive each byte except header in the reception buffer */
else
{
if (RxCounter != 0)
{
HDMI_CEC_RX_MessageStructPrivate.Operande[RxCounter-1] = CEC_ReceiveDataByte();
RxCounter++;
}
else
{
HDMI_CEC_RX_MessageStructPrivate.Opcode = CEC_ReceiveDataByte();
RxCounter++;
}
}
/* Clear all reception flags */
CEC_ClearFlag(CEC_FLAG_RSOM | CEC_FLAG_REOM | CEC_FLAG_RBTF);
}
/********************** Transmission ******************************************/
/* Check if a transmission error occured */
if (CEC_GetFlagStatus(CEC_FLAG_TERR))
{
TransErrorCode = HDMI_CEC_GetErrorStatus();
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
SendFrame = 1;
SendStatus = 0;
}
/* Check if end of message bit is set in the data to be transmitted */
else if (CEC_GetFlagStatus(CEC_FLAG_TEOM))
{
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_RBTF);
CEC_EndOfMessageCmd(DISABLE);
SendFrame = 1;
SendStatus = SUCCESS;
}
/* Check if data byte has been sent */
else if (CEC_GetFlagStatus(CEC_FLAG_TBTRF))
{
/* Set EOM bit if the byte to be transmitted is the last one of the TransmitBuffer */
if (TxCounter == (HDMI_CEC_TX_MessageStructPrivate.TxMessageLength))
{
CEC_SendDataByte(BufferPointer[TxCounter]);
TxCounter++;
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(ENABLE);
}
else
{
/* Put the byte in the TX Buffer */
CEC_SendDataByte(BufferPointer[TxCounter]);
TxCounter++;
CEC_ClearFlag(CEC_FLAG_TBTRF);
}
}
}
/**
* @brief Report physical address to all other devices thus allowing any
device to create a map of the network.
* @param None
* @retval HDMI_CEC_Error: CEC Error code.
*/
HDMI_CEC_Error HDMI_CEC_ReportPhysicalAddress(void)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
HDMI_CEC_Message HDMI_CEC_TX_Message;
HDMI_CEC_TX_Message.Header = ((MyLogicalAddress << 4) | 0xF);
HDMI_CEC_TX_Message.Opcode = HDMI_CEC_OPCODE_REPORT_PHYSICAL_ADDRESS;
HDMI_CEC_TX_Message.Operande[0] = MyPhysicalAddress >> 8;
HDMI_CEC_TX_Message.Operande[1] = MyPhysicalAddress & 0xFF;
HDMI_CEC_TX_Message.Operande[2] = DeviceType;
HDMI_CEC_TX_Message.TxMessageLength = 0x03;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_Message);
return errorstatus;
}
/**
* @brief Handle CEC command receive callback.
* When receiving the STANDBY Opcode commande, the system is entred in
* Stop mode and when wakeup, the PLL is configured as system clock and
* the HSI is selected as PLL source.
* @param None
* @retval None
*/
void HDMI_CEC_CommandCallBack(void)
{
uint8_t i = 0, sendcount = 0;
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
EXTI_InitTypeDef EXTI_InitStructure;
switch (HDMI_CEC_RX_MessageStructPrivate.Opcode)
{
case HDMI_CEC_OPCODE_REPORT_PHYSICAL_ADDRESS:
HDMI_CEC_MapStruct.PhysicalAddress_A = HDMI_CEC_RX_MessageStructPrivate.Operande[1] >> 4;
HDMI_CEC_MapStruct.PhysicalAddress_B = HDMI_CEC_RX_MessageStructPrivate.Operande[1] & 0x0F;
HDMI_CEC_MapStruct.PhysicalAddress_C = HDMI_CEC_RX_MessageStructPrivate.Operande[0] >> 4;
HDMI_CEC_MapStruct.PhysicalAddress_D = HDMI_CEC_RX_MessageStructPrivate.Operande[0] & 0x0F;
HDMI_CEC_MapStruct.LogicalAddress = (HDMI_CEC_RX_MessageStructPrivate.Header >> 0x4) & 0x0F;
HDMI_CEC_MapStruct.DeviceType = HDMI_CEC_RX_MessageStructPrivate.Operande[2];
HDMI_CEC_DeviceMap[DeviceCount] = HDMI_CEC_MapStruct;
HDMI_CEC_Follower_String[(HDMI_CEC_DeviceMap[DeviceCount].LogicalAddress)][1] = "1";
DeviceCount++;
break;
case HDMI_CEC_OPCODE_STANDBY:
/* CEC Line */
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource8);
/* Configure the CEC Line as EXTI Line on Falling Edge */
EXTI_ClearITPendingBit(EXTI_Line8);
EXTI_InitStructure.EXTI_Line = EXTI_Line8;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Request to enter Stop mode */
PWR_EnterSTOPMode(PWR_Regulator_ON, PWR_STOPEntry_WFI);
/* Disable the CEC EXTI Line */
EXTI_InitStructure.EXTI_LineCmd = DISABLE;
EXTI_Init(&EXTI_InitStructure);
/* Configure the PLL Source */
RCC_PLLConfig(RCC_PLLSource_HSI_Div2, RCC_PLLMul_6);
/* Enable PLL */
RCC_PLLCmd(ENABLE);
/* Wait till PLL is ready */
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
{
}
/* Select PLL as system clock source */
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
/* Wait till PLL is used as system clock source */
while(RCC_GetSYSCLKSource() != 0x08)
{
}
break;
case HDMI_CEC_OPCODE_GET_CEC_VERSION:
/* Send the Used CEC version */
HDMI_CEC_TX_MessageStructPrivate.Header = ((MyLogicalAddress << 4) | HDMI_CEC_RX_MessageStructPrivate.Header >> 4);
HDMI_CEC_TX_MessageStructPrivate.Opcode = HDMI_CEC_OPCODE_CEC_VERSION;
HDMI_CEC_TX_MessageStructPrivate.Operande[0] = HDMI_CEC_VERSION; /* CEC Version */
HDMI_CEC_TX_MessageStructPrivate.TxMessageLength = 0x01;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
/* Retransmit message until 5 time */
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
}
break;
case HDMI_CEC_OPCODE_GIVE_PHYSICAL_ADDRESS:
/* Send the Physical address */
errorstatus = HDMI_CEC_ReportPhysicalAddress();
sendcount = 0;
/* Retransmit message until 5 time */
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = HDMI_CEC_ReportPhysicalAddress();
}
break;
case HDMI_CEC_OPCODE_FEATURE_ABORT:
/* The device doesn't support the requested message type, or that it cannot
execute it at the present time. */
FeatureOpcode = HDMI_CEC_RX_MessageStructPrivate.Operande[0];
AbortReason = HDMI_CEC_RX_MessageStructPrivate.Operande[1];
break;
case HDMI_CEC_OPCODE_GIVE_OSD_NAME:
/* Send the OSD name = STM32100B CEC*/
HDMI_CEC_TX_MessageStructPrivate.Header = ((MyLogicalAddress << 4) | HDMI_CEC_RX_MessageStructPrivate.Header >> 4);
HDMI_CEC_TX_MessageStructPrivate.Opcode = HDMI_CEC_OPCODE_SET_OSD_NAME;
/* STM32100B*/
HDMI_CEC_TX_MessageStructPrivate.Operande[0] = 0x53;
HDMI_CEC_TX_MessageStructPrivate.Operande[1] = 0x54;
HDMI_CEC_TX_MessageStructPrivate.Operande[2] = 0x4D;
HDMI_CEC_TX_MessageStructPrivate.Operande[3] = 0x33;
HDMI_CEC_TX_MessageStructPrivate.Operande[4] = 0x32;
HDMI_CEC_TX_MessageStructPrivate.Operande[5] = 0x31;
HDMI_CEC_TX_MessageStructPrivate.Operande[6] = 0x30;
HDMI_CEC_TX_MessageStructPrivate.Operande[7] = 0x30;
HDMI_CEC_TX_MessageStructPrivate.Operande[8] = 0x42;
HDMI_CEC_TX_MessageStructPrivate.Operande[9] = 0x20;
/* CEC */
HDMI_CEC_TX_MessageStructPrivate.Operande[10] = 0x43;
HDMI_CEC_TX_MessageStructPrivate.Operande[11] = 0x45;
HDMI_CEC_TX_MessageStructPrivate.Operande[12] = 0x43;
HDMI_CEC_TX_MessageStructPrivate.TxMessageLength = 13;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
sendcount = 0;
/* Retransmit message until 5 time */
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
}
break;
case HDMI_CEC_OPCODE_ROUTING_CHANGE:
for (i = 0;i < 0x14;i++)
{
if ((HDMI_CEC_DeviceMap[i].PhysicalAddress_A == HDMI_CEC_RX_MessageStructPrivate.Operande[1] >> 4) &&
(HDMI_CEC_DeviceMap[i].PhysicalAddress_B == HDMI_CEC_RX_MessageStructPrivate.Operande[1]&0x0F) &&
(HDMI_CEC_DeviceMap[i].PhysicalAddress_C == HDMI_CEC_RX_MessageStructPrivate.Operande[0] >> 4) &&
(HDMI_CEC_DeviceMap[i].PhysicalAddress_D == HDMI_CEC_RX_MessageStructPrivate.Operande[0]&0x0F))
{
HDMI_CEC_MapStruct.LogicalAddress = (HDMI_CEC_RX_MessageStructPrivate.Header >> 0x4) & 0x0F;
HDMI_CEC_MapStruct.DeviceType = HDMI_CEC_RX_MessageStructPrivate.Operande[2];
HDMI_CEC_DeviceMap[i] = HDMI_CEC_MapStruct;
}
}
break;
default:
/* Send Abort feature*/
HDMI_CEC_TX_MessageStructPrivate.Header = ((MyLogicalAddress << 4) | HDMI_CEC_RX_MessageStructPrivate.Header >> 4);
HDMI_CEC_TX_MessageStructPrivate.Opcode = HDMI_CEC_OPCODE_FEATURE_ABORT;
HDMI_CEC_TX_MessageStructPrivate.Operande[0] = 0x02; /* defines command to be performed */
HDMI_CEC_TX_MessageStructPrivate.Operande[1] = HDMI_CEC_REFUSED; /* Reason for abort feature */
HDMI_CEC_TX_MessageStructPrivate.TxMessageLength = 0x02;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
sendcount = 0;
/* Retransmit message until 5 time */
while ((errorstatus != HDMI_CEC_OK) && sendcount < 0x5)
{
sendcount++;
errorstatus = HDMI_CEC_TransmitMessage(&HDMI_CEC_TX_MessageStructPrivate);
}
break;
}
}
/**
* @brief Check the connected CEC devices.
* @param None
* @retval HDMI_CEC_Error
*/
HDMI_CEC_Error HDMI_CEC_CheckConnectedDevices(void)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
uint32_t count = 0, i = 1;
/*----------------------------- TV device ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x0);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[0][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Recording device 1 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x1);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[1][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Recording device 2 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x2);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[2][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Tuner 1 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x3);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[3][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Playback device 1 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x4);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[4][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Audio system ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x5);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[5][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Tuner 2 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x6);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[6][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Tuner 3 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x7);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[7][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Playback device 2 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x8);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[8][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Recording device 3 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0x9);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[9][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Tuner 4 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0xA);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[10][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
/*----------------------------- Playback device 3 ---------------------------*/
CEC_OwnAddressConfig(MyLogicalAddress); /* Own address = MyLogicalAddress */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte((MyLogicalAddress << 4) | 0xB);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_OK)
{
HDMI_CEC_Follower_String[11][1] = "1";
i++;
errorstatus = HDMI_CEC_OK;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
CECDevicesNumber = i - 1;
return errorstatus;
}
/**
* @brief Physical address discovery.
* @param None
* @retval HDMI_CEC_Error: CEC Error code.
*/
static HDMI_CEC_Error PhysicalAddressDiscovery(void)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
#ifdef HDMI_CEC_USE_DDC
uint32_t index = 0, i = 0;
#endif
/*------------------------------ Physical address discovery -----------------*/
if (HDMI_CEC_ROOT == 0x1)
{
MyPhysicalAddress = 0x0000;
/* The HDMI-CEC here is configured as sink or as a repeater. The configuration
of the +5V power signal and the HPD should be well configured.
Implement here the EDID Structure to be sent to the HDMI source.
For more details please refer to the HDMI specification.
The EDID structure should be sent to the device source using the DDC Channel
and using the HPD signal. */
}
else
{
#ifdef HDMI_CEC_USE_DDC
/* The HDMI-CEC here is configured as source or as a repeater. The configuration
of the +5V power signal and the HPD should be well configured.
The source should wait for HPD and then read the EDID structure. */
while(GPIO_ReadInputDataBit(HDMI_CEC_HPD_GPIO_PORT, HDMI_CEC_HPD_PIN) == RESET)
{
}
/* Wait for 100 ms after HPD was received */
for(i = 0; i < 0x5FFFF; i++)
{
}
/* Return the physical address using the I2C by reading the 2 bytes 24 and
25 form the EDID */
/* Read the EDID Block 0 and EDID Block 1 at address 0xA0 */
/*!< While the bus is busy */
while(I2C_GetFlagStatus(HDMI_CEC_I2C, I2C_FLAG_BUSY))
{
}
/*!< Send START condition */
I2C_GenerateSTART(HDMI_CEC_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for write */
I2C_Send7bitAddress(HDMI_CEC_I2C, 0xA0, I2C_Direction_Transmitter);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
}
/*!< Send the EEPROM's internal address to read from: Only one byte address */
I2C_SendData(HDMI_CEC_I2C, 0x00);
/*!< Test on EV8 and clear it */
while(!I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
}
/*!< Send STRAT condition a second time */
I2C_GenerateSTART(HDMI_CEC_I2C, ENABLE);
/*!< Test on EV5 and clear it */
while(!I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
}
/*!< Send EEPROM address for read */
I2C_Send7bitAddress(HDMI_CEC_I2C, 0xA1, I2C_Direction_Receiver);
/*!< Test on EV6 and clear it */
while(!I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
}
/* While there is data to be read */
while (NumByteToRead-- > 1)
{
while(I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
}
for(i = 0; i < 0xFFF; i++)
{
}
pBuffer[index++] = I2C_ReceiveData(HDMI_CEC_I2C);
}
/* Disable Acknowledgement */
I2C_AcknowledgeConfig(HDMI_CEC_I2C, DISABLE);
/* Send STOP Condition */
I2C_GenerateSTOP(HDMI_CEC_I2C, ENABLE);
while(I2C_CheckEvent(HDMI_CEC_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED));
pBuffer[index] = I2C_ReceiveData(HDMI_CEC_I2C);
/* Enable Acknowledgement to be ready for another reception */
I2C_AcknowledgeConfig(HDMI_CEC_I2C, ENABLE);
MyPhysicalAddress = ((pBuffer[138] << 8) | pBuffer[137]);
#else
MyPhysicalAddress = 0x1000;
#endif
}
return errorstatus;
}
/**
* @brief Allocate the logical address.
* @param None
* @retval HDMI_CEC_Error: CEC Error code.
*/
static HDMI_CEC_Error LogicalAddressAllocation(void)
{
HDMI_CEC_Error errorstatus = HDMI_CEC_OK;
uint32_t count = 0;
/*------------------ Logical address allocation -----------------------------*/
/* Get the device type */
/* Device type = CEC_TV */
if (DeviceType == HDMI_CEC_TV)
{
if (HDMI_CEC_ROOT)
{
MyLogicalAddress = 0x00;
}
else
{
CEC_OwnAddressConfig(0xE); /* Own address = 0xE */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0xEE);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the polling message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x0E;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
MyLogicalAddress = 0x0F;
errorstatus = HDMI_CEC_DEVICE_UNREGISTRED;
}
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF);
CEC_EndOfMessageCmd(DISABLE);
}
/* Device type = CEC_RECORDING */
if (DeviceType == HDMI_CEC_RECORDING)
{
CEC_OwnAddressConfig(0x1); /* Own address = 0x1 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x11);
/* Start of message */
CEC_StartOfMessage();
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x01;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0x2); /* Own address = 0x2 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x22);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x02;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0x9); /* Own address = 0x9 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x99);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x09;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
MyLogicalAddress = 0x0F;
errorstatus = HDMI_CEC_DEVICE_UNREGISTRED;
}
}
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
}
/* Device type = CEC_TUNER */
if (DeviceType == HDMI_CEC_TUNER)
{
CEC_OwnAddressConfig(0x3); /* Own address = 0x3 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x33);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x03;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0x6); /* Own address = 0x6 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x66);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x06;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0x7); /* Own address = 0x7 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x77);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x07;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0xA); /* Own address = 0xA */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0xAA);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x0A;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
MyLogicalAddress = 0x0F;
errorstatus = HDMI_CEC_DEVICE_UNREGISTRED;
}
}
}
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
}
/* Device type = CEC_PLAYBACK */
if (DeviceType == HDMI_CEC_PLAYBACK)
{
CEC_OwnAddressConfig(0x4); /* Own address = 0x4 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x44);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x04;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0x8); /* Own address = 0x8 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x88);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x08;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
CEC_OwnAddressConfig(0xB); /* Own address = 0xBB */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0xBB);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x0B;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
MyLogicalAddress = 0x0F;
errorstatus = HDMI_CEC_DEVICE_UNREGISTRED;
}
}
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
}
/* Device type = CEC Audio System */
if (DeviceType == HDMI_CEC_AUDIOSYSTEM)
{
CEC_OwnAddressConfig(0x5); /* Own address = 0x5 */
CEC_EndOfMessageCmd(ENABLE);
CEC_SendDataByte(0x55);
/* Start of message */
CEC_StartOfMessage();
count = 0;
/* Wait till the header message is sent */
while ((CEC_GetFlagStatus(CEC_FLAG_TBTRF) == RESET) && (CEC_GetFlagStatus(CEC_FLAG_TERR) == RESET) && (count < HDMI_CEC_TIMEOUT_VALUE))
{
count++;
}
if (count >= HDMI_CEC_TIMEOUT_VALUE)
{
errorstatus = HDMI_CEC_TIMEOUT;
return(errorstatus);
}
errorstatus = HDMI_CEC_GetErrorStatus();
if (errorstatus == HDMI_CEC_BLOCK_ACKNOWLEDGE)
{
MyLogicalAddress = 0x05;
errorstatus = HDMI_CEC_OK;
}
else if (errorstatus == HDMI_CEC_OK)
{
MyLogicalAddress = 0x0F;
errorstatus = HDMI_CEC_DEVICE_UNREGISTRED;
}
/* Clear CEC CSR register */
CEC_ClearFlag(CEC_FLAG_TBTRF | CEC_FLAG_TERR);
CEC_EndOfMessageCmd(DISABLE);
}
return errorstatus;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM32100B_EVAL/stm32100b_eval_cec.c
|
C
|
asf20
| 49,615
|
/**
******************************************************************************
* @file stm32100b_eval.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides
* - set of firmware functions to manage Leds, push-button and COM ports
* - low level initialization functions for SD card (on SPI), SPI serial
* flash (sFLASH) and temperature sensor (LM75)
* available on STM32100B-EVAL evaluation board from STMicroelectronics.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32100b_eval.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_i2c.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM32100B_EVAL
* @{
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL
* @brief This file provides firmware functions to manage Leds, push-buttons,
* COM ports, SD card on SPI, serial flash (sFLASH) and temperature
* sensor (LM75) available on STM32100B-EVAL evaluation board from
* STMicroelectronics.
* @{
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_Variables
* @{
*/
GPIO_TypeDef* GPIO_PORT[LEDn] = {LED1_GPIO_PORT, LED2_GPIO_PORT, LED3_GPIO_PORT,
LED4_GPIO_PORT};
const uint16_t GPIO_PIN[LEDn] = {LED1_PIN, LED2_PIN, LED3_PIN,
LED4_PIN};
const uint32_t GPIO_CLK[LEDn] = {LED1_GPIO_CLK, LED2_GPIO_CLK, LED3_GPIO_CLK,
LED4_GPIO_CLK};
GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {WAKEUP_BUTTON_GPIO_PORT, TAMPER_BUTTON_GPIO_PORT,
KEY_BUTTON_GPIO_PORT, RIGHT_BUTTON_GPIO_PORT,
LEFT_BUTTON_GPIO_PORT, UP_BUTTON_GPIO_PORT,
DOWN_BUTTON_GPIO_PORT, SEL_BUTTON_GPIO_PORT};
const uint16_t BUTTON_PIN[BUTTONn] = {WAKEUP_BUTTON_PIN, TAMPER_BUTTON_PIN,
KEY_BUTTON_PIN, RIGHT_BUTTON_PIN,
LEFT_BUTTON_PIN, UP_BUTTON_PIN,
DOWN_BUTTON_PIN, SEL_BUTTON_PIN};
const uint32_t BUTTON_CLK[BUTTONn] = {WAKEUP_BUTTON_GPIO_CLK, TAMPER_BUTTON_GPIO_CLK,
KEY_BUTTON_GPIO_CLK, RIGHT_BUTTON_GPIO_CLK,
LEFT_BUTTON_GPIO_CLK, UP_BUTTON_GPIO_CLK,
DOWN_BUTTON_GPIO_CLK, SEL_BUTTON_GPIO_CLK};
const uint16_t BUTTON_EXTI_LINE[BUTTONn] = {WAKEUP_BUTTON_EXTI_LINE,
TAMPER_BUTTON_EXTI_LINE,
KEY_BUTTON_EXTI_LINE,
RIGHT_BUTTON_EXTI_LINE,
LEFT_BUTTON_EXTI_LINE,
UP_BUTTON_EXTI_LINE,
DOWN_BUTTON_EXTI_LINE,
SEL_BUTTON_EXTI_LINE};
const uint16_t BUTTON_PORT_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PORT_SOURCE,
TAMPER_BUTTON_EXTI_PORT_SOURCE,
KEY_BUTTON_EXTI_PORT_SOURCE,
RIGHT_BUTTON_EXTI_PORT_SOURCE,
LEFT_BUTTON_EXTI_PORT_SOURCE,
UP_BUTTON_EXTI_PORT_SOURCE,
DOWN_BUTTON_EXTI_PORT_SOURCE,
SEL_BUTTON_EXTI_PORT_SOURCE};
const uint16_t BUTTON_PIN_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PIN_SOURCE,
TAMPER_BUTTON_EXTI_PIN_SOURCE,
KEY_BUTTON_EXTI_PIN_SOURCE,
RIGHT_BUTTON_EXTI_PIN_SOURCE,
LEFT_BUTTON_EXTI_PIN_SOURCE,
UP_BUTTON_EXTI_PIN_SOURCE,
DOWN_BUTTON_EXTI_PIN_SOURCE,
SEL_BUTTON_EXTI_PIN_SOURCE};
const uint16_t BUTTON_IRQn[BUTTONn] = {WAKEUP_BUTTON_EXTI_IRQn, TAMPER_BUTTON_EXTI_IRQn,
KEY_BUTTON_EXTI_IRQn, RIGHT_BUTTON_EXTI_IRQn,
LEFT_BUTTON_EXTI_IRQn, UP_BUTTON_EXTI_IRQn,
DOWN_BUTTON_EXTI_IRQn, SEL_BUTTON_EXTI_IRQn};
USART_TypeDef* COM_USART[COMn] = {EVAL_COM1, EVAL_COM2};
GPIO_TypeDef* COM_TX_PORT[COMn] = {EVAL_COM1_TX_GPIO_PORT, EVAL_COM2_TX_GPIO_PORT};
GPIO_TypeDef* COM_RX_PORT[COMn] = {EVAL_COM1_RX_GPIO_PORT, EVAL_COM2_RX_GPIO_PORT};
const uint32_t COM_USART_CLK[COMn] = {EVAL_COM1_CLK, EVAL_COM2_CLK};
const uint32_t COM_TX_PORT_CLK[COMn] = {EVAL_COM1_TX_GPIO_CLK, EVAL_COM2_TX_GPIO_CLK};
const uint32_t COM_RX_PORT_CLK[COMn] = {EVAL_COM1_RX_GPIO_CLK, EVAL_COM2_RX_GPIO_CLK};
const uint16_t COM_TX_PIN[COMn] = {EVAL_COM1_TX_PIN, EVAL_COM2_TX_PIN};
const uint16_t COM_RX_PIN[COMn] = {EVAL_COM1_RX_PIN, EVAL_COM2_RX_PIN};
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32100B_EVAL_LOW_LEVEL_Private_Functions
* @{
*/
/**
* @brief Configures LED GPIO.
* @param Led: Specifies the Led to be configured.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDInit(Led_TypeDef Led)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable the GPIO_LED Clock */
RCC_APB2PeriphClockCmd(GPIO_CLK[Led], ENABLE);
/* Configure the GPIO_LED pin */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN[Led];
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIO_PORT[Led], &GPIO_InitStructure);
}
/**
* @brief Turns selected LED On.
* @param Led: Specifies the Led to be set on.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOn(Led_TypeDef Led)
{
GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}
/**
* @brief Turns selected LED Off.
* @param Led: Specifies the Led to be set off.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOff(Led_TypeDef Led)
{
GPIO_PORT[Led]->BRR = GPIO_PIN[Led];
}
/**
* @brief Toggles the selected LED.
* @param Led: Specifies the Led to be toggled.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDToggle(Led_TypeDef Led)
{
GPIO_PORT[Led]->ODR ^= GPIO_PIN[Led];
}
/**
* @brief Configures Button GPIO and EXTI Line.
* @param Button: Specifies the Button to be configured.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @param Button_Mode: Specifies Button mode.
* This parameter can be one of following parameters:
* @arg BUTTON_MODE_GPIO: Button will be used as simple IO
* @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
* generation capability
* @retval None
*/
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the BUTTON Clock */
RCC_APB2PeriphClockCmd(BUTTON_CLK[Button] | RCC_APB2Periph_AFIO, ENABLE);
/* Configure Button pin as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN[Button];
GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStructure);
if (Button_Mode == BUTTON_MODE_EXTI)
{
/* Connect Button EXTI Line to Button GPIO Pin */
GPIO_EXTILineConfig(BUTTON_PORT_SOURCE[Button], BUTTON_PIN_SOURCE[Button]);
/* Configure Button EXTI line */
EXTI_InitStructure.EXTI_Line = BUTTON_EXTI_LINE[Button];
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
if(Button != BUTTON_WAKEUP)
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
}
else
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
}
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set Button EXTI Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = BUTTON_IRQn[Button];
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
}
/**
* @brief Returns the selected Button state.
* @param Button: Specifies the Button to be checked.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @retval The Button GPIO pin value.
*/
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button)
{
return GPIO_ReadInputDataBit(BUTTON_PORT[Button], BUTTON_PIN[Button]);
}
/**
* @brief Configures COM port.
* @param COM: Specifies the COM port to be configured.
* This parameter can be one of following parameters:
* @arg COM1
* @arg COM2
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure that
* contains the configuration information for the specified USART peripheral.
* @retval None
*/
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_APB2PeriphClockCmd(COM_TX_PORT_CLK[COM] | COM_RX_PORT_CLK[COM] | RCC_APB2Periph_AFIO, ENABLE);
/* Enable UART clock */
if (COM == COM1)
{
RCC_APB2PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
else
{
/* Enable the USART2 Pins Software Remapping */
GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);
RCC_APB1PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = COM_TX_PIN[COM];
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = COM_RX_PIN[COM];
GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);
/* USART configuration */
USART_Init(COM_USART[COM], USART_InitStruct);
/* Enable USART */
USART_Cmd(COM_USART[COM], ENABLE);
}
/**
* @brief DeInitializes the SD/SD communication.
* @param None
* @retval None
*/
void SD_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_Cmd(SD_SPI, DISABLE); /*!< SD_SPI disable */
SPI_I2S_DeInit(SD_SPI); /*!< DeInitializes the SD_SPI */
/*!< SD_SPI Periph clock disable */
RCC_APB2PeriphClockCmd(SD_SPI_CLK, DISABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the SD_SPI and CS pins.
* @param None
* @retval None
*/
void SD_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
/*!< SD_SPI_CS_GPIO, SD_SPI_MOSI_GPIO, SD_SPI_MISO_GPIO, SD_SPI_DETECT_GPIO
and SD_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(SD_CS_GPIO_CLK | SD_SPI_MOSI_GPIO_CLK | SD_SPI_MISO_GPIO_CLK |
SD_SPI_SCK_GPIO_CLK | SD_DETECT_GPIO_CLK, ENABLE);
/*!< SD_SPI Periph clock enable */
RCC_APB2PeriphClockCmd(SD_SPI_CLK, ENABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
/*!< SD_SPI Config */
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SD_SPI, &SPI_InitStructure);
SPI_Cmd(SD_SPI, ENABLE); /*!< SD_SPI enable */
}
/**
* @brief DeInitializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable the sFLASH_SPI */
SPI_Cmd(sFLASH_SPI, DISABLE);
/*!< DeInitializes the sFLASH_SPI */
SPI_I2S_DeInit(sFLASH_SPI);
/*!< sFLASH_SPI Periph clock disable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, DISABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< sFLASH_SPI_CS_GPIO, sFLASH_SPI_MOSI_GPIO, sFLASH_SPI_MISO_GPIO
and sFLASH_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_CS_GPIO_CLK | sFLASH_SPI_MOSI_GPIO_CLK | sFLASH_SPI_MISO_GPIO_CLK |
sFLASH_SPI_SCK_GPIO_CLK, ENABLE);
/*!< sFLASH_SPI Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, ENABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief DeInitializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable LM75_I2C */
I2C_Cmd(LM75_I2C, DISABLE);
/*!< DeInitializes the LM75_I2C */
I2C_DeInit(LM75_I2C);
/*!< LM75_I2C Periph clock disable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, DISABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the LM75_I2C..
* @param None
* @retval None
*/
void LM75_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< LM75_I2C Periph clock enable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, ENABLE);
/*!< LM75_I2C_SCL_GPIO_CLK, LM75_I2C_SDA_GPIO_CLK
and LM75_I2C_SMBUSALERT_GPIO_CLK Periph clock enable */
RCC_APB2PeriphClockCmd(LM75_I2C_SCL_GPIO_CLK | LM75_I2C_SDA_GPIO_CLK |
LM75_I2C_SMBUSALERT_GPIO_CLK, ENABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM32100B_EVAL/stm32100b_eval.c
|
C
|
asf20
| 21,232
|
/**
******************************************************************************
* @file stm3210b_eval_lcd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the stm3210b_eval_lcd
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210B_EVAL_LCD_H
#define __STM3210B_EVAL_LCD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "../Common/fonts.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210B_EVAL
* @{
*/
/** @addtogroup STM3210B_EVAL_LCD
* @{
*/
/** @defgroup STM3210B_EVAL_LCD_Exported_Types
* @{
*/
typedef struct
{
int16_t X;
int16_t Y;
} Point, * pPoint;
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LCD_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line below if you want to use LCD_DrawBMP function to
* display a bitmap picture on the LCD. This function assumes that the bitmap
* file is loaded in the SPI Flash (mounted on STM3210B-EVAL board), however
* user can tailor it according to his application hardware requirement.
*/
/*#define USE_LCD_DrawBMP*/
/**
* @brief Uncomment the line below if you want to use user defined Delay function
* (for precise timing), otherwise default _delay_ function defined within
* this driver is used (less precise timing).
*/
/* #define USE_Delay */
#ifdef USE_Delay
#include "main.h"
#define _delay_ Delay /* !< User can provide more timing precise _delay_ function
(with 10ms time base), using SysTick for example */
#else
#define _delay_ delay /* !< Default _delay_ function with less precise timing */
#endif
/**
* @brief LCD Control pins
*/
#define LCD_NCS_PIN GPIO_Pin_2
#define LCD_NCS_GPIO_PORT GPIOB
#define LCD_NCS_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_NWR_PIN GPIO_Pin_15
#define LCD_NWR_GPIO_PORT GPIOD
#define LCD_NWR_GPIO_CLK RCC_APB2Periph_GPIOD
#define LCD_RS_PIN GPIO_Pin_7
#define LCD_RS_GPIO_PORT GPIOD
#define LCD_RS_GPIO_CLK RCC_APB2Periph_GPIOD
/**
* @brief LCD SPI Interface pins
*/
#define LCD_SPI SPI2
#define LCD_SPI_CLK RCC_APB1Periph_SPI2
#define LCD_SPI_SCK_PIN GPIO_Pin_13
#define LCD_SPI_SCK_GPIO_PORT GPIOB
#define LCD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_SPI_MISO_PIN GPIO_Pin_14
#define LCD_SPI_MISO_GPIO_PORT GPIOB
#define LCD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOB
#define LCD_SPI_MOSI_PIN GPIO_Pin_15
#define LCD_SPI_MOSI_GPIO_PORT GPIOB
#define LCD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @brief LCD Registers
*/
#define LCD_REG_0 0x00
#define LCD_REG_1 0x01
#define LCD_REG_2 0x02
#define LCD_REG_3 0x03
#define LCD_REG_4 0x04
#define LCD_REG_5 0x05
#define LCD_REG_6 0x06
#define LCD_REG_7 0x07
#define LCD_REG_8 0x08
#define LCD_REG_9 0x09
#define LCD_REG_10 0x0A
#define LCD_REG_12 0x0C
#define LCD_REG_13 0x0D
#define LCD_REG_14 0x0E
#define LCD_REG_15 0x0F
#define LCD_REG_16 0x10
#define LCD_REG_17 0x11
#define LCD_REG_18 0x12
#define LCD_REG_19 0x13
#define LCD_REG_20 0x14
#define LCD_REG_21 0x15
#define LCD_REG_22 0x16
#define LCD_REG_23 0x17
#define LCD_REG_24 0x18
#define LCD_REG_25 0x19
#define LCD_REG_26 0x1A
#define LCD_REG_27 0x1B
#define LCD_REG_28 0x1C
#define LCD_REG_29 0x1D
#define LCD_REG_30 0x1E
#define LCD_REG_31 0x1F
#define LCD_REG_32 0x20
#define LCD_REG_33 0x21
#define LCD_REG_34 0x22
#define LCD_REG_36 0x24
#define LCD_REG_37 0x25
#define LCD_REG_40 0x28
#define LCD_REG_41 0x29
#define LCD_REG_43 0x2B
#define LCD_REG_45 0x2D
#define LCD_REG_48 0x30
#define LCD_REG_49 0x31
#define LCD_REG_50 0x32
#define LCD_REG_51 0x33
#define LCD_REG_52 0x34
#define LCD_REG_53 0x35
#define LCD_REG_54 0x36
#define LCD_REG_55 0x37
#define LCD_REG_56 0x38
#define LCD_REG_57 0x39
#define LCD_REG_59 0x3B
#define LCD_REG_60 0x3C
#define LCD_REG_61 0x3D
#define LCD_REG_62 0x3E
#define LCD_REG_63 0x3F
#define LCD_REG_64 0x40
#define LCD_REG_65 0x41
#define LCD_REG_66 0x42
#define LCD_REG_67 0x43
#define LCD_REG_68 0x44
#define LCD_REG_69 0x45
#define LCD_REG_70 0x46
#define LCD_REG_71 0x47
#define LCD_REG_72 0x48
#define LCD_REG_73 0x49
#define LCD_REG_74 0x4A
#define LCD_REG_75 0x4B
#define LCD_REG_76 0x4C
#define LCD_REG_77 0x4D
#define LCD_REG_78 0x4E
#define LCD_REG_79 0x4F
#define LCD_REG_80 0x50
#define LCD_REG_81 0x51
#define LCD_REG_82 0x52
#define LCD_REG_83 0x53
#define LCD_REG_96 0x60
#define LCD_REG_97 0x61
#define LCD_REG_106 0x6A
#define LCD_REG_118 0x76
#define LCD_REG_128 0x80
#define LCD_REG_129 0x81
#define LCD_REG_130 0x82
#define LCD_REG_131 0x83
#define LCD_REG_132 0x84
#define LCD_REG_133 0x85
#define LCD_REG_134 0x86
#define LCD_REG_135 0x87
#define LCD_REG_136 0x88
#define LCD_REG_137 0x89
#define LCD_REG_139 0x8B
#define LCD_REG_140 0x8C
#define LCD_REG_141 0x8D
#define LCD_REG_143 0x8F
#define LCD_REG_144 0x90
#define LCD_REG_145 0x91
#define LCD_REG_146 0x92
#define LCD_REG_147 0x93
#define LCD_REG_148 0x94
#define LCD_REG_149 0x95
#define LCD_REG_150 0x96
#define LCD_REG_151 0x97
#define LCD_REG_152 0x98
#define LCD_REG_153 0x99
#define LCD_REG_154 0x9A
#define LCD_REG_157 0x9D
#define LCD_REG_192 0xC0
#define LCD_REG_193 0xC1
#define LCD_REG_227 0xE3
#define LCD_REG_229 0xE5
#define LCD_REG_231 0xE7
#define LCD_REG_239 0xEF
/**
* @brief LCD color
*/
#define LCD_COLOR_WHITE 0xFFFF
#define LCD_COLOR_BLACK 0x0000
#define LCD_COLOR_GREY 0xF7DE
#define LCD_COLOR_BLUE 0x001F
#define LCD_COLOR_BLUE2 0x051F
#define LCD_COLOR_RED 0xF800
#define LCD_COLOR_MAGENTA 0xF81F
#define LCD_COLOR_GREEN 0x07E0
#define LCD_COLOR_CYAN 0x7FFF
#define LCD_COLOR_YELLOW 0xFFE0
/**
* @brief LCD Lines depending on the chosen fonts.
*/
#define LCD_LINE_0 LINE(0)
#define LCD_LINE_1 LINE(1)
#define LCD_LINE_2 LINE(2)
#define LCD_LINE_3 LINE(3)
#define LCD_LINE_4 LINE(4)
#define LCD_LINE_5 LINE(5)
#define LCD_LINE_6 LINE(6)
#define LCD_LINE_7 LINE(7)
#define LCD_LINE_8 LINE(8)
#define LCD_LINE_9 LINE(9)
#define LCD_LINE_10 LINE(10)
#define LCD_LINE_11 LINE(11)
#define LCD_LINE_12 LINE(12)
#define LCD_LINE_13 LINE(13)
#define LCD_LINE_14 LINE(14)
#define LCD_LINE_15 LINE(15)
#define LCD_LINE_16 LINE(16)
#define LCD_LINE_17 LINE(17)
#define LCD_LINE_18 LINE(18)
#define LCD_LINE_19 LINE(19)
#define LCD_LINE_20 LINE(20)
#define LCD_LINE_21 LINE(21)
#define LCD_LINE_22 LINE(22)
#define LCD_LINE_23 LINE(23)
#define LCD_LINE_24 LINE(24)
#define LCD_LINE_25 LINE(25)
#define LCD_LINE_26 LINE(26)
#define LCD_LINE_27 LINE(27)
#define LCD_LINE_28 LINE(28)
#define LCD_LINE_29 LINE(29)
/**
* @brief LCD default font
*/
#define LCD_DEFAULT_FONT Font16x24
/**
* @brief LCD Direction
*/
#define LCD_DIR_HORIZONTAL 0x0000
#define LCD_DIR_VERTICAL 0x0001
/**
* @brief LCD Size (Width and Height)
*/
#define LCD_PIXEL_WIDTH 0x0140
#define LCD_PIXEL_HEIGHT 0x00F0
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LCD_Exported_Macros
* @{
*/
#define ASSEMBLE_RGB(R, G, B) ((((R)& 0xF8) << 8) | (((G) & 0xFC) << 3) | (((B) & 0xF8) >> 3))
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LCD_Exported_Functions
* @{
*/
void LCD_DeInit(void);
void LCD_Setup(void);
void STM3210B_LCD_Init(void);
void LCD_SetColors(__IO uint16_t _TextColor, __IO uint16_t _BackColor);
void LCD_GetColors(__IO uint16_t *_TextColor, __IO uint16_t *_BackColor);
void LCD_SetTextColor(__IO uint16_t Color);
void LCD_SetBackColor(__IO uint16_t Color);
void LCD_ClearLine(uint8_t Line);
void LCD_Clear(uint16_t Color);
void LCD_SetCursor(uint8_t Xpos, uint16_t Ypos);
void LCD_DrawChar(uint8_t Xpos, uint16_t Ypos, const uint16_t *c);
void LCD_DisplayChar(uint8_t Line, uint16_t Column, uint8_t Ascii);
void LCD_SetFont(sFONT *fonts);
sFONT *LCD_GetFont(void);
void LCD_DisplayStringLine(uint8_t Line, uint8_t *ptr);
void LCD_SetDisplayWindow(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_WindowModeDisable(void);
void LCD_DrawLine(uint8_t Xpos, uint16_t Ypos, uint16_t Length, uint8_t Direction);
void LCD_DrawRect(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_DrawCircle(uint8_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_DrawMonoPict(const uint32_t *Pict);
void LCD_DrawBMP(uint32_t BmpAddress);
void LCD_DrawUniLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
void LCD_DrawFullRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height);
void LCD_DrawFullCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_PolyLine(pPoint Points, uint16_t PointCount);
void LCD_PolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLine(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_FillPolyLine(pPoint Points, uint16_t PointCount);
void LCD_nCS_StartByte(uint8_t Start_Byte);
void LCD_WriteRegIndex(uint8_t LCD_Reg);
void LCD_WriteReg(uint8_t LCD_Reg, uint16_t LCD_RegValue);
void LCD_WriteRAM_Prepare(void);
void LCD_WriteRAMWord(uint16_t RGB_Code);
uint16_t LCD_ReadReg(uint8_t LCD_Reg);
void LCD_WriteRAM(uint16_t RGB_Code);
void LCD_PowerOn(void);
void LCD_DisplayOn(void);
void LCD_DisplayOff(void);
void LCD_CtrlLinesConfig(void);
void LCD_CtrlLinesWrite(GPIO_TypeDef* GPIOx, uint16_t CtrlPins, BitAction BitVal);
void LCD_SPIConfig(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM3210B_EVAL_LCD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210B_EVAL/stm3210b_eval_lcd.h
|
C
|
asf20
| 12,898
|
/**
******************************************************************************
* @file stm3210b_eval.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains definitions for STM3210B_EVAL's Leds, push-buttons
* COM ports, SD Card (on SPI), sFLASH (on SPI) and Temperature sensor
* LM75 (on I2C) hardware resources.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210B_EVAL_H
#define __STM3210B_EVAL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_i2c.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210B_EVAL
* @{
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL
* @{
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Exported_Constants
* @{
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_LED
* @{
*/
#define LEDn 4
#define LED1_PIN GPIO_Pin_6
#define LED1_GPIO_PORT GPIOC
#define LED1_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED2_PIN GPIO_Pin_7
#define LED2_GPIO_PORT GPIOC
#define LED2_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED3_PIN GPIO_Pin_8
#define LED3_GPIO_PORT GPIOC
#define LED3_GPIO_CLK RCC_APB2Periph_GPIOC
#define LED4_PIN GPIO_Pin_9
#define LED4_GPIO_PORT GPIOC
#define LED4_GPIO_CLK RCC_APB2Periph_GPIOC
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_BUTTON
* @{
*/
#define BUTTONn 8
/**
* @brief Wakeup push-button
*/
#define WAKEUP_BUTTON_PIN GPIO_Pin_0
#define WAKEUP_BUTTON_GPIO_PORT GPIOA
#define WAKEUP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOA
#define WAKEUP_BUTTON_EXTI_LINE EXTI_Line0
#define WAKEUP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOA
#define WAKEUP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define WAKEUP_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Tamper push-button
*/
#define TAMPER_BUTTON_PIN GPIO_Pin_13
#define TAMPER_BUTTON_GPIO_PORT GPIOC
#define TAMPER_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOC
#define TAMPER_BUTTON_EXTI_LINE EXTI_Line13
#define TAMPER_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOC
#define TAMPER_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource13
#define TAMPER_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Key push-button
*/
#define KEY_BUTTON_PIN GPIO_Pin_9
#define KEY_BUTTON_GPIO_PORT GPIOB
#define KEY_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOB
#define KEY_BUTTON_EXTI_LINE EXTI_Line9
#define KEY_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOB
#define KEY_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource9
#define KEY_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @brief Joystick Right push-button
*/
#define RIGHT_BUTTON_PIN GPIO_Pin_0
#define RIGHT_BUTTON_GPIO_PORT GPIOE
#define RIGHT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOE
#define RIGHT_BUTTON_EXTI_LINE EXTI_Line0
#define RIGHT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOE
#define RIGHT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define RIGHT_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Joystick Left push-button
*/
#define LEFT_BUTTON_PIN GPIO_Pin_1
#define LEFT_BUTTON_GPIO_PORT GPIOE
#define LEFT_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOE
#define LEFT_BUTTON_EXTI_LINE EXTI_Line1
#define LEFT_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOE
#define LEFT_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource1
#define LEFT_BUTTON_EXTI_IRQn EXTI1_IRQn
/**
* @brief Joystick Up push-button
*/
#define UP_BUTTON_PIN GPIO_Pin_8
#define UP_BUTTON_GPIO_PORT GPIOD
#define UP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define UP_BUTTON_EXTI_LINE EXTI_Line8
#define UP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define UP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource8
#define UP_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @brief Joystick Down push-button
*/
#define DOWN_BUTTON_PIN GPIO_Pin_14
#define DOWN_BUTTON_GPIO_PORT GPIOD
#define DOWN_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define DOWN_BUTTON_EXTI_LINE EXTI_Line14
#define DOWN_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define DOWN_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource14
#define DOWN_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Joystick Sel push-button
*/
#define SEL_BUTTON_PIN GPIO_Pin_12
#define SEL_BUTTON_GPIO_PORT GPIOD
#define SEL_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOD
#define SEL_BUTTON_EXTI_LINE EXTI_Line12
#define SEL_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOD
#define SEL_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource12
#define SEL_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_COM
* @{
*/
#define COMn 2
/**
* @brief Definition for COM port1, connected to USART1
*/
#define EVAL_COM1 USART1
#define EVAL_COM1_CLK RCC_APB2Periph_USART1
#define EVAL_COM1_TX_PIN GPIO_Pin_9
#define EVAL_COM1_TX_GPIO_PORT GPIOA
#define EVAL_COM1_TX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_RX_PIN GPIO_Pin_10
#define EVAL_COM1_RX_GPIO_PORT GPIOA
#define EVAL_COM1_RX_GPIO_CLK RCC_APB2Periph_GPIOA
#define EVAL_COM1_IRQn USART1_IRQn
/**
* @brief Definition for COM port2, connected to USART2 (USART2 pins remapped on GPIOD)
*/
#define EVAL_COM2 USART2
#define EVAL_COM2_CLK RCC_APB1Periph_USART2
#define EVAL_COM2_TX_PIN GPIO_Pin_5
#define EVAL_COM2_TX_GPIO_PORT GPIOD
#define EVAL_COM2_TX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM2_RX_PIN GPIO_Pin_6
#define EVAL_COM2_RX_GPIO_PORT GPIOD
#define EVAL_COM2_RX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM2_IRQn USART2_IRQn
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_SD_SPI
* @{
*/
/**
* @brief SD SPI Interface pins
*/
#define SD_SPI SPI1
#define SD_SPI_CLK RCC_APB2Periph_SPI1
#define SD_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */
#define SD_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */
#define SD_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */
#define SD_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */
#define SD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_CS_PIN GPIO_Pin_12 /* PC.12 */
#define SD_CS_GPIO_PORT GPIOC /* GPIOC */
#define SD_CS_GPIO_CLK RCC_APB2Periph_GPIOC
#define SD_DETECT_PIN GPIO_Pin_7 /* PE.07 */
#define SD_DETECT_GPIO_PORT GPIOE /* GPIOE */
#define SD_DETECT_GPIO_CLK RCC_APB2Periph_GPIOE
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_M25P_FLASH_SPI
* @{
*/
/**
* @brief M25P FLASH SPI Interface pins
*/
#define sFLASH_SPI SPI1
#define sFLASH_SPI_CLK RCC_APB2Periph_SPI1
#define sFLASH_SPI_SCK_PIN GPIO_Pin_5 /* PA.05 */
#define sFLASH_SPI_SCK_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MISO_PIN GPIO_Pin_6 /* PA.06 */
#define sFLASH_SPI_MISO_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_SPI_MOSI_PIN GPIO_Pin_7 /* PA.07 */
#define sFLASH_SPI_MOSI_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOA
#define sFLASH_CS_PIN GPIO_Pin_4 /* PA.04 */
#define sFLASH_CS_GPIO_PORT GPIOA /* GPIOA */
#define sFLASH_CS_GPIO_CLK RCC_APB2Periph_GPIOA
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_LOW_LEVEL_TSENSOR_I2C
* @{
*/
/**
* @brief LM75 Temperature Sensor I2C Interface pins
*/
#define LM75_I2C I2C1
#define LM75_I2C_CLK RCC_APB1Periph_I2C1
#define LM75_I2C_SCL_PIN GPIO_Pin_6 /* PB.06 */
#define LM75_I2C_SCL_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SCL_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SDA_PIN GPIO_Pin_7 /* PB.07 */
#define LM75_I2C_SDA_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SDA_GPIO_CLK RCC_APB2Periph_GPIOB
#define LM75_I2C_SMBUSALERT_PIN GPIO_Pin_5 /* PB.05 */
#define LM75_I2C_SMBUSALERT_GPIO_PORT GPIOB /* GPIOB */
#define LM75_I2C_SMBUSALERT_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @}
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Exported_Functions
* @{
*/
void STM_EVAL_LEDInit(Led_TypeDef Led);
void STM_EVAL_LEDOn(Led_TypeDef Led);
void STM_EVAL_LEDOff(Led_TypeDef Led);
void STM_EVAL_LEDToggle(Led_TypeDef Led);
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode);
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button);
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct);
void SD_LowLevel_DeInit(void);
void SD_LowLevel_Init(void);
void sFLASH_LowLevel_DeInit(void);
void sFLASH_LowLevel_Init(void);
void LM75_LowLevel_DeInit(void);
void LM75_LowLevel_Init(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM3210B_EVAL_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210B_EVAL/stm3210b_eval.h
|
C
|
asf20
| 12,054
|
/**
******************************************************************************
* @file stm3210b_eval.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides
* - set of firmware functions to manage Leds, push-button and COM ports
* - low level initialization functions for SD card (on SPI), SPI serial
* flash (sFLASH) and temperature sensor (LM75)
* available on STM3210B-EVAL evaluation board from STMicroelectronics.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210b_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210B_EVAL
* @{
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL
* @brief This file provides firmware functions to manage Leds, push-buttons,
* COM ports, SD card on SPI, serial flash (sFLASH), serial EEPROM (sEE)
* and temperature sensor (LM75) available on STM3210B-EVAL evaluation
* board from STMicroelectronics.
* @{
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_Variables
* @{
*/
GPIO_TypeDef* GPIO_PORT[LEDn] = {LED1_GPIO_PORT, LED2_GPIO_PORT, LED3_GPIO_PORT,
LED4_GPIO_PORT};
const uint16_t GPIO_PIN[LEDn] = {LED1_PIN, LED2_PIN, LED3_PIN,
LED4_PIN};
const uint32_t GPIO_CLK[LEDn] = {LED1_GPIO_CLK, LED2_GPIO_CLK, LED3_GPIO_CLK,
LED4_GPIO_CLK};
GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {WAKEUP_BUTTON_GPIO_PORT, TAMPER_BUTTON_GPIO_PORT,
KEY_BUTTON_GPIO_PORT, RIGHT_BUTTON_GPIO_PORT,
LEFT_BUTTON_GPIO_PORT, UP_BUTTON_GPIO_PORT,
DOWN_BUTTON_GPIO_PORT, SEL_BUTTON_GPIO_PORT};
const uint16_t BUTTON_PIN[BUTTONn] = {WAKEUP_BUTTON_PIN, TAMPER_BUTTON_PIN,
KEY_BUTTON_PIN, RIGHT_BUTTON_PIN,
LEFT_BUTTON_PIN, UP_BUTTON_PIN,
DOWN_BUTTON_PIN, SEL_BUTTON_PIN};
const uint32_t BUTTON_CLK[BUTTONn] = {WAKEUP_BUTTON_GPIO_CLK, TAMPER_BUTTON_GPIO_CLK,
KEY_BUTTON_GPIO_CLK, RIGHT_BUTTON_GPIO_CLK,
LEFT_BUTTON_GPIO_CLK, UP_BUTTON_GPIO_CLK,
DOWN_BUTTON_GPIO_CLK, SEL_BUTTON_GPIO_CLK};
const uint16_t BUTTON_EXTI_LINE[BUTTONn] = {WAKEUP_BUTTON_EXTI_LINE,
TAMPER_BUTTON_EXTI_LINE,
KEY_BUTTON_EXTI_LINE,
RIGHT_BUTTON_EXTI_LINE,
LEFT_BUTTON_EXTI_LINE,
UP_BUTTON_EXTI_LINE,
DOWN_BUTTON_EXTI_LINE,
SEL_BUTTON_EXTI_LINE};
const uint16_t BUTTON_PORT_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PORT_SOURCE,
TAMPER_BUTTON_EXTI_PORT_SOURCE,
KEY_BUTTON_EXTI_PORT_SOURCE,
RIGHT_BUTTON_EXTI_PORT_SOURCE,
LEFT_BUTTON_EXTI_PORT_SOURCE,
UP_BUTTON_EXTI_PORT_SOURCE,
DOWN_BUTTON_EXTI_PORT_SOURCE,
SEL_BUTTON_EXTI_PORT_SOURCE};
const uint16_t BUTTON_PIN_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PIN_SOURCE,
TAMPER_BUTTON_EXTI_PIN_SOURCE,
KEY_BUTTON_EXTI_PIN_SOURCE,
RIGHT_BUTTON_EXTI_PIN_SOURCE,
LEFT_BUTTON_EXTI_PIN_SOURCE,
UP_BUTTON_EXTI_PIN_SOURCE,
DOWN_BUTTON_EXTI_PIN_SOURCE,
SEL_BUTTON_EXTI_PIN_SOURCE};
const uint16_t BUTTON_IRQn[BUTTONn] = {WAKEUP_BUTTON_EXTI_IRQn, TAMPER_BUTTON_EXTI_IRQn,
KEY_BUTTON_EXTI_IRQn, RIGHT_BUTTON_EXTI_IRQn,
LEFT_BUTTON_EXTI_IRQn, UP_BUTTON_EXTI_IRQn,
DOWN_BUTTON_EXTI_IRQn, SEL_BUTTON_EXTI_IRQn};
USART_TypeDef* COM_USART[COMn] = {EVAL_COM1, EVAL_COM2};
GPIO_TypeDef* COM_TX_PORT[COMn] = {EVAL_COM1_TX_GPIO_PORT, EVAL_COM2_TX_GPIO_PORT};
GPIO_TypeDef* COM_RX_PORT[COMn] = {EVAL_COM1_RX_GPIO_PORT, EVAL_COM2_RX_GPIO_PORT};
const uint32_t COM_USART_CLK[COMn] = {EVAL_COM1_CLK, EVAL_COM2_CLK};
const uint32_t COM_TX_PORT_CLK[COMn] = {EVAL_COM1_TX_GPIO_CLK, EVAL_COM2_TX_GPIO_CLK};
const uint32_t COM_RX_PORT_CLK[COMn] = {EVAL_COM1_RX_GPIO_CLK, EVAL_COM2_RX_GPIO_CLK};
const uint16_t COM_TX_PIN[COMn] = {EVAL_COM1_TX_PIN, EVAL_COM2_TX_PIN};
const uint16_t COM_RX_PIN[COMn] = {EVAL_COM1_RX_PIN, EVAL_COM2_RX_PIN};
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210B_EVAL_LOW_LEVEL_Private_Functions
* @{
*/
/**
* @brief Configures LED GPIO.
* @param Led: Specifies the Led to be configured.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDInit(Led_TypeDef Led)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable the GPIO_LED Clock */
RCC_APB2PeriphClockCmd(GPIO_CLK[Led], ENABLE);
/* Configure the GPIO_LED pin */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN[Led];
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIO_PORT[Led], &GPIO_InitStructure);
}
/**
* @brief Turns selected LED On.
* @param Led: Specifies the Led to be set on.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOn(Led_TypeDef Led)
{
GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}
/**
* @brief Turns selected LED Off.
* @param Led: Specifies the Led to be set off.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOff(Led_TypeDef Led)
{
GPIO_PORT[Led]->BRR = GPIO_PIN[Led];
}
/**
* @brief Toggles the selected LED.
* @param Led: Specifies the Led to be toggled.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDToggle(Led_TypeDef Led)
{
GPIO_PORT[Led]->ODR ^= GPIO_PIN[Led];
}
/**
* @brief Configures Button GPIO and EXTI Line.
* @param Button: Specifies the Button to be configured.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @param Button_Mode: Specifies Button mode.
* This parameter can be one of following parameters:
* @arg BUTTON_MODE_GPIO: Button will be used as simple IO
* @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
* generation capability
* @retval None
*/
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the BUTTON Clock */
RCC_APB2PeriphClockCmd(BUTTON_CLK[Button] | RCC_APB2Periph_AFIO, ENABLE);
/* Configure Button pin as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN[Button];
GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStructure);
if (Button_Mode == BUTTON_MODE_EXTI)
{
/* Connect Button EXTI Line to Button GPIO Pin */
GPIO_EXTILineConfig(BUTTON_PORT_SOURCE[Button], BUTTON_PIN_SOURCE[Button]);
/* Configure Button EXTI line */
EXTI_InitStructure.EXTI_Line = BUTTON_EXTI_LINE[Button];
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
if(Button != BUTTON_WAKEUP)
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
}
else
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
}
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set Button EXTI Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = BUTTON_IRQn[Button];
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
}
/**
* @brief Returns the selected Button state.
* @param Button: Specifies the Button to be checked.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @retval The Button GPIO pin value.
*/
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button)
{
return GPIO_ReadInputDataBit(BUTTON_PORT[Button], BUTTON_PIN[Button]);
}
/**
* @brief Configures COM port.
* @param COM: Specifies the COM port to be configured.
* This parameter can be one of following parameters:
* @arg COM1
* @arg COM2
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure that
* contains the configuration information for the specified USART peripheral.
* @retval None
*/
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_APB2PeriphClockCmd(COM_TX_PORT_CLK[COM] | COM_RX_PORT_CLK[COM] | RCC_APB2Periph_AFIO, ENABLE);
if (COM == COM1)
{
RCC_APB2PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
else
{
/* Enable the USART2 Pins Software Remapping */
GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);
RCC_APB1PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = COM_TX_PIN[COM];
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = COM_RX_PIN[COM];
GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);
/* USART configuration */
USART_Init(COM_USART[COM], USART_InitStruct);
/* Enable USART */
USART_Cmd(COM_USART[COM], ENABLE);
}
/**
* @brief DeInitializes the SD/SD communication.
* @param None
* @retval None
*/
void SD_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_Cmd(SD_SPI, DISABLE); /*!< SD_SPI disable */
SPI_I2S_DeInit(SD_SPI); /*!< DeInitializes the SD_SPI */
/*!< SD_SPI Periph clock disable */
RCC_APB2PeriphClockCmd(SD_SPI_CLK, DISABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the SD_SPI and CS pins.
* @param None
* @retval None
*/
void SD_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
/*!< SD_SPI_CS_GPIO, SD_SPI_MOSI_GPIO, SD_SPI_MISO_GPIO, SD_SPI_DETECT_GPIO
and SD_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(SD_CS_GPIO_CLK | SD_SPI_MOSI_GPIO_CLK | SD_SPI_MISO_GPIO_CLK |
SD_SPI_SCK_GPIO_CLK | SD_DETECT_GPIO_CLK, ENABLE);
/*!< SD_SPI Periph clock enable */
RCC_APB2PeriphClockCmd(SD_SPI_CLK, ENABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
/*!< SD_SPI Config */
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SD_SPI, &SPI_InitStructure);
SPI_Cmd(SD_SPI, ENABLE); /*!< SD_SPI enable */
}
/**
* @brief DeInitializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable the sFLASH_SPI */
SPI_Cmd(sFLASH_SPI, DISABLE);
/*!< DeInitializes the sFLASH_SPI */
SPI_I2S_DeInit(sFLASH_SPI);
/*!< sFLASH_SPI Periph clock disable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, DISABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the peripherals used by the SPI FLASH driver.
* @param None
* @retval None
*/
void sFLASH_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< sFLASH_SPI_CS_GPIO, sFLASH_SPI_MOSI_GPIO, sFLASH_SPI_MISO_GPIO
and sFLASH_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_CS_GPIO_CLK | sFLASH_SPI_MOSI_GPIO_CLK | sFLASH_SPI_MISO_GPIO_CLK |
sFLASH_SPI_SCK_GPIO_CLK, ENABLE);
/*!< sFLASH_SPI Periph clock enable */
RCC_APB2PeriphClockCmd(sFLASH_SPI_CLK, ENABLE);
/*!< Configure sFLASH_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(sFLASH_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MISO_PIN;
GPIO_Init(sFLASH_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = sFLASH_SPI_MOSI_PIN;
GPIO_Init(sFLASH_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sFLASH_CS_PIN pin: sFLASH Card CS pin */
GPIO_InitStructure.GPIO_Pin = sFLASH_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(sFLASH_CS_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief DeInitializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< Disable LM75_I2C */
I2C_Cmd(LM75_I2C, DISABLE);
/*!< DeInitializes the LM75_I2C */
I2C_DeInit(LM75_I2C);
/*!< LM75_I2C Periph clock disable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, DISABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the LM75_I2C.
* @param None
* @retval None
*/
void LM75_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*!< LM75_I2C Periph clock enable */
RCC_APB1PeriphClockCmd(LM75_I2C_CLK, ENABLE);
/*!< LM75_I2C_SCL_GPIO_CLK, LM75_I2C_SDA_GPIO_CLK
and LM75_I2C_SMBUSALERT_GPIO_CLK Periph clock enable */
RCC_APB2PeriphClockCmd(LM75_I2C_SCL_GPIO_CLK | LM75_I2C_SDA_GPIO_CLK |
LM75_I2C_SMBUSALERT_GPIO_CLK, ENABLE);
/*!< Configure LM75_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(LM75_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SDA_PIN;
GPIO_Init(LM75_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure LM75_I2C pin: SMBUS ALERT */
GPIO_InitStructure.GPIO_Pin = LM75_I2C_SMBUSALERT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(LM75_I2C_SMBUSALERT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210B_EVAL/stm3210b_eval.c
|
C
|
asf20
| 21,162
|
/**
******************************************************************************
* @file stm32_eval.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief STM32xx-EVAL abstraction layer.
* This file should be added to the main application to use the provided
* functions that manage Leds, push-buttons, COM ports and low level
* HW resources initialization of the different modules available on
* STM32 evaluation boards from STMicroelectronics.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @defgroup STM32_EVAL
* @brief This file provides firmware functions to manage Leds, push-buttons,
* COM ports and low level HW resources initialization of the different
* modules available on STM32 Evaluation Boards from STMicroelectronics.
* @{
*/
/** @defgroup STM32_EVAL_Abstraction_Layer
* @{
*/
#ifdef USE_STM32100B_EVAL
#include "stm32100b_eval/stm32100b_eval.c"
#elif defined USE_STM3210B_EVAL
#include "stm3210b_eval/stm3210b_eval.c"
#elif defined USE_STM3210E_EVAL
#include "stm3210e_eval/stm3210e_eval.c"
#elif defined USE_STM3210C_EVAL
#include "stm3210c_eval/stm3210c_eval.c"
#else
#error "Please select first the STM32 EVAL board to be used (in stm32_eval.h)"
#endif
/** @defgroup STM32_EVAL_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM32_EVAL_Private_Functions
* @{
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/stm32_eval.c
|
C
|
asf20
| 2,778
|
/**
******************************************************************************
* @file stm3210c_eval.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file provides
* - set of firmware functions to manage Leds, push-button and COM ports
* - low level initialization functions for SD card (on SPI) and I2C
* serial EEPROM (sEE)
* available on STM3210C-EVAL evaluation board from STMicroelectronics.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210c_eval.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_i2c.h"
#include "stm32f10x_dma.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL
* @{
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL
* @brief This file provides firmware functions to manage Leds, push-buttons,
* COM ports, SD card on SPI and EEPROM (sEE) available on STM3210C-EVAL
* evaluation board from STMicroelectronics.
* @{
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_Variables
* @{
*/
GPIO_TypeDef* GPIO_PORT[LEDn] = {LED1_GPIO_PORT, LED2_GPIO_PORT, LED3_GPIO_PORT,
LED4_GPIO_PORT};
const uint16_t GPIO_PIN[LEDn] = {LED1_PIN, LED2_PIN, LED3_PIN,
LED4_PIN};
const uint32_t GPIO_CLK[LEDn] = {LED1_GPIO_CLK, LED2_GPIO_CLK, LED3_GPIO_CLK,
LED4_GPIO_CLK};
GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {WAKEUP_BUTTON_GPIO_PORT, TAMPER_BUTTON_GPIO_PORT,
KEY_BUTTON_GPIO_PORT};
const uint16_t BUTTON_PIN[BUTTONn] = {WAKEUP_BUTTON_PIN, TAMPER_BUTTON_PIN,
KEY_BUTTON_PIN};
const uint32_t BUTTON_CLK[BUTTONn] = {WAKEUP_BUTTON_GPIO_CLK, TAMPER_BUTTON_GPIO_CLK,
KEY_BUTTON_GPIO_CLK};
const uint16_t BUTTON_EXTI_LINE[BUTTONn] = {WAKEUP_BUTTON_EXTI_LINE,
TAMPER_BUTTON_EXTI_LINE,
KEY_BUTTON_EXTI_LINE};
const uint16_t BUTTON_PORT_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PORT_SOURCE,
TAMPER_BUTTON_EXTI_PORT_SOURCE,
KEY_BUTTON_EXTI_PORT_SOURCE};
const uint16_t BUTTON_PIN_SOURCE[BUTTONn] = {WAKEUP_BUTTON_EXTI_PIN_SOURCE,
TAMPER_BUTTON_EXTI_PIN_SOURCE,
KEY_BUTTON_EXTI_PIN_SOURCE};
const uint16_t BUTTON_IRQn[BUTTONn] = {WAKEUP_BUTTON_EXTI_IRQn, TAMPER_BUTTON_EXTI_IRQn,
KEY_BUTTON_EXTI_IRQn};
USART_TypeDef* COM_USART[COMn] = {EVAL_COM1};
GPIO_TypeDef* COM_TX_PORT[COMn] = {EVAL_COM1_TX_GPIO_PORT};
GPIO_TypeDef* COM_RX_PORT[COMn] = {EVAL_COM1_RX_GPIO_PORT};
const uint32_t COM_USART_CLK[COMn] = {EVAL_COM1_CLK};
const uint32_t COM_TX_PORT_CLK[COMn] = {EVAL_COM1_TX_GPIO_CLK};
const uint32_t COM_RX_PORT_CLK[COMn] = {EVAL_COM1_RX_GPIO_CLK};
const uint16_t COM_TX_PIN[COMn] = {EVAL_COM1_TX_PIN};
const uint16_t COM_RX_PIN[COMn] = {EVAL_COM1_RX_PIN};
DMA_InitTypeDef sEEDMA_InitStructure;
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Private_Functions
* @{
*/
/**
* @brief Configures LED GPIO.
* @param Led: Specifies the Led to be configured.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDInit(Led_TypeDef Led)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable the GPIO_LED Clock */
RCC_APB2PeriphClockCmd(GPIO_CLK[Led], ENABLE);
/* Configure the GPIO_LED pin */
GPIO_InitStructure.GPIO_Pin = GPIO_PIN[Led];
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIO_PORT[Led], &GPIO_InitStructure);
}
/**
* @brief Turns selected LED On.
* @param Led: Specifies the Led to be set on.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOn(Led_TypeDef Led)
{
GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}
/**
* @brief Turns selected LED Off.
* @param Led: Specifies the Led to be set off.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDOff(Led_TypeDef Led)
{
GPIO_PORT[Led]->BRR = GPIO_PIN[Led];
}
/**
* @brief Toggles the selected LED.
* @param Led: Specifies the Led to be toggled.
* This parameter can be one of following parameters:
* @arg LED1
* @arg LED2
* @arg LED3
* @arg LED4
* @retval None
*/
void STM_EVAL_LEDToggle(Led_TypeDef Led)
{
GPIO_PORT[Led]->ODR ^= GPIO_PIN[Led];
}
/**
* @brief Configures Button GPIO and EXTI Line.
* @param Button: Specifies the Button to be configured.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @param Button_Mode: Specifies Button mode.
* This parameter can be one of following parameters:
* @arg BUTTON_MODE_GPIO: Button will be used as simple IO
* @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
* generation capability
* @retval None
*/
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the BUTTON Clock */
RCC_APB2PeriphClockCmd(BUTTON_CLK[Button] | RCC_APB2Periph_AFIO, ENABLE);
/* Configure Button pin as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN[Button];
GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStructure);
if (Button_Mode == BUTTON_MODE_EXTI)
{
/* Connect Button EXTI Line to Button GPIO Pin */
GPIO_EXTILineConfig(BUTTON_PORT_SOURCE[Button], BUTTON_PIN_SOURCE[Button]);
/* Configure Button EXTI line */
EXTI_InitStructure.EXTI_Line = BUTTON_EXTI_LINE[Button];
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
if(Button != BUTTON_WAKEUP)
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
}
else
{
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
}
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set Button EXTI Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = BUTTON_IRQn[Button];
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
}
/**
* @brief Returns the selected Button state.
* @param Button: Specifies the Button to be checked.
* This parameter can be one of following parameters:
* @arg BUTTON_WAKEUP: Wakeup Push Button
* @arg BUTTON_TAMPER: Tamper Push Button
* @arg BUTTON_KEY: Key Push Button
* @arg BUTTON_RIGHT: Joystick Right Push Button
* @arg BUTTON_LEFT: Joystick Left Push Button
* @arg BUTTON_UP: Joystick Up Push Button
* @arg BUTTON_DOWN: Joystick Down Push Button
* @arg BUTTON_SEL: Joystick Sel Push Button
* @retval The Button GPIO pin value.
*/
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button)
{
return GPIO_ReadInputDataBit(BUTTON_PORT[Button], BUTTON_PIN[Button]);
}
/**
* @brief Configures COM port.
* @param COM: Specifies the COM port to be configured.
* This parameter can be one of following parameters:
* @arg COM1
* @arg COM2
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure that
* contains the configuration information for the specified USART peripheral.
* @retval None
*/
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_APB2PeriphClockCmd(COM_TX_PORT_CLK[COM] | COM_RX_PORT_CLK[COM] | RCC_APB2Periph_AFIO, ENABLE);
if (COM == COM1)
{
/* Enable the USART2 Pins Software Remapping */
GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);
RCC_APB1PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
}
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = COM_TX_PIN[COM];
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin = COM_RX_PIN[COM];
GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);
/* USART configuration */
USART_Init(COM_USART[COM], USART_InitStruct);
/* Enable USART */
USART_Cmd(COM_USART[COM], ENABLE);
}
/**
* @brief DeInitializes the SD/SD communication.
* @param None
* @retval None
*/
void SD_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_Cmd(SD_SPI, DISABLE); /*!< SD_SPI disable */
SPI_I2S_DeInit(SD_SPI); /*!< DeInitializes the SD_SPI */
/*!< SD_SPI Periph clock disable */
RCC_APB1PeriphClockCmd(SD_SPI_CLK, DISABLE);
/*!< DeRemap SPI3 Pins */
GPIO_PinRemapConfig(GPIO_Remap_SPI3, DISABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief Initializes the SD_SPI and CS pins.
* @param None
* @retval None
*/
void SD_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
/*!< SD_SPI_CS_GPIO, SD_SPI_MOSI_GPIO, SD_SPI_MISO_GPIO, SD_SPI_DETECT_GPIO
and SD_SPI_SCK_GPIO Periph clock enable */
RCC_APB2PeriphClockCmd(SD_CS_GPIO_CLK | SD_SPI_MOSI_GPIO_CLK | SD_SPI_MISO_GPIO_CLK |
SD_SPI_SCK_GPIO_CLK | SD_DETECT_GPIO_CLK, ENABLE);
/*!< SD_SPI Periph clock enable */
RCC_APB1PeriphClockCmd(SD_SPI_CLK, ENABLE);
/*!< AFIO Periph clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
/*!< Remap SPI3 Pins */
GPIO_PinRemapConfig(GPIO_Remap_SPI3,ENABLE);
/*!< Configure SD_SPI pins: SCK */
GPIO_InitStructure.GPIO_Pin = SD_SPI_SCK_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(SD_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MISO */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MISO_PIN;
GPIO_Init(SD_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI pins: MOSI */
GPIO_InitStructure.GPIO_Pin = SD_SPI_MOSI_PIN;
GPIO_Init(SD_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure SD_SPI_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
/*!< SD_SPI Config */
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SD_SPI, &SPI_InitStructure);
SPI_Cmd(SD_SPI, ENABLE); /*!< SD_SPI enable */
}
/**
* @brief DeInitializes peripherals used by the I2C EEPROM driver.
* @param None
* @retval None
*/
void sEE_LowLevel_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* sEE_I2C Peripheral Disable */
I2C_Cmd(sEE_I2C, DISABLE);
/* sEE_I2C DeInit */
I2C_DeInit(sEE_I2C);
/*!< sEE_I2C Periph clock disable */
RCC_APB1PeriphClockCmd(sEE_I2C_CLK, DISABLE);
/*!< GPIO configuration */
/*!< Configure sEE_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = sEE_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(sEE_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sEE_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = sEE_I2C_SDA_PIN;
GPIO_Init(sEE_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/* Configure and enable I2C DMA TX Channel interrupt */
NVIC_InitStructure.NVIC_IRQChannel = sEE_I2C_DMA_TX_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = sEE_I2C_DMA_PREPRIO;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = sEE_I2C_DMA_SUBPRIO;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
/* Configure and enable I2C DMA RX Channel interrupt */
NVIC_InitStructure.NVIC_IRQChannel = sEE_I2C_DMA_RX_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = sEE_I2C_DMA_PREPRIO;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = sEE_I2C_DMA_SUBPRIO;
NVIC_Init(&NVIC_InitStructure);
/* Disable and Deinitialize the DMA channels */
DMA_Cmd(sEE_I2C_DMA_CHANNEL_TX, DISABLE);
DMA_Cmd(sEE_I2C_DMA_CHANNEL_RX, DISABLE);
DMA_DeInit(sEE_I2C_DMA_CHANNEL_TX);
DMA_DeInit(sEE_I2C_DMA_CHANNEL_RX);
}
/**
* @brief Initializes peripherals used by the I2C EEPROM driver.
* @param None
* @retval None
*/
void sEE_LowLevel_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/*!< sEE_I2C_SCL_GPIO_CLK and sEE_I2C_SDA_GPIO_CLK Periph clock enable */
RCC_APB2PeriphClockCmd(sEE_I2C_SCL_GPIO_CLK | sEE_I2C_SDA_GPIO_CLK, ENABLE);
/*!< sEE_I2C Periph clock enable */
RCC_APB1PeriphClockCmd(sEE_I2C_CLK, ENABLE);
/*!< GPIO configuration */
/*!< Configure sEE_I2C pins: SCL */
GPIO_InitStructure.GPIO_Pin = sEE_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(sEE_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/*!< Configure sEE_I2C pins: SDA */
GPIO_InitStructure.GPIO_Pin = sEE_I2C_SDA_PIN;
GPIO_Init(sEE_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/* Configure and enable I2C DMA TX Channel interrupt */
NVIC_InitStructure.NVIC_IRQChannel = sEE_I2C_DMA_TX_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = sEE_I2C_DMA_PREPRIO;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = sEE_I2C_DMA_SUBPRIO;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Configure and enable I2C DMA RX Channel interrupt */
NVIC_InitStructure.NVIC_IRQChannel = sEE_I2C_DMA_RX_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = sEE_I2C_DMA_PREPRIO;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = sEE_I2C_DMA_SUBPRIO;
NVIC_Init(&NVIC_InitStructure);
/*!< I2C DMA TX and RX channels configuration */
/* Enable the DMA clock */
RCC_AHBPeriphClockCmd(sEE_I2C_DMA_CLK, ENABLE);
/* I2C TX DMA Channel configuration */
DMA_DeInit(sEE_I2C_DMA_CHANNEL_TX);
sEEDMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)sEE_I2C_DR_Address;
sEEDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)0; /* This parameter will be configured durig communication */
sEEDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST; /* This parameter will be configured durig communication */
sEEDMA_InitStructure.DMA_BufferSize = 0xFFFF; /* This parameter will be configured durig communication */
sEEDMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
sEEDMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
sEEDMA_InitStructure.DMA_PeripheralDataSize = DMA_MemoryDataSize_Byte;
sEEDMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
sEEDMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
sEEDMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
sEEDMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(sEE_I2C_DMA_CHANNEL_TX, &sEEDMA_InitStructure);
/* I2C RX DMA Channel configuration */
DMA_DeInit(sEE_I2C_DMA_CHANNEL_RX);
DMA_Init(sEE_I2C_DMA_CHANNEL_RX, &sEEDMA_InitStructure);
/* Enable the DMA Channels Interrupts */
DMA_ITConfig(sEE_I2C_DMA_CHANNEL_TX, DMA_IT_TC, ENABLE);
DMA_ITConfig(sEE_I2C_DMA_CHANNEL_RX, DMA_IT_TC, ENABLE);
}
/**
* @brief Initializes DMA channel used by the I2C EEPROM driver.
* @param None
* @retval None
*/
void sEE_LowLevel_DMAConfig(uint32_t pBuffer, uint32_t BufferSize, uint32_t Direction)
{
/* Initialize the DMA with the new parameters */
if (Direction == sEE_DIRECTION_TX)
{
/* Configure the DMA Tx Channel with the buffer address and the buffer size */
sEEDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)pBuffer;
sEEDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
sEEDMA_InitStructure.DMA_BufferSize = (uint32_t)BufferSize;
DMA_Init(sEE_I2C_DMA_CHANNEL_TX, &sEEDMA_InitStructure);
}
else
{
/* Configure the DMA Rx Channel with the buffer address and the buffer size */
sEEDMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)pBuffer;
sEEDMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
sEEDMA_InitStructure.DMA_BufferSize = (uint32_t)BufferSize;
DMA_Init(sEE_I2C_DMA_CHANNEL_RX, &sEEDMA_InitStructure);
}
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210C_EVAL/stm3210c_eval.c
|
C
|
asf20
| 20,592
|
/**
******************************************************************************
* @file stm3210c_eval.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains definitions for STM3210C_EVAL's Leds, push-buttons
* COM ports, SD Card on SPI and sEE on I2C hardware resources.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 210 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210C_EVAL_H
#define __STM3210C_EVAL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32_eval.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL_LOW_LEVEL
* @{
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Exported_Constants
* @{
*/
/** @addtogroup STM3210C_EVAL_LOW_LEVEL_LED
* @{
*/
#define LEDn 4
#define LED1_PIN GPIO_Pin_7
#define LED1_GPIO_PORT GPIOD
#define LED1_GPIO_CLK RCC_APB2Periph_GPIOD
#define LED2_PIN GPIO_Pin_13
#define LED2_GPIO_PORT GPIOD
#define LED2_GPIO_CLK RCC_APB2Periph_GPIOD
#define LED3_PIN GPIO_Pin_3
#define LED3_GPIO_PORT GPIOD
#define LED3_GPIO_CLK RCC_APB2Periph_GPIOD
#define LED4_PIN GPIO_Pin_4
#define LED4_GPIO_PORT GPIOD
#define LED4_GPIO_CLK RCC_APB2Periph_GPIOD
/**
* @}
*/
/** @addtogroup STM3210C_EVAL_LOW_LEVEL_BUTTON
* @{
*/
#define BUTTONn 3 /*!< Joystick pins are connected to
an IO Expander (accessible through
I2C1 interface) */
/**
* @brief Wakeup push-button
*/
#define WAKEUP_BUTTON_PIN GPIO_Pin_0
#define WAKEUP_BUTTON_GPIO_PORT GPIOA
#define WAKEUP_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOA
#define WAKEUP_BUTTON_EXTI_LINE EXTI_Line0
#define WAKEUP_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOA
#define WAKEUP_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource0
#define WAKEUP_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @brief Tamper push-button
*/
#define TAMPER_BUTTON_PIN GPIO_Pin_13
#define TAMPER_BUTTON_GPIO_PORT GPIOC
#define TAMPER_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOC
#define TAMPER_BUTTON_EXTI_LINE EXTI_Line13
#define TAMPER_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOC
#define TAMPER_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource13
#define TAMPER_BUTTON_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Key push-button
*/
#define KEY_BUTTON_PIN GPIO_Pin_9
#define KEY_BUTTON_GPIO_PORT GPIOB
#define KEY_BUTTON_GPIO_CLK RCC_APB2Periph_GPIOB
#define KEY_BUTTON_EXTI_LINE EXTI_Line9
#define KEY_BUTTON_EXTI_PORT_SOURCE GPIO_PortSourceGPIOB
#define KEY_BUTTON_EXTI_PIN_SOURCE GPIO_PinSource9
#define KEY_BUTTON_EXTI_IRQn EXTI9_5_IRQn
/**
* @}
*/
/** @addtogroup STM3210C_EVAL_LOW_LEVEL_COM
* @{
*/
#define COMn 1
/**
* @brief Definition for COM port1, connected to USART2 (USART2 pins remapped on GPIOD)
*/
#define EVAL_COM1 USART2
#define EVAL_COM1_CLK RCC_APB1Periph_USART2
#define EVAL_COM1_TX_PIN GPIO_Pin_5
#define EVAL_COM1_TX_GPIO_PORT GPIOD
#define EVAL_COM1_TX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM1_RX_PIN GPIO_Pin_6
#define EVAL_COM1_RX_GPIO_PORT GPIOD
#define EVAL_COM1_RX_GPIO_CLK RCC_APB2Periph_GPIOD
#define EVAL_COM1_IRQn USART2_IRQn
/**
* @}
*/
/** @addtogroup STM3210B_EVAL_SD_SPI
* @{
*/
/**
* @brief SD SPI Interface pins
*/
#define SD_SPI SPI3
#define SD_SPI_CLK RCC_APB1Periph_SPI3
#define SD_SPI_SCK_PIN GPIO_Pin_10 /* PC.10 */
#define SD_SPI_SCK_GPIO_PORT GPIOC /* GPIOC */
#define SD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOC
#define SD_SPI_MISO_PIN GPIO_Pin_11 /* PC.11 */
#define SD_SPI_MISO_GPIO_PORT GPIOC /* GPIOC */
#define SD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOC
#define SD_SPI_MOSI_PIN GPIO_Pin_12 /* PC.12 */
#define SD_SPI_MOSI_GPIO_PORT GPIOC /* GPIOC */
#define SD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOC
#define SD_CS_PIN GPIO_Pin_4 /* PA.04 */
#define SD_CS_GPIO_PORT GPIOA /* GPIOA */
#define SD_CS_GPIO_CLK RCC_APB2Periph_GPIOA
#define SD_DETECT_PIN GPIO_Pin_0 /* PE.00 */
#define SD_DETECT_GPIO_PORT GPIOE /* GPIOE */
#define SD_DETECT_GPIO_CLK RCC_APB2Periph_GPIOE
/**
* @}
*/
/** @addtogroup STM3210C_EVAL_LOW_LEVEL_I2C_EE
* @{
*/
/**
* @brief I2C EEPROM Interface pins
*/
#define sEE_I2C I2C1
#define sEE_I2C_CLK RCC_APB1Periph_I2C1
#define sEE_I2C_SCL_PIN GPIO_Pin_6 /* PB.06 */
#define sEE_I2C_SCL_GPIO_PORT GPIOB /* GPIOB */
#define sEE_I2C_SCL_GPIO_CLK RCC_APB2Periph_GPIOB
#define sEE_I2C_SDA_PIN GPIO_Pin_7 /* PB.07 */
#define sEE_I2C_SDA_GPIO_PORT GPIOB /* GPIOB */
#define sEE_I2C_SDA_GPIO_CLK RCC_APB2Periph_GPIOB
#define sEE_M24C64_32
#define sEE_I2C_DMA DMA1
#define sEE_I2C_DMA_CHANNEL_TX DMA1_Channel6
#define sEE_I2C_DMA_CHANNEL_RX DMA1_Channel7
#define sEE_I2C_DMA_FLAG_TX_TC DMA1_IT_TC6
#define sEE_I2C_DMA_FLAG_TX_GL DMA1_IT_GL6
#define sEE_I2C_DMA_FLAG_RX_TC DMA1_IT_TC7
#define sEE_I2C_DMA_FLAG_RX_GL DMA1_IT_GL7
#define sEE_I2C_DMA_CLK RCC_AHBPeriph_DMA1
#define sEE_I2C_DR_Address ((uint32_t)0x40005410)
#define sEE_USE_DMA
#define sEE_I2C_DMA_TX_IRQn DMA1_Channel6_IRQn
#define sEE_I2C_DMA_RX_IRQn DMA1_Channel7_IRQn
#define sEE_I2C_DMA_TX_IRQHandler DMA1_Channel6_IRQHandler
#define sEE_I2C_DMA_RX_IRQHandler DMA1_Channel7_IRQHandler
#define sEE_I2C_DMA_PREPRIO 0
#define sEE_I2C_DMA_SUBPRIO 0
#define sEE_DIRECTION_TX 0
#define sEE_DIRECTION_RX 1
/**
* @}
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LOW_LEVEL_Exported_Functions
* @{
*/
void STM_EVAL_LEDInit(Led_TypeDef Led);
void STM_EVAL_LEDOn(Led_TypeDef Led);
void STM_EVAL_LEDOff(Led_TypeDef Led);
void STM_EVAL_LEDToggle(Led_TypeDef Led);
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode);
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button);
void STM_EVAL_COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct);
void SD_LowLevel_DeInit(void);
void SD_LowLevel_Init(void);
void sEE_LowLevel_DeInit(void);
void sEE_LowLevel_Init(void);
void sEE_LowLevel_DMAConfig(uint32_t pBuffer, uint32_t BufferSize, uint32_t Direction);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM3210C_EVAL_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210C_EVAL/stm3210c_eval.h
|
C
|
asf20
| 8,957
|
/**
******************************************************************************
* @file stm3210c_eval_ioe.c
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file includes the IO Expander driver for STMPE811 IO Expander
* devices.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* File Info : ---------------------------------------------------------------
SUPPORTED FEATURES:
- IO Read/write : Set/Reset and Read (Polling/Interrupt)
- Joystick: config and Read (Polling/Interrupt)
- Touch Screen Features: Single point mode (Polling/Interrupt)
- TempSensor Feature: accuracy not determined (Polling).
UNSUPPORTED FEATURES:
- Row ADC Feature is not supported (not implemented on STM3210C-EVAL board)
----------------------------------------------------------------------------*/
/* Includes ------------------------------------------------------------------*/
#include "stm3210c_eval_ioe.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL
* @{
*/
/** @defgroup STM3210C_EVAL_IOE
* @brief This file includes the IO Expander driver for STMPE811 IO Expander
* devices.
* @{
*/
/** @defgroup STM3210C_EVAL_IOE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Private_Defines
* @{
*/
#define TIMEOUT_MAX 0x1000 /*<! The value of the maximal timeout for I2C waiting loops */
#define TS_CONVERSION_DELAY 0x10000 /*<! The application should wait before ADC end of conversion.
This delay depends on the system clock frequency, the value 0x10000
is selected for system clock equal to 72 MHz. For lower frequencies
please modify the delay accordingly. */
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Private_Variables
* @{
*/
TS_STATE TS_State; /*<! The global structure holding the TS state */
uint32_t TimeOut = TIMEOUT_MAX; /*<! Value of Timeout when I2C communication fails */
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Private_FunctionPrototypes
* @{
*/
static uint16_t IOE_TS_Read_X(void);
static uint16_t IOE_TS_Read_Y(void);
static uint16_t IOE_TS_Read_Z(void);
static void IOE_GPIO_Config(void);
static void IOE_I2C_Config(void);
static void IOE_EXTI_Config(void);
#ifndef USE_Delay
static void delay(__IO uint32_t nCount);
#endif /* USE_Delay*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Private_Functions
* @{
*/
/**
* @brief Initializes and Configures the two IO_Expanders Functionalities
* (IOs, Touch Screen ..) and configures all STM3210C-EVAL necessary
* hardware (GPIOs, APB clocks ..).
* @param None
* @retval IOE_OK if all initializations done correctly. Other value if error.
*/
uint8_t IOE_Config(void)
{
/* Configure the needed pins */
IOE_GPIO_Config();
/* Read IO Expander 1 ID */
if(IOE_IsOperational(IOE_1_ADDR))
{
return IOE1_NOT_OPERATIONAL;
}
if(IOE_IsOperational(IOE_2_ADDR))
{
return IOE2_NOT_OPERATIONAL;
}
/* Generate IOExpander Software reset */
IOE_Reset(IOE_1_ADDR);
IOE_Reset(IOE_2_ADDR);
/* ---------------------- IO Expander 1 configuration --------------------- */
/* Enable the GPIO, Touch Screen and ADC functionalities */
IOE_FnctCmd(IOE_1_ADDR, IOE_IO_FCT | IOE_TS_FCT | IOE_ADC_FCT, ENABLE);
/* Configure the VBAT pin in output mode pin*/
IOE_IOPinConfig(IOE_1_ADDR, VBAT_DIV_PIN , Direction_OUT);
/* ENABLE the alternate function for IN1 pin */
IOE_IOAFConfig(IOE_1_ADDR, VBAT_DIV_PIN, ENABLE);
/* Apply the default state for the out pins */
IOE_WriteIOPin(VBAT_DIV_PIN, BitReset);
/* Configure the MEMS interrupt pins in Input mode */
IOE_IOPinConfig(IOE_2_ADDR, (uint32_t)(MEMS_INT1_PIN | MEMS_INT2_PIN), Direction_IN);
/* ENABLE the alternate function for the Joystick pins */
IOE_IOAFConfig(IOE_2_ADDR, (uint32_t)(MEMS_INT1_PIN | MEMS_INT2_PIN), ENABLE);
/* Configure the IOs to detect Falling and Rising Edges */
IOE_IOEdgeConfig(IOE_2_ADDR, (uint32_t)(MEMS_INT1_PIN | MEMS_INT2_PIN), (uint32_t)(EDGE_FALLING | EDGE_RISING));
/* Touch Screen controller configuration */
IOE_TS_Config();
/* ------------------------------------------------------------------------ */
/* ---------------------- IO Expander 2 configuration --------------------- */
/* Enable the GPIO, Temperature Sensor and ADC functionalities */
IOE_FnctCmd(IOE_2_ADDR, IOE_IO_FCT | IOE_TEMPSENS_FCT | IOE_ADC_FCT, ENABLE);
/* Configure the Audio Codec Reset pin in output mode pin*/
IOE_IOPinConfig(IOE_2_ADDR, (uint32_t)(AUDIO_RESET_PIN), Direction_OUT);
IOE_IOPinConfig(IOE_2_ADDR, (uint32_t)(MII_INT_PIN), Direction_IN);
/* ENABLE the alternate function for IN1 pin */
IOE_IOAFConfig(IOE_2_ADDR, (uint32_t)(AUDIO_RESET_PIN | MII_INT_PIN), ENABLE);
/* Apply the default state for the out pins */
IOE_WriteIOPin(AUDIO_RESET_PIN, BitReset);
IOE_WriteIOPin(MII_INT_PIN, BitReset);
/* Configure the Joystick pins in Input mode */
IOE_IOPinConfig(IOE_2_ADDR, JOY_IO_PINS , Direction_IN);
/* ENABLE the alternate function for the Joystick pins */
IOE_IOAFConfig(IOE_2_ADDR, JOY_IO_PINS, ENABLE);
/* Configure the IOs to detect Falling and Rising Edges */
IOE_IOEdgeConfig(IOE_2_ADDR, JOY_IO_PINS, (uint8_t)(EDGE_FALLING | EDGE_RISING));
/* Temperature Sensor module configuration */
IOE_TempSens_Config();
/* ------------------------------------------------------------------------ */
/* Configuration is OK */
return IOE_OK;
}
/**
* @brief Configures The selected interrupts on the IO Expanders.
* @param IOE_ITSRC_Source: the source of the interrupts. Could be one or a
* combination of the following parameters:
* @arg IOE_ITSRC_JOYSTICK: Joystick IO intputs.
* @arg IOE_ITSRC_TSC: Touch Screen interrupts.
* @arg IOE_ITSRC_INMEMS: MEMS interrupt lines.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_ITConfig(uint32_t IOE_ITSRC_Source)
{
/* Configure the Interrupt output pin to generate low level (INT_CTRL) */
IOE_ITOutConfig(Polarity_High, Type_Level);
/* Manage the Joystick Interrupts */
if (IOE_ITSRC_Source & IOE_ITSRC_JOYSTICK)
{
/* Enable the Global interrupt */
IOE_GITCmd(IOE_2_ADDR, ENABLE);
/* Enable the Joystick pins to generate interrupt (GPIO_INT_EN) */
IOE_IOITConfig(IOE_2_ADDR, IOE_JOY_IT, ENABLE);
/* Enable the Global GPIO Interrupt */
IOE_GITConfig(IOE_2_ADDR, IOE_GIT_GPIO, ENABLE);
/* Read the GPIO_IT_STA to clear all pending bits if any */
I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_INT_STA);
/* Enable the Joystick pins to generate interrupt */
IOE_IOITConfig(IOE_2_ADDR, IOE_JOY_IT, ENABLE);
/* Read the GPIO_IT_STA to clear all pending bits if any */
I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_INT_STA);
}
/* Manage the MEMS Interrupts lines */
if (IOE_ITSRC_Source & IOE_ITSRC_INMEMS)
{
/* Enable the Global interrupt */
IOE_GITCmd(IOE_1_ADDR, ENABLE);
/* Enable the pins to generate interrupt (GPIO_INT_EN) */
IOE_IOITConfig(IOE_1_ADDR, IOE_INMEMS_IT, ENABLE);
/* Enable the Global GPIO Interrupt */
IOE_GITConfig(IOE_1_ADDR, IOE_GIT_GPIO, ENABLE);
/* Read the GPIO_IT_STA to clear all pending bits if any */
I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_GPIO_INT_STA);
/* Enable the pins to generate interrupt */
IOE_IOITConfig(IOE_1_ADDR, IOE_INMEMS_IT, ENABLE);
/* Read the GPIO_IT_STA to clear all pending bits if any */
I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_GPIO_INT_STA);
}
/* Manage the Touch Screen Interrupts */
if (IOE_ITSRC_Source & IOE_ITSRC_TSC)
{
/* Enable the Global interrupt */
IOE_GITCmd(IOE_1_ADDR, ENABLE);
/* Enable the Global GPIO Interrupt */
IOE_GITConfig(IOE_1_ADDR, (uint8_t)(IOE_GIT_TOUCH | IOE_GIT_FTH | IOE_GIT_FOV), ENABLE);
/* Read the GPIO_IT_STA to clear all pending bits if any */
I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_GPIO_INT_STA);
}
/* Configure the Interrupt line as EXTI source */
IOE_EXTI_Config();
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Writes a bit value to an output IO pin.
* @param IO_Pin: The output pin to be set or reset. This parameter can be one
* of the following values:
* @arg AUDIO_RESET_PIN: Audio codec reset pin
* @arg MII_INT_PIN: Ethernet Phy MII interrupt pin
* @arg VBAT_DIV_PIN: Battery devider pin
* @param BitVal: The value to be set. This parameter can be one of the
* following values: BitSet or BitReset. See IOE_BitVal_TypeDef.
* @retval IOE_OK or PARAM_ERROR
*/
uint8_t IOE_WriteIOPin(uint8_t IO_Pin, IOE_BitValue_TypeDef BitVal)
{
uint8_t DeviceAddr = 0;
/* Get the IO expander Address according to which pin is to be controlled */
if (IO_Pin & IO1_OUT_ALL_PINS)
{
DeviceAddr = IOE_1_ADDR;
}
else if (IO_Pin & IO2_OUT_ALL_PINS)
{
DeviceAddr = IOE_2_ADDR;
}
else
{
return PARAM_ERROR;
}
/* Apply the bit value to the selected pin */
if (BitVal == BitReset)
{
/* Set the register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_CLR_PIN, IO_Pin);
}
else
{
/* Set the register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_SET_PIN, IO_Pin);
}
return IOE_OK;
}
/**
* @brief Returns the status of the selected input IO pin.
* @param IO_Pin: The input pin to be read. This parameter can be one
* of the following values:
* @arg MEMS_INT1_PIN: MEMS interrupt line 1.
* @arg MEMS_INT2_PIN: MEMS interrupt line 2.
* @arg JOY_IO_PINS: Joystick IO pins (use IOE_JoyStickGetState for these pins)
* @retval None
*/
uint8_t IOE_ReadIOPin(uint32_t IO_Pin)
{
uint8_t DeviceAddr = 0;
uint8_t tmp = 0;
if (IO_Pin & IO1_IN_ALL_PINS)
{
DeviceAddr = IOE_1_ADDR;
}
else if (IO_Pin & IO2_IN_ALL_PINS)
{
DeviceAddr = IOE_2_ADDR;
}
else
{
return PARAM_ERROR;
}
/* Get all the Pins status */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_MP_STA);
if ((tmp & (uint8_t)IO_Pin) != 0)
{
return BitSet;
}
else
{
return BitReset;
}
}
/**
* @brief Returns the current Joystick status.
* @param None
* @retval The code of the Joystick key pressed:
* @arg JOY_NONE
* @arg JOY_SEL
* @arg JOY_DOWN
* @arg JOY_LEFT
* @arg JOY_RIGHT
* @arg JOY_UP
*/
JOYState_TypeDef
IOE_JoyStickGetState(void)
{
uint8_t tmp = 0;
/* Read the status of all pins */
tmp = (uint32_t)I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_MP_STA);
/* Check the pressed keys */
if ((tmp & JOY_IO_NONE) == JOY_IO_NONE)
{
return (JOYState_TypeDef) JOY_NONE;
}
else if (!(tmp & JOY_IO_SEL))
{
return (JOYState_TypeDef) JOY_SEL;
}
else if (!(tmp & JOY_IO_DOWN))
{
return (JOYState_TypeDef) JOY_DOWN;
}
else if (!(tmp & JOY_IO_LEFT))
{
return (JOYState_TypeDef) JOY_LEFT;
}
else if (!(tmp & JOY_IO_RIGHT))
{
return (JOYState_TypeDef) JOY_RIGHT;
}
else if (!(tmp & JOY_IO_UP))
{
return (JOYState_TypeDef) JOY_UP;
}
else
{
return (JOYState_TypeDef) JOY_NONE;
}
}
/**
* @brief Returns Status and positions of the Touch screen.
* @param None
* @retval Pointer to TS_STATE structure holding Touch Screen information.
*/
TS_STATE* IOE_TS_GetState(void)
{
uint32_t xDiff, yDiff , x , y, count;
static uint32_t _x = 0, _y = 0;
/* Check if the Touch detect event happenned */
TS_State.TouchDetected = (I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_TSC_CTRL) & 0x80);
/* Wait till end of ADC conversion */
for (count = TS_CONVERSION_DELAY; count > 0; count--);
if(TS_State.TouchDetected)
{
x = IOE_TS_Read_X();
y = IOE_TS_Read_Y();
xDiff = x > _x? (x - _x): (_x - x);
yDiff = y > _y? (y - _y): (_y - y);
if (xDiff + yDiff > 5)
{
_x = x;
_y = y;
}
}
/* Update the X position */
TS_State.X = _x;
/* Update the Y position */
TS_State.Y = _y;
/* Update the Z Pression index */
TS_State.Z = IOE_TS_Read_Z();
/* Clear the interrupt pending bit and enable the FIFO again */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_FIFO_STA, 0x01);
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_FIFO_STA, 0x00);
/* Return pointer to the updated structure */
return &TS_State;
}
/**
* @brief Returns the temperature row value (in 16 bit format).
* @param None
* @retval The temperature row value.
*/
uint32_t IOE_TempSens_GetData(void)
{
static __IO uint32_t tmp = 0;
/* Aquire data enable */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_TEMP_CTRL, 0x03);
/* Enable the TEMPSENS module */
tmp = (uint32_t)((I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_TEMP_DATA) & 0x03) << 8);
tmp |= (uint32_t)I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_TEMP_DATA + 1);
tmp = (uint32_t)((33 * tmp * 100) / 751);
tmp = (uint32_t)((tmp + 5) / 10);
/* return the temprature row value */
return tmp;
}
/**
* @brief Checks the selected Global interrupt source pending bit
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param Global_IT: the Global interrupt source to be checked, could be:
* @arg Global_IT_GPIO : All IOs interrupt
* @arg Global_IT_ADC : ADC interrupt
* @arg Global_IT_TEMP : Temperature Sensor interrupts
* @arg Global_IT_FE : Touch Screen Controller FIFO Error interrupt
* @arg Global_IT_FF : Touch Screen Controller FIFO Full interrupt
* @arg Global_IT_FOV : Touch Screen Controller FIFO Overrun interrupt
* @arg Global_IT_FTH : Touch Screen Controller FIFO Threshold interrupt
* @arg Global_IT_TOUCH : Touch Screen Controller Touch Detected interrupt
* @retval Status of the checked flag. Could be SET or RESET.
*/
FlagStatus IOE_GetGITStatus(uint8_t DeviceAddr, uint8_t Global_IT)
{
__IO uint8_t tmp = 0;
/* get the Interrupt status */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_INT_STA);
if ((tmp & (uint8_t)Global_IT) != 0)
{
return SET;
}
else
{
return RESET;
}
}
/**
* @brief Clears the selected Global interrupt pending bit(s)
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param Global_IT: the Global interrupt to be cleared, could be any combination
* of the following values:
* @arg Global_IT_GPIO : All IOs interrupt
* @arg Global_IT_ADC : ADC interrupt
* @arg Global_IT_TEMP : Temperature Sensor interrupts
* @arg Global_IT_FE : Touch Screen Controller FIFO Error interrupt
* @arg Global_IT_FF : Touch Screen Controller FIFO Full interrupt
* @arg Global_IT_FOV : Touch Screen Controller FIFO Overrun interrupt
* @arg Global_IT_FTH : Touch Screen Controller FIFO Threshold interrupt
* @arg Global_IT_TOUCH : Touch Screen Controller Touch Detected interrupt
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_ClearGITPending(uint8_t DeviceAddr, uint8_t Global_IT)
{
/* Write 1 to the bits that have to be cleared */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_INT_STA, Global_IT);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Checks the status of the selected IO interrupt pending bit
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_IT: the IO interrupt to be checked could be IO_ITx Where x can be
* from 0 to 7.
* @retval Status of the checked flag. Could be SET or RESET.
*/
FlagStatus IOE_GetIOITStatus(uint8_t DeviceAddr, uint8_t IO_IT)
{
uint8_t tmp = 0;
/* get the Interrupt status */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_INT_STA);
if ((tmp & (uint8_t)IO_IT) != 0)
{
return SET;
}
else
{
return RESET;
}
}
/**
* @brief Clears the selected IO interrupt pending bit(s).
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_IT: the IO interrupt to be checked could be IO_ITx Where x can be
* from 0 to 7.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_ClearIOITPending(uint8_t DeviceAddr, uint8_t IO_IT)
{
/* Write 1 to the bits that have to be cleared */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_INT_STA, IO_IT);
/* Clear the Edge detection pending bit*/
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_ED, IO_IT);
/* Clear the Rising edge pending bit */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_RE, IO_IT);
/* Clear the Falling edge pending bit */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_GPIO_FE, IO_IT);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Checks if the selected device is correctly configured and
* communicates correctly ont the I2C bus.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @retval IOE_OK if IOE is operational. Other value if failure.
*/
uint8_t IOE_IsOperational(uint8_t DeviceAddr)
{
/* Return Error if the ID is not correct */
if( IOE_ReadID(DeviceAddr) != (uint16_t)STMPE811_ID )
{
/* Check if a Timeout occured */
if (TimeOut == 0)
{
return IOE_TIEMOUT;
}
else
{
return IOE_FAILURE; /* ID is not Correct */
}
}
else
{
return IOE_OK; /* ID is correct */
}
}
/**
* @brief Resets the IO Expander by Software (SYS_CTRL1, RESET bit).
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_Reset(uint8_t DeviceAddr)
{
/* Power Down the IO_Expander */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_SYS_CTRL1, 0x02);
/* wait for a delay to insure registers erasing */
_delay_(2);
/* Power On the Codec after the power off => all registers are reinitialized*/
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_SYS_CTRL1, 0x00);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Reads the selected device's ID.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @retval The Device ID (two bytes).
*/
uint16_t IOE_ReadID(uint8_t DeviceAddr)
{
uint16_t tmp = 0;
/* Read device ID */
tmp = I2C_ReadDeviceRegister(DeviceAddr, 0);
tmp = (uint32_t)(tmp << 8);
tmp |= (uint32_t)I2C_ReadDeviceRegister(DeviceAddr, 1);
/* Return the ID */
return (uint16_t)tmp;
}
/**
* @brief Configures the selcted IO Expander functionalities.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IOE_TEMPSENS_FCT: the functions to be configured. could be any
* combination of the following values:
* @arg IOE_IO_FCT : IO function
* @arg IOE_TS_FCT : Touch Screen function
* @arg IOE_ADC_FCT : ADC function
* @arg IOE_TEMPSENS_FCT : Tempreature Sensor function
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_FnctCmd(uint8_t DeviceAddr, uint8_t Fct, FunctionalState NewState)
{
uint8_t tmp = 0;
/* Get the register value */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_SYS_CTRL2);
if (NewState != DISABLE)
{
/* Set the Functionalities to be Enabled */
tmp &= ~(uint8_t)Fct;
}
else
{
/* Set the Functionalities to be Disabled */
tmp |= (uint8_t)Fct;
}
/* Set the register value */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_SYS_CTRL2, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Configures the selected pin direction (to be an input or an output)
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_Pin: IO_Pin_x: Where x can be from 0 to 7.
* @param Direction: could be Direction_IN or Direction_OUT.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_IOPinConfig(uint8_t DeviceAddr, uint8_t IO_Pin, uint8_t Direction)
{
uint8_t tmp = 0;
/* Get all the Pins direction */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_DIR);
if (Direction != Direction_IN)
{
tmp |= (uint8_t)IO_Pin;
}
else
{
tmp &= ~(uint8_t)IO_Pin;
}
/* Write the register new value */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_DIR, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Enables or disables the Global interrupt.
* @param DeviceAddr: The address of the IOExpander, could be :I OE_1_ADDR
* or IOE_2_ADDR.
* @param NewState: could be ENABLE or DISABLE.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_GITCmd(uint8_t DeviceAddr, FunctionalState NewState)
{
uint8_t tmp = 0;
/* Read the Interrupt Control register */
I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_INT_CTRL);
if (NewState != DISABLE)
{
/* Set the global interrupts to be Enabled */
tmp |= (uint8_t)IOE_GIT_EN;
}
else
{
/* Set the global interrupts to be Disabled */
tmp &= ~(uint8_t)IOE_GIT_EN;
}
/* Write Back the Interrupt Control register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_INT_CTRL, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Configures the selected source to generate or not a global interrupt
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param Global_IT: the interrupt source to be configured, could be:
* @arg Global_IT_GPIO : All IOs interrupt
* @arg Global_IT_ADC : ADC interrupt
* @arg Global_IT_TEMP : Temperature Sensor interrupts
* @arg Global_IT_FE : Touch Screen Controller FIFO Error interrupt
* @arg Global_IT_FF : Touch Screen Controller FIFO Full interrupt
* @arg Global_IT_FOV : Touch Screen Controller FIFO Overrun interrupt
* @arg Global_IT_FTH : Touch Screen Controller FIFO Threshold interrupt
* @arg Global_IT_TOUCH : Touch Screen Controller Touch Detected interrupt
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_GITConfig(uint8_t DeviceAddr, uint8_t Global_IT, FunctionalState NewState)
{
uint8_t tmp = 0;
/* Get the current value of the INT_EN register */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_INT_EN);
if (NewState != DISABLE)
{
/* Set the interrupts to be Enabled */
tmp |= (uint8_t)Global_IT;
}
else
{
/* Set the interrupts to be Disabled */
tmp &= ~(uint8_t)Global_IT;
}
/* Set the register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_INT_EN, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Configures the selected pins to generate an interrupt or not.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_IT: The IO interrupt to be configured. This parameter could be any
* combination of the following values:
* @arg IO_IT_x: where x can be from 0 to 7.
* @param NewState: could be ENABLE or DISABLE.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_IOITConfig(uint8_t DeviceAddr, uint8_t IO_IT, FunctionalState NewState)
{
uint8_t tmp = 0;
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_INT_EN);
if (NewState != DISABLE)
{
/* Set the interrupts to be Enabled */
tmp |= (uint8_t)IO_IT;
}
else
{
/* Set the interrupts to be Disabled */
tmp &= ~(uint8_t)IO_IT;
}
/* Set the register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_INT_EN, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Configures the touch Screen Controller (Single point detection)
* @param None
* @retval IOE_OK if all initializations are OK. Other value if error.
*/
uint8_t IOE_TS_Config(void)
{
uint8_t tmp = 0;
/* Enable TSC Fct: already done in IOE_Config */
tmp = I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_SYS_CTRL2);
tmp &= ~(uint32_t)(IOE_TS_FCT | IOE_ADC_FCT);
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_SYS_CTRL2, tmp);
/* Enable the TSC gloabl interrupts */
tmp = I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_INT_EN);
tmp |= (uint32_t)(IOE_GIT_TOUCH | IOE_GIT_FTH | IOE_GIT_FOV);
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_INT_EN, tmp);
/* Select Sample Time, bit number and ADC Reference */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_ADC_CTRL1, 0x49);
/* Wait for ~20 ms */
_delay_(2);
/* Select the ADC clock speed: 3.25 MHz */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_ADC_CTRL2, 0x01);
/* Select TSC pins in non default mode */
tmp = I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_GPIO_AF);
tmp &= ~(uint8_t)TOUCH_IO_ALL;
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_GPIO_AF, tmp);
/* Select 2 nF filter capacitor */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_TSC_CFG, 0x9A);
/* Select single point reading */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_FIFO_TH, 0x01);
/* Write 0x01 to clear the FIFO memory content. */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_FIFO_STA, 0x01);
/* Write 0x00 to put the FIFO back into operation mode */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_FIFO_STA, 0x00);
/* set the data format for Z value: 7 fractional part and 1 whole part */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_TSC_FRACT_XYZ, 0x01);
/* set the driving capability of the device for TSC pins: 50mA */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_TSC_I_DRIVE, 0x01);
/* Use no tracking index, touchscreen controller operation mode (XYZ) and
enable the TSC */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_TSC_CTRL, 0x01);
/* Clear all the status pending bits */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_INT_STA, 0xFF);
/* Initialize the TS structure to their default values */
TS_State.TouchDetected = TS_State.X = TS_State.Y = TS_State.Z = 0;
/* All configuration done */
return IOE_OK;
}
/**
* @brief Configures and enables the Temperature sensor module.
* @param None
* @retval IOE_OK if all initializations are OK. Other value if error.
*/
uint8_t IOE_TempSens_Config(void)
{
__IO uint8_t tmp = 0;
/* Enable Temperature Sensor Fct: already done in IOE_Config */
tmp = I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_SYS_CTRL2);
tmp &= ~(uint32_t)(IOE_TEMPSENS_FCT | IOE_ADC_FCT);
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_SYS_CTRL2, tmp);
/* Enable the TEMPSENS module */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_TEMP_CTRL, 0x01);
/* Aquire data enable */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_TEMP_CTRL, 0x3);
/* All configuration done */
return IOE_OK;
}
/**
* @brief Configures the selected pin to be in Alternate function or not
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_Pin: IO_Pin_x, Where x can be from 0 to 7.
* @param NewState: State of the AF for the selected pin, could be
* ENABLE or DISABLE.
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_IOAFConfig(uint8_t DeviceAddr, uint8_t IO_Pin, FunctionalState NewState)
{
uint8_t tmp = 0;
/* Get the current state of the GPIO_AF register */
tmp = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_AF);
if (NewState != DISABLE)
{
/* Enable the selected pins alternate function */
tmp |= (uint8_t)IO_Pin;
}
else
{
/* Disable the selected pins alternate function */
tmp &= ~(uint8_t)IO_Pin;
}
/* Write back the new valu in GPIO_AF register */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_AF, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Configures the Edge for which a transition is detectable for the
* the selected pin.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param IO_Pin: IO_Pin_x, Where x can be from 0 to 7.
* @param Edge: The edge which will be detected. This parameter can be one or a
* a combination of follwing values: EDGE_FALLING and EDGE_RISING .
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_IOEdgeConfig(uint8_t DeviceAddr, uint8_t IO_Pin, uint8_t Edge)
{
uint8_t tmp1 = 0, tmp2 = 0;
/* Get the registers values */
tmp1 = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_FE);
tmp2 = I2C_ReadDeviceRegister(DeviceAddr, IOE_REG_GPIO_RE);
/* Disable the Falling Edge */
tmp1 &= ~(uint8_t)IO_Pin;
/* Disable the Falling Edge */
tmp2 &= ~(uint8_t)IO_Pin;
/* Enable the Falling edge if selected */
if (Edge & EDGE_FALLING)
{
tmp1 |= (uint8_t)IO_Pin;
}
/* Enable the Rising edge if selected */
if (Edge & EDGE_RISING)
{
tmp2 |= (uint8_t)IO_Pin;
}
/* Write back the registers values */
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_FE, tmp1);
I2C_WriteDeviceRegister(DeviceAddr, IOE_REG_GPIO_RE, tmp2);
/* if OK return 0 */
return IOE_OK;
}
/**
* @brief Configures the Interrupt line active state and format (level/edge)
* @param Polarity: could be
* @arg Polarity_Low: Interrupt line is active Low/Falling edge
* @arg Polarity_High: Interrupt line is active High/Rising edge
* @param Type: Interrupt line activity type, could be one of the following values
* @arg Type_Level: Interrupt line is active in level model
* @arg Type_Edge: Interrupt line is active in edge model
* @retval IOE_OK: if all initializations are OK. Other value if error.
*/
uint8_t IOE_ITOutConfig(uint8_t Polarity, uint8_t Type)
{
uint8_t tmp = 0;
/* Get the register IOE_REG_INT_CTRL value */
tmp = I2C_ReadDeviceRegister(IOE_1_ADDR, IOE_REG_INT_CTRL);
/* Mask the polarity and type bits */
tmp &= ~(uint8_t)0x06;
/* Modify the Interrupt Output line configuration */
tmp |= (uint8_t)(Polarity | Type);
/* Set the register */
I2C_WriteDeviceRegister(IOE_1_ADDR, IOE_REG_INT_CTRL, tmp);
/* Get the register IOE_REG_INT_CTRL value */
tmp = I2C_ReadDeviceRegister(IOE_2_ADDR, IOE_REG_INT_CTRL);
/* Mask the polarity and type bits */
tmp &= ~(uint8_t)0x06;
/* Modify the Interrupt Output line configuration */
tmp |= (uint8_t)(Polarity | Type);
/* Set the register */
I2C_WriteDeviceRegister(IOE_2_ADDR, IOE_REG_INT_CTRL, tmp);
/* If all OK return IOE_OK */
return IOE_OK;
}
/**
* @brief Writes a value in a register of the device through I2C.
* @param DeviceAddr: The address of the IOExpander, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param RegisterAddr: The target register adress
* @param RegisterValue: The target register value to be written
* @retval IOE_OK: if all operations are OK. Other value if error.
*/
uint8_t I2C_WriteDeviceRegister(uint8_t DeviceAddr, uint8_t RegisterAddr, uint8_t RegisterValue)
{
uint32_t read_verif = 0;
/* Reset all I2C2 registers */
I2C_SoftwareResetCmd(IOE_I2C, ENABLE);
I2C_SoftwareResetCmd(IOE_I2C, DISABLE);
/* Enable the IOE_I2C peripheral */
I2C_Cmd(IOE_I2C, ENABLE);
/* Configure the I2C peripheral */
IOE_I2C_Config();
/* Begin the config sequence */
I2C_GenerateSTART(IOE_I2C, ENABLE);
/* Test on EV5 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Transmit the slave address and enable writing operation */
I2C_Send7bitAddress(IOE_I2C, DeviceAddr, I2C_Direction_Transmitter);
/* Test on EV6 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Transmit the first address for r/w operations */
I2C_SendData(IOE_I2C, RegisterAddr);
/* Test on EV8 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Prepare the register value to be sent */
I2C_SendData(IOE_I2C, RegisterValue);
/* Test on EV8 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* End the configuration sequence */
I2C_GenerateSTOP(IOE_I2C, ENABLE);
#ifdef VERIFY_WRITTENDATA
/* Verify (if needed) that the loaded data is correct */
/* Read the just written register*/
read_verif = I2C_ReadDeviceRegister(DeviceAddr, RegisterAddr);
/* Load the register and verify its value */
if (read_verif != RegisterValue)
{
/* Control data wrongly tranfered */
read_verif = IOE_FAILURE;
}
else
{
/* Control data correctly transfered */
read_verif = 0;
}
#endif
/* Return the verifying value: 0 (Passed) or 1 (Failed) */
return read_verif;
}
/**
* @brief Reads a register of the device through I2C.
* @param DeviceAddr: The address of the device, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param RegisterAddr: The target register adress (between 00x and 0x24)
* @retval The value of the read register (0xAA if Timout occured)
*/
uint8_t I2C_ReadDeviceRegister(uint8_t DeviceAddr, uint8_t RegisterAddr)
{
uint32_t tmp = 0;
/* Disable the IOE_I2C peripheral */
I2C_Cmd(IOE_I2C, DISABLE);
/* Reset all I2C2 registers */
I2C_SoftwareResetCmd(IOE_I2C, ENABLE);
I2C_SoftwareResetCmd(IOE_I2C, DISABLE);
/* Configure the I2C peripheral */
IOE_I2C_Config();
/* Enable the I2C peripheral */
I2C_GenerateSTART(IOE_I2C, ENABLE);
/* Test on EV5 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Disable Acknowledgement */
I2C_AcknowledgeConfig(IOE_I2C, DISABLE);
/* Transmit the slave address and enable writing operation */
I2C_Send7bitAddress(IOE_I2C, DeviceAddr, I2C_Direction_Transmitter);
/* Test on EV6 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Transmit the first address for r/w operations */
I2C_SendData(IOE_I2C, RegisterAddr);
/* Test on EV8 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Regenerate a start condition */
I2C_GenerateSTART(IOE_I2C, ENABLE);
/* Test on EV5 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_MODE_SELECT))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Transmit the slave address and enable writing operation */
I2C_Send7bitAddress(IOE_I2C, DeviceAddr, I2C_Direction_Receiver);
/* Test on EV6 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Test on EV7 and clear it */
TimeOut = TIMEOUT_MAX;
while (!I2C_CheckEvent(IOE_I2C, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* End the configuration sequence */
I2C_GenerateSTOP(IOE_I2C, ENABLE);
/* Load the register value */
tmp = I2C_ReceiveData(IOE_I2C);
/* Enable Acknowledgement */
I2C_AcknowledgeConfig(IOE_I2C, ENABLE);
/* Return the read value */
return tmp;
}
/**
* @brief Reads a buffer of 2 bytes from the device registers.
* @param DeviceAddr: The address of the device, could be : IOE_1_ADDR
* or IOE_2_ADDR.
* @param RegisterAddr: The target register adress (between 00x and 0x24)
* @retval A pointer to the buffer containing the two returned bytes (in halfword).
*/
uint16_t I2C_ReadDataBuffer(uint8_t DeviceAddr, uint32_t RegisterAddr)
{
uint8_t Buffer[2] = {0x00, 0x00};
/* Disable the I2C1 peripheral */
I2C_Cmd(I2C1, DISABLE);
/* Reset all I2C2 registers */
I2C_SoftwareResetCmd(I2C1, ENABLE);
I2C_SoftwareResetCmd(I2C1, DISABLE);
/* Configure the I2C peripheral */
IOE_I2C_Config();
/* Enable the I2C peripheral */
I2C_GenerateSTART(I2C1, ENABLE);
/* Test on EV5 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Send device address for write */
I2C_Send7bitAddress(I2C1, DeviceAddr, I2C_Direction_Transmitter);
/* Test on EV6 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Clear EV6 by setting again the PE bit */
I2C_Cmd(I2C1, ENABLE);
/* Send the device's internal address to write to */
I2C_SendData(I2C1, RegisterAddr);
/* Test on EV8 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Send STRAT condition a second time */
I2C_GenerateSTART(I2C1, ENABLE);
/* Test on EV5 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Send IOExpander address for read */
I2C_Send7bitAddress(I2C1, DeviceAddr, I2C_Direction_Receiver);
/* Test on EV6 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Test on EV7 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Read the first byte from the IOExpander */
Buffer[1] = I2C_ReceiveData(I2C1);
/* Disable Acknowledgement */
I2C_AcknowledgeConfig(I2C1, DISABLE);
/* Send STOP Condition */
I2C_GenerateSTOP(I2C1, ENABLE);
/* Test on EV7 and clear it */
TimeOut = TIMEOUT_MAX;
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
if (TimeOut-- == 0) return IOE_TIEMOUT;
}
/* Read the second byte from the IOExpander */
Buffer[0] = I2C_ReceiveData(I2C1);
/* Enable Acknowledgement to be ready for another reception */
I2C_AcknowledgeConfig(I2C1, ENABLE);
/* return a pointer to the buffer */
return *(uint16_t *)Buffer;
}
/**
* @brief Return Touch Screen X position value
* @param None
* @retval X position.
*/
static uint16_t IOE_TS_Read_X(void)
{
int32_t x, xr;
x = I2C_ReadDataBuffer(IOE_1_ADDR, IOE_REG_TSC_DATA_Y);
/* first correction */
xr = (x * 320) >> 12;
/* second correction */
xr = ((xr * 32)/29) - 17;
if(xr <= 0)
xr = 0;
return (uint16_t)(xr);
}
/**
* @brief Return Touch Screen Y position value
* @param None
* @retval Y position.
*/
static uint16_t IOE_TS_Read_Y(void)
{
int32_t y, yr;
y= I2C_ReadDataBuffer(IOE_1_ADDR, IOE_REG_TSC_DATA_X);
yr= (y * 240) >> 12;
yr = ((yr * 240) / 217) - 12;
if(yr <= 0)
yr = 0;
return (uint16_t)(yr);
}
/**
* @brief Return Touch Screen Z position value
* @param None
* @retval Z position.
*/
static uint16_t IOE_TS_Read_Z(void)
{
uint32_t z;
z = I2C_ReadDataBuffer(IOE_1_ADDR, IOE_REG_TSC_DATA_Z);
if(z <= 0)
z = 0;
return (uint16_t)(z);
}
/**
* @brief Initializes the GPIO pins used by the IO expander.
* @param None
* @retval None
*/
static void IOE_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable IOE_I2C and IOE_I2C_PORT & Alternate Function clocks */
RCC_APB1PeriphClockCmd(IOE_I2C_CLK, ENABLE);
RCC_APB2PeriphClockCmd(IOE_I2C_SCL_GPIO_CLK | IOE_I2C_SDA_GPIO_CLK | IOE_IT_GPIO_CLK
| RCC_APB2Periph_AFIO, ENABLE);
/* Reset IOE_I2C IP */
RCC_APB1PeriphResetCmd(IOE_I2C_CLK, ENABLE);
/* Release reset signal of IOE_I2C IP */
RCC_APB1PeriphResetCmd(IOE_I2C_CLK, DISABLE);
/* IOE_I2C SCL and SDA pins configuration */
GPIO_InitStructure.GPIO_Pin = IOE_I2C_SCL_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(IOE_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
/* IOE_I2C SCL and SDA pins configuration */
GPIO_InitStructure.GPIO_Pin = IOE_I2C_SDA_PIN;
GPIO_Init(IOE_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
/* Set EXTI pin as Input PullUp - IO_Expander_INT */
GPIO_InitStructure.GPIO_Pin = IOE_IT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(IOE_IT_GPIO_PORT, &GPIO_InitStructure);
/* Connect IO Expander IT line to EXTI line */
GPIO_EXTILineConfig(IOE_IT_EXTI_PORT_SOURCE, IOE_IT_EXTI_PIN_SOURCE);
}
/**
* @brief Configure the I2C Peripheral used to communicate with IO_Expanders.
* @param None
* @retval None
*/
static void IOE_I2C_Config(void)
{
I2C_InitTypeDef I2C_InitStructure;
/* IOE_I2C configuration */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = IOE_I2C_SPEED;
I2C_Init(IOE_I2C, &I2C_InitStructure);
}
/**
* @brief Configures the IO expander Interrupt line and GPIO in EXTI mode.
* @param None
* @retval None
*/
static void IOE_EXTI_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
/* Enable Button GPIO clock */
RCC_APB2PeriphClockCmd(IOE_IT_GPIO_CLK | RCC_APB2Periph_AFIO, ENABLE);
/* Configure Button pin as input floating */
GPIO_InitStructure.GPIO_Pin = IOE_IT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(IOE_IT_GPIO_PORT, &GPIO_InitStructure);
/* Connect Button EXTI Line to Button GPIO Pin */
GPIO_EXTILineConfig(IOE_IT_EXTI_PORT_SOURCE, IOE_IT_EXTI_PIN_SOURCE);
/* Configure Button EXTI line */
EXTI_InitStructure.EXTI_Line = IOE_IT_EXTI_LINE;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set Button EXTI Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = IOE_IT_EXTI_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
#ifndef USE_Delay
/**
* @brief Inserts a delay time.
* @param nCount: specifies the delay time length.
* @retval None
*/
static void delay(__IO uint32_t nCount)
{
__IO uint32_t index = 0;
for(index = (100000 * nCount); index != 0; index--)
{
}
}
#endif /* USE_Delay*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210C_EVAL/stm3210c_eval_ioe.c
|
C
|
asf20
| 46,567
|
/**
******************************************************************************
* @file stm3210c_eval_ioe.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the IO Expander
* firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* File Info : ---------------------------------------------------------------
SUPPORTED FEATURES:
- IO Read/write : Set/Reset and Read (Polling/Interrupt)
- Joystick: config and Read (Polling/Interrupt)
- Touch Screen Features: Single point mode (Polling/Interrupt)
- TempSensor Feature: accuracy not determined (Polling).
UNSUPPORTED FEATURES:
- Row ADC Feature is not supported (not implemented on STM3210C-EVAL board)
----------------------------------------------------------------------------*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210C_EVAL_IOE_H
#define __STM3210C_EVAL_IOE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL
* @{
*/
/** @defgroup STM3210C_EVAL_IOE
* @{
*/
/** @defgroup STM3210C_EVAL_IOE_Exported_Types
* @{
*/
/**
* @brief Touch Screen Information structure
*/
typedef struct
{
uint16_t TouchDetected;
uint16_t X;
uint16_t Y;
uint16_t Z;
}TS_STATE;
/**
* @brief Joystick State definitions
*/
#ifndef __STM32_EVAL_H
typedef enum
{
JOY_NONE = 0,
JOY_SEL = 1,
JOY_DOWN = 2,
JOY_LEFT = 3,
JOY_RIGHT = 4,
JOY_UP = 5
} JOYState_TypeDef
;
#endif /* __STM32_EVAL_H */
/**
* @brief IO_Expander Error codes
*/
typedef enum
{
IOE_OK = 0,
IOE_FAILURE,
IOE_TIEMOUT,
PARAM_ERROR,
IOE1_NOT_OPERATIONAL,
IOE2_NOT_OPERATIONAL
}IOE_Status_TypDef;
/**
* @brief IO bit values
*/
typedef enum
{
BitReset = 0,
BitSet = 1
}IOE_BitValue_TypeDef;
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line below to enable verfying each written byte in write
* operation. The I2C_WriteDeviceRegister() function will then compare the
* written and read data and return error status if a mismatch occurs.
*/
/* #define VERIFY_WRITTENDATA */
/**
* @brief Uncomment the line below if you want to use user defined Delay function
* (for precise timing), otherwise default _delay_ function defined within
* this driver is used (less precise timing).
*/
/* #define USE_Delay */
#ifdef USE_Delay
#include "main.h"
#define _delay_ Delay /* !< User can provide more timing precise _delay_ function
(with 10ms time base), using SysTick for example */
#else
#define _delay_ delay /* !< Default _delay_ function with less precise timing */
#endif
/*------------------------------------------------------------------------------
Hardware Configuration
------------------------------------------------------------------------------*/
/**
* @brief I2C port definitions
*/
#define IOE_I2C I2C1
#define IOE_I2C_CLK RCC_APB1Periph_I2C1
#define IOE_I2C_SCL_PIN GPIO_Pin_6
#define IOE_I2C_SCL_GPIO_PORT GPIOB
#define IOE_I2C_SCL_GPIO_CLK RCC_APB2Periph_GPIOB
#define IOE_I2C_SDA_PIN GPIO_Pin_7
#define IOE_I2C_SDA_GPIO_PORT GPIOB
#define IOE_I2C_SDA_GPIO_CLK RCC_APB2Periph_GPIOB
#define IOE_I2C_SPEED 400000
/**
* @brief IO Expander Interrupt line on EXTI
*/
#define IOE_IT_PIN GPIO_Pin_14
#define IOE_IT_GPIO_PORT GPIOB
#define IOE_IT_GPIO_CLK RCC_APB2Periph_GPIOB
#define IOE_IT_EXTI_PORT_SOURCE GPIO_PortSourceGPIOB
#define IOE_IT_EXTI_PIN_SOURCE GPIO_PinSource14
#define IOE_IT_EXTI_LINE EXTI_Line14
#define IOE_IT_EXTI_IRQn EXTI15_10_IRQn
/**
* @brief Eval Board IO Pins definition
*/
#define AUDIO_RESET_PIN IO_Pin_2 /* IO_Exapnader_2 */ /* Output */
#define MII_INT_PIN IO_Pin_0 /* IO_Exapnader_2 */ /* Output */
#define VBAT_DIV_PIN IO_Pin_0 /* IO_Exapnader_1 */ /* Output */
#define MEMS_INT1_PIN IO_Pin_3 /* IO_Exapnader_1 */ /* Input */
#define MEMS_INT2_PIN IO_Pin_2 /* IO_Exapnader_1 */ /* Input */
/**
* @brief Eval Board both IO Exapanders Pins definition
*/
#define IO1_IN_ALL_PINS (uint32_t)(MEMS_INT1_PIN | MEMS_INT2_PIN)
#define IO2_IN_ALL_PINS (uint32_t)(JOY_IO_PINS)
#define IO1_OUT_ALL_PINS (uint32_t)(VBAT_DIV_PIN)
#define IO2_OUT_ALL_PINS (uint32_t)(AUDIO_RESET_PIN | MII_INT_PIN)
/**
* @brief The 7 bits IO Expanders adresses and chip IDs
*/
#define IOE_1_ADDR 0x82
#define IOE_2_ADDR 0x88
#define STMPE811_ID 0x0811
/*------------------------------------------------------------------------------
Functional and Interrupt Management
------------------------------------------------------------------------------*/
/**
* @brief IO Expander Functionalities definitions
*/
#define IOE_ADC_FCT 0x01
#define IOE_TS_FCT 0x02
#define IOE_IO_FCT 0x04
#define IOE_TEMPSENS_FCT 0x08
/**
* @brief Interrupt source configuration definitons
*/
#define IOE_ITSRC_TSC 0x01 /* IO_Exapnder 1 */
#define IOE_ITSRC_INMEMS 0x02 /* IO_Exapnder 1 */
#define IOE_ITSRC_JOYSTICK 0x04 /* IO_Exapnder 2 */
#define IOE_ITSRC_TEMPSENS 0x08 /* IO_Exapnder 2 */
/**
* @brief Glaobal Interrupts definitions
*/
#define IOE_GIT_GPIO 0x80
#define IOE_GIT_ADC 0x40
#define IOE_GIT_TEMP 0x20
#define IOE_GIT_FE 0x10
#define IOE_GIT_FF 0x08
#define IOE_GIT_FOV 0x04
#define IOE_GIT_FTH 0x02
#define IOE_GIT_TOUCH 0x01
/*------------------------------------------------------------------------------
STMPE811 device register definition
------------------------------------------------------------------------------*/
/**
* @brief Identification registers
*/
#define IOE_REG_CHP_ID 0x00
#define IOE_REG_ID_VER 0x02
/**
* @brief General Control Registers
*/
#define IOE_REG_SYS_CTRL1 0x03
#define IOE_REG_SYS_CTRL2 0x04
#define IOE_REG_SPI_CFG 0x08
/**
* @brief Interrupt Control register
*/
#define IOE_REG_INT_CTRL 0x09
#define IOE_REG_INT_EN 0x0A
#define IOE_REG_INT_STA 0x0B
#define IOE_REG_GPIO_INT_EN 0x0C
#define IOE_REG_GPIO_INT_STA 0x0D
/**
* @brief GPIO Registers
*/
#define IOE_REG_GPIO_SET_PIN 0x10
#define IOE_REG_GPIO_CLR_PIN 0x11
#define IOE_REG_GPIO_MP_STA 0x12
#define IOE_REG_GPIO_DIR 0x13
#define IOE_REG_GPIO_ED 0x14
#define IOE_REG_GPIO_RE 0x15
#define IOE_REG_GPIO_FE 0x16
#define IOE_REG_GPIO_AF 0x17
/**
* @brief ADC Registers
*/
#define IOE_REG_ADC_INT_EN 0x0E
#define IOE_REG_ADC_INT_STA 0x0F
#define IOE_REG_ADC_CTRL1 0x20
#define IOE_REG_ADC_CTRL2 0x21
#define IOE_REG_ADC_CAPT 0x22
#define IOE_REG_ADC_DATA_CH0 0x30 /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH1 0x32 /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH2 0x34 /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH3 0x36 /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH4 0x38 /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH5 0x3A /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH6 0x3B /* 16-Bit register */
#define IOE_REG_ADC_DATA_CH7 0x3C /* 16-Bit register */
/**
* @brief TouchScreen Registers
*/
#define IOE_REG_TSC_CTRL 0x40
#define IOE_REG_TSC_CFG 0x41
#define IOE_REG_WDM_TR_X 0x42
#define IOE_REG_WDM_TR_Y 0x44
#define IOE_REG_WDM_BL_X 0x46
#define IOE_REG_WDM_BL_Y 0x48
#define IOE_REG_FIFO_TH 0x4A
#define IOE_REG_FIFO_STA 0x4B
#define IOE_REG_FIFO_SIZE 0x4C
#define IOE_REG_TSC_DATA_X 0x4D
#define IOE_REG_TSC_DATA_Y 0x4F
#define IOE_REG_TSC_DATA_Z 0x51
#define IOE_REG_TSC_DATA_XYZ 0x52
#define IOE_REG_TSC_FRACT_XYZ 0x56
#define IOE_REG_TSC_DATA 0x57
#define IOE_REG_TSC_I_DRIVE 0x58
#define IOE_REG_TSC_SHIELD 0x59
/**
* @brief Temperature Sensor registers
*/
#define IOE_REG_TEMP_CTRL 0x60
#define IOE_REG_TEMP_DATA 0x61
#define IOE_REG_TEMP_TH 0x62
/*------------------------------------------------------------------------------
Functions parameters defines
------------------------------------------------------------------------------*/
/**
* @brief Touch Screen Pins definition
*/
#define TOUCH_YD IO_Pin_1 /* IO_Exapnader_1 */ /* Input */
#define TOUCH_XD IO_Pin_2 /* IO_Exapnader_1 */ /* Input */
#define TOUCH_YU IO_Pin_3 /* IO_Exapnader_1 */ /* Input */
#define TOUCH_XU IO_Pin_4 /* IO_Exapnader_1 */ /* Input */
#define TOUCH_IO_ALL (uint32_t)(IO_Pin_1 | IO_Pin_2 | IO_Pin_3 | IO_Pin_4)
/**
* @brief JOYSTICK Pins definition
*/
#define JOY_IO_SEL IO_Pin_7
#define JOY_IO_DOWN IO_Pin_6
#define JOY_IO_LEFT IO_Pin_5
#define JOY_IO_RIGHT IO_Pin_4
#define JOY_IO_UP IO_Pin_3
#define JOY_IO_NONE JOY_IO_PINS
#define JOY_IO_PINS (uint32_t)(IO_Pin_3 | IO_Pin_4 | IO_Pin_5 | IO_Pin_6 | IO_Pin_7)
/**
* @brief IO Pins
*/
#define IO_Pin_0 0x01
#define IO_Pin_1 0x02
#define IO_Pin_2 0x04
#define IO_Pin_3 0x08
#define IO_Pin_4 0x10
#define IO_Pin_5 0x20
#define IO_Pin_6 0x40
#define IO_Pin_7 0x80
#define IO_Pin_ALL 0xFF
/**
* @brief IO Pin directions
*/
#define Direction_IN 0x00
#define Direction_OUT 0x01
/**
* @brief Interrupt Line output parameters
*/
#define Polarity_Low 0x00
#define Polarity_High 0x04
#define Type_Level 0x00
#define Type_Edge 0x02
/**
* @brief IO Interrupts
*/
#define IO_IT_0 0x01
#define IO_IT_1 0x02
#define IO_IT_2 0x04
#define IO_IT_3 0x08
#define IO_IT_4 0x10
#define IO_IT_5 0x20
#define IO_IT_6 0x40
#define IO_IT_7 0x80
#define ALL_IT 0xFF
#define IOE_JOY_IT (uint8_t)(IO_IT_3 | IO_IT_4 | IO_IT_5 | IO_IT_6 | IO_IT_7)
#define IOE_TS_IT (uint8_t)(IO_IT_0 | IO_IT_1 | IO_IT_2)
#define IOE_INMEMS_IT (uint8_t)(IO_IT_2 | IO_IT_3)
/**
* @brief Edge detection value
*/
#define EDGE_FALLING 0x01
#define EDGE_RISING 0x02
/**
* @brief Global interrupt Enable bit
*/
#define IOE_GIT_EN 0x01
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM3210C_EVAL_IOE_Exported_Functions
* @{
*/
/**
* @brief Configuration and initialization functions
*/
uint8_t IOE_Config(void);
uint8_t IOE_ITConfig(uint32_t IOE_ITSRC_Source);
/**
* @brief IO pins control functions
*/
uint8_t IOE_WriteIOPin(uint8_t IO_Pin, IOE_BitValue_TypeDef BitVal);
uint8_t IOE_ReadIOPin(uint32_t IO_Pin);
JOYState_TypeDef
IOE_JoyStickGetState(void);
/**
* @brief Touch Screen controller functions
*/
TS_STATE* IOE_TS_GetState(void);
/**
* @brief Interrupts Mangement functions
*/
FlagStatus IOE_GetGITStatus(uint8_t DeviceAddr, uint8_t Global_IT);
uint8_t IOE_ClearGITPending(uint8_t DeviceAddr, uint8_t IO_IT);
FlagStatus IOE_GetIOITStatus(uint8_t DeviceAddr, uint8_t IO_IT);
uint8_t IOE_ClearIOITPending(uint8_t DeviceAddr, uint8_t IO_IT);
/**
* @brief Temperature Sensor functions
*/
uint32_t IOE_TempSens_GetData(void);
/**
* @brief IO-Expander Control functions
*/
uint8_t IOE_IsOperational(uint8_t DeviceAddr);
uint8_t IOE_Reset(uint8_t DeviceAddr);
uint16_t IOE_ReadID(uint8_t DeviceAddr);
uint8_t IOE_FnctCmd(uint8_t DeviceAddr, uint8_t Fct, FunctionalState NewState);
uint8_t IOE_IOPinConfig(uint8_t DeviceAddr, uint8_t IO_Pin, uint8_t Direction);
uint8_t IOE_GITCmd(uint8_t DeviceAddr, FunctionalState NewState);
uint8_t IOE_GITConfig(uint8_t DeviceAddr, uint8_t Global_IT, FunctionalState NewState);
uint8_t IOE_IOITConfig(uint8_t DeviceAddr, uint8_t IO_IT, FunctionalState NewState);
/**
* @brief Low Layer functions
*/
uint8_t IOE_TS_Config(void);
uint8_t IOE_TempSens_Config(void);
uint8_t IOE_IOAFConfig(uint8_t DeviceAddr, uint8_t IO_Pin, FunctionalState NewState);
uint8_t IOE_IOEdgeConfig(uint8_t DeviceAddr, uint8_t IO_Pin, uint8_t Edge);
uint8_t IOE_ITOutConfig(uint8_t Polarity, uint8_t Type);
uint8_t I2C_WriteDeviceRegister(uint8_t DeviceAddr, uint8_t RegisterAddr, uint8_t RegisterValue);
uint8_t I2C_ReadDeviceRegister(uint8_t DeviceAddr, uint8_t RegisterAddr);
uint16_t I2C_ReadDataBuffer(uint8_t DeviceAddr, uint32_t RegisterAddr);
#ifdef __cplusplus
}
#endif
#endif /* __STM3210C_EVAL_IOE_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210C_EVAL/stm3210c_eval_ioe.h
|
C
|
asf20
| 15,158
|
/**
******************************************************************************
* @file stm3210c_eval_lcd.h
* @author MCD Application Team
* @version V4.2.0
* @date 04/16/2010
* @brief This file contains all the functions prototypes for the lcd firmware driver.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2010 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM3210C_EVAL_LCD_H
#define __STM3210C_EVAL_LCD_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "../Common/fonts.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL
* @{
*/
/** @addtogroup STM3210C_EVAL_LCD
* @{
*/
/** @defgroup STM3210C_EVAL_LCD_Exported_Types
* @{
*/
typedef struct
{
int16_t X;
int16_t Y;
} Point, * pPoint;
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LCD_Exported_Constants
* @{
*/
/**
* @brief Uncomment the line below if you want to use LCD_DrawBMP function to
* display a bitmap picture on the LCD. This function assumes that the bitmap
* file is loaded in the SPI Flash (mounted on STM3210C-EVAL board), however
* user can tailor it according to his application hardware requirement.
*/
/*#define USE_LCD_DrawBMP*/
/**
* @brief Uncomment the line below if you want to use user defined Delay function
* (for precise timing), otherwise default _delay_ function defined within
* this driver is used (less precise timing).
*/
/* #define USE_Delay */
#ifdef USE_Delay
#include "main.h"
#define _delay_ Delay /* !< User can provide more timing precise _delay_ function
(with 10ms time base), using SysTick for example */
#else
#define _delay_ delay /* !< Default _delay_ function with less precise timing */
#endif
/**
* @brief LCD Control pins
*/
#define LCD_NCS_PIN GPIO_Pin_2
#define LCD_NCS_GPIO_PORT GPIOB
#define LCD_NCS_GPIO_CLK RCC_APB2Periph_GPIOB
/**
* @brief LCD SPI Interface pins
*/
#define LCD_SPI SPI3
#define LCD_SPI_CLK RCC_APB1Periph_SPI3
#define LCD_SPI_SCK_PIN GPIO_Pin_10
#define LCD_SPI_SCK_GPIO_PORT GPIOC
#define LCD_SPI_SCK_GPIO_CLK RCC_APB2Periph_GPIOC
#define LCD_SPI_MISO_PIN GPIO_Pin_11
#define LCD_SPI_MISO_GPIO_PORT GPIOC
#define LCD_SPI_MISO_GPIO_CLK RCC_APB2Periph_GPIOC
#define LCD_SPI_MOSI_PIN GPIO_Pin_12
#define LCD_SPI_MOSI_GPIO_PORT GPIOC
#define LCD_SPI_MOSI_GPIO_CLK RCC_APB2Periph_GPIOC
/**
* @brief LCD Registers
*/
#define LCD_REG_0 0x00
#define LCD_REG_1 0x01
#define LCD_REG_2 0x02
#define LCD_REG_3 0x03
#define LCD_REG_4 0x04
#define LCD_REG_5 0x05
#define LCD_REG_6 0x06
#define LCD_REG_7 0x07
#define LCD_REG_8 0x08
#define LCD_REG_9 0x09
#define LCD_REG_10 0x0A
#define LCD_REG_12 0x0C
#define LCD_REG_13 0x0D
#define LCD_REG_14 0x0E
#define LCD_REG_15 0x0F
#define LCD_REG_16 0x10
#define LCD_REG_17 0x11
#define LCD_REG_18 0x12
#define LCD_REG_19 0x13
#define LCD_REG_20 0x14
#define LCD_REG_21 0x15
#define LCD_REG_22 0x16
#define LCD_REG_23 0x17
#define LCD_REG_24 0x18
#define LCD_REG_25 0x19
#define LCD_REG_26 0x1A
#define LCD_REG_27 0x1B
#define LCD_REG_28 0x1C
#define LCD_REG_29 0x1D
#define LCD_REG_30 0x1E
#define LCD_REG_31 0x1F
#define LCD_REG_32 0x20
#define LCD_REG_33 0x21
#define LCD_REG_34 0x22
#define LCD_REG_36 0x24
#define LCD_REG_37 0x25
#define LCD_REG_40 0x28
#define LCD_REG_41 0x29
#define LCD_REG_43 0x2B
#define LCD_REG_45 0x2D
#define LCD_REG_48 0x30
#define LCD_REG_49 0x31
#define LCD_REG_50 0x32
#define LCD_REG_51 0x33
#define LCD_REG_52 0x34
#define LCD_REG_53 0x35
#define LCD_REG_54 0x36
#define LCD_REG_55 0x37
#define LCD_REG_56 0x38
#define LCD_REG_57 0x39
#define LCD_REG_59 0x3B
#define LCD_REG_60 0x3C
#define LCD_REG_61 0x3D
#define LCD_REG_62 0x3E
#define LCD_REG_63 0x3F
#define LCD_REG_64 0x40
#define LCD_REG_65 0x41
#define LCD_REG_66 0x42
#define LCD_REG_67 0x43
#define LCD_REG_68 0x44
#define LCD_REG_69 0x45
#define LCD_REG_70 0x46
#define LCD_REG_71 0x47
#define LCD_REG_72 0x48
#define LCD_REG_73 0x49
#define LCD_REG_74 0x4A
#define LCD_REG_75 0x4B
#define LCD_REG_76 0x4C
#define LCD_REG_77 0x4D
#define LCD_REG_78 0x4E
#define LCD_REG_79 0x4F
#define LCD_REG_80 0x50
#define LCD_REG_81 0x51
#define LCD_REG_82 0x52
#define LCD_REG_83 0x53
#define LCD_REG_96 0x60
#define LCD_REG_97 0x61
#define LCD_REG_106 0x6A
#define LCD_REG_118 0x76
#define LCD_REG_128 0x80
#define LCD_REG_129 0x81
#define LCD_REG_130 0x82
#define LCD_REG_131 0x83
#define LCD_REG_132 0x84
#define LCD_REG_133 0x85
#define LCD_REG_134 0x86
#define LCD_REG_135 0x87
#define LCD_REG_136 0x88
#define LCD_REG_137 0x89
#define LCD_REG_139 0x8B
#define LCD_REG_140 0x8C
#define LCD_REG_141 0x8D
#define LCD_REG_143 0x8F
#define LCD_REG_144 0x90
#define LCD_REG_145 0x91
#define LCD_REG_146 0x92
#define LCD_REG_147 0x93
#define LCD_REG_148 0x94
#define LCD_REG_149 0x95
#define LCD_REG_150 0x96
#define LCD_REG_151 0x97
#define LCD_REG_152 0x98
#define LCD_REG_153 0x99
#define LCD_REG_154 0x9A
#define LCD_REG_157 0x9D
#define LCD_REG_192 0xC0
#define LCD_REG_193 0xC1
#define LCD_REG_229 0xE5
/**
* @brief LCD color
*/
#define LCD_COLOR_WHITE 0xFFFF
#define LCD_COLOR_BLACK 0x0000
#define LCD_COLOR_GREY 0xF7DE
#define LCD_COLOR_BLUE 0x001F
#define LCD_COLOR_BLUE2 0x051F
#define LCD_COLOR_RED 0xF800
#define LCD_COLOR_MAGENTA 0xF81F
#define LCD_COLOR_GREEN 0x07E0
#define LCD_COLOR_CYAN 0x7FFF
#define LCD_COLOR_YELLOW 0xFFE0
/**
* @brief LCD Lines depending on the chosen fonts.
*/
#define LCD_LINE_0 LINE(0)
#define LCD_LINE_1 LINE(1)
#define LCD_LINE_2 LINE(2)
#define LCD_LINE_3 LINE(3)
#define LCD_LINE_4 LINE(4)
#define LCD_LINE_5 LINE(5)
#define LCD_LINE_6 LINE(6)
#define LCD_LINE_7 LINE(7)
#define LCD_LINE_8 LINE(8)
#define LCD_LINE_9 LINE(9)
#define LCD_LINE_10 LINE(10)
#define LCD_LINE_11 LINE(11)
#define LCD_LINE_12 LINE(12)
#define LCD_LINE_13 LINE(13)
#define LCD_LINE_14 LINE(14)
#define LCD_LINE_15 LINE(15)
#define LCD_LINE_16 LINE(16)
#define LCD_LINE_17 LINE(17)
#define LCD_LINE_18 LINE(18)
#define LCD_LINE_19 LINE(19)
#define LCD_LINE_20 LINE(20)
#define LCD_LINE_21 LINE(21)
#define LCD_LINE_22 LINE(22)
#define LCD_LINE_23 LINE(23)
#define LCD_LINE_24 LINE(24)
#define LCD_LINE_25 LINE(25)
#define LCD_LINE_26 LINE(26)
#define LCD_LINE_27 LINE(27)
#define LCD_LINE_28 LINE(28)
#define LCD_LINE_29 LINE(29)
/**
* @brief LCD default font
*/
#define LCD_DEFAULT_FONT Font16x24
/**
* @brief LCD Direction
*/
#define LCD_DIR_HORIZONTAL 0x0000
#define LCD_DIR_VERTICAL 0x0001
/**
* @brief LCD Size (Width and Height)
*/
#define LCD_PIXEL_WIDTH 0x0140
#define LCD_PIXEL_HEIGHT 0x00F0
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LCD_Exported_Macros
* @{
*/
#define ASSEMBLE_RGB(R, G, B) ((((R)& 0xF8) << 8) | (((G) & 0xFC) << 3) | (((B) & 0xF8) >> 3))
/**
* @}
*/
/** @defgroup STM3210C_EVAL_LCD_Exported_Functions
* @{
*/
void LCD_DeInit(void);
void LCD_Setup(void);
void STM3210C_LCD_Init(void);
void LCD_SetColors(__IO uint16_t _TextColor, __IO uint16_t _BackColor);
void LCD_GetColors(__IO uint16_t *_TextColor, __IO uint16_t *_BackColor);
void LCD_SetTextColor(__IO uint16_t Color);
void LCD_SetBackColor(__IO uint16_t Color);
void LCD_ClearLine(uint8_t Line);
void LCD_Clear(uint16_t Color);
void LCD_SetCursor(uint8_t Xpos, uint16_t Ypos);
void LCD_DrawChar(uint8_t Xpos, uint16_t Ypos, const uint16_t *c);
void LCD_DisplayChar(uint8_t Line, uint16_t Column, uint8_t Ascii);
void LCD_SetFont(sFONT *fonts);
sFONT *LCD_GetFont(void);
void LCD_DisplayStringLine(uint8_t Line, uint8_t *ptr);
void LCD_SetDisplayWindow(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_WindowModeDisable(void);
void LCD_DrawLine(uint8_t Xpos, uint16_t Ypos, uint16_t Length, uint8_t Direction);
void LCD_DrawRect(uint8_t Xpos, uint16_t Ypos, uint8_t Height, uint16_t Width);
void LCD_DrawCircle(uint8_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_DrawMonoPict(const uint32_t *Pict);
#ifdef USE_LCD_DrawBMP
//void LCD_DrawBMP(uint32_t BmpAddress);
void LCD_DrawBMP(const uint16_t *BmpAddress);
#endif
void LCD_DrawUniLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
void LCD_DrawFullRect(uint16_t Xpos, uint16_t Ypos, uint16_t Width, uint16_t Height);
void LCD_DrawFullCircle(uint16_t Xpos, uint16_t Ypos, uint16_t Radius);
void LCD_PolyLine(pPoint Points, uint16_t PointCount);
void LCD_PolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLine(pPoint Points, uint16_t PointCount);
void LCD_ClosedPolyLineRelative(pPoint Points, uint16_t PointCount);
void LCD_FillPolyLine(pPoint Points, uint16_t PointCount);
void LCD_nCS_StartByte(uint8_t Start_Byte);
void LCD_WriteRegIndex(uint8_t LCD_Reg);
void LCD_WriteReg(uint8_t LCD_Reg, uint16_t LCD_RegValue);
void LCD_WriteRAM_Prepare(void);
void LCD_WriteRAMWord(uint16_t RGB_Code);
uint16_t LCD_ReadReg(uint8_t LCD_Reg);
void LCD_WriteRAM(uint16_t RGB_Code);
void LCD_PowerOn(void);
void LCD_DisplayOn(void);
void LCD_DisplayOff(void);
void LCD_CtrlLinesConfig(void);
void LCD_CtrlLinesWrite(GPIO_TypeDef* GPIOx, uint16_t CtrlPins, BitAction BitVal);
void LCD_SPIConfig(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM3210C_EVAL_LCD_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/STM32_EVAL/STM3210C_EVAL/stm3210c_eval_lcd.h
|
C
|
asf20
| 12,501
|
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210E-EVAL\SysTick.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210E-EVAL\SysTick.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210B-EVAL\SysTick.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210B-EVAL\SysTick.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210C-EVAL\SysTick.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210C-EVAL\SysTick.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210E-EVAL_XL\SysTick.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\RIDE\STM3210E-EVAL_XL\SysTick.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM32100B-EVAL\Project.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM32100B-EVAL\Project.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210B-EVAL\Project.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210B-EVAL\Project.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210C-EVAL\Project.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210C-EVAL\Project.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210E-EVAL\Project.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210E-EVAL\Project.hex)
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210E-EVAL_XL\Project.hex (hex2bin.exe .\..\..\Project\Device_Firmware_Upgrade\binary_template\HiTOP\STM3210E-EVAL_XL\Project.hex)
pause
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/Binary/hextobin.bat
|
Batchfile
|
asf20
| 1,830
|
@echo off
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210C-EVAL\Debug\STM3210C-EVAL.elf ("arm-elf-objcopy.exe" -O binary ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210C-EVAL\Debug\STM3210C-EVAL.elf" ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210C-EVAL\Debug\STM3210C-EVAL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210B-EVAL\Debug\STM3210B-EVAL.elf ("arm-elf-objcopy.exe" -O binary ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210B-EVAL\Debug\STM3210B-EVAL.elf" ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210B-EVAL\Debug\STM3210B-EVAL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL\Debug\STM3210E-EVAL.elf ("arm-elf-objcopy.exe" -O binary ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL\Debug\STM3210E-EVAL.elf" ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL\Debug\STM3210E-EVAL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL_XL\Debug\STM32F10X_XL.elf ("arm-elf-objcopy.exe" -O binary ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL_XL\Debug\STM32F10X_XL.elf" ".\..\..\Project\Device_Firmware_Upgrade\binary_template\TrueSTUDIO\STM3210E-EVAL_XL\Debug\STM32F10X_XL_SysTick.bin")
pause
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/Binary/TrueSTUDIO_elf2bin.bat
|
Batchfile
|
asf20
| 1,520
|
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL_XL\STM3210E-EVAL_XL.axf (C:\Keil\ARM\BIN40\fromelf.exe ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL_XL\STM3210E-EVAL_XL.axf" --bin --output ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL_XL\STM3210E-EVAL_XL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210B-EVAL\STM3210B-EVAL.axf (C:\Keil\ARM\BIN40\fromelf.exe ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210B-EVAL\STM3210B-EVAL.axf" --bin --output ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210B-EVAL\STM3210B-EVAL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL\STM3210E-EVAL.axf (C:\Keil\ARM\BIN40\fromelf.exe ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL\STM3210E-EVAL.axf" --bin --output ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210E-EVAL\STM3210E-EVAL_SysTick.bin")
if exist .\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210C-EVAL\STM3210C-EVAL.axf (C:\Keil\ARM\BIN40\fromelf.exe ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210C-EVAL\STM3210C-EVAL.axf" --bin --output ".\..\..\Project\Device_Firmware_Upgrade\binary_template\MDK-ARM\STM3210C-EVAL\STM3210C-EVAL_SysTick.bin")
pause
|
zzqq5414-jk-rabbit
|
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Utilities/Binary/axftobin.bat
|
Batchfile
|
asf20
| 1,454
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Texture filtering modes.
public final static int FILTER_NEAREST_NEIGHBOR = 0;
public final static int FILTER_BILINEAR = 1;
public final static int FILTER_TRILINEAR = 2;
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
// A reference to the application context.
private Context mContext;
private LandTileMap mTiles;
private int mTextureResource;
private int mTextureResource2;
private int mTextureId2;
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private Object mCameraLock = new Object();
private boolean mCameraDirty;
private NativeRenderer mNativeRenderer;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
private boolean mUseTextureLods = false;
private boolean mUseHardwareMips = false;
boolean mColorTextureLods = false;
private int mTextureFilter = FILTER_BILINEAR;
private int mMaxTextureSize = 0;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
mUseHardwareBuffers = true;
}
public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) {
mTextureResource = textureResource;
mTextureResource2 = textureResource2;
mTiles = tiles;
}
/** Draws the landscape. */
public void onDrawFrame(GL10 gl) {
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
if (mTiles != null) {
// Clear the screen. Note that a real application probably would only clear the depth buffer
// (or maybe not even that).
if (mNativeRenderer == null) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
// If the camera has moved since the last frame, rebuild our projection matrix.
if (mCameraDirty){
synchronized (mCameraLock) {
if (mNativeRenderer != null) {
mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition);
} else {
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z,
mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z,
0.0f, 1.0f, 0.0f);
}
mCameraDirty = false;
}
}
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
// Draw the landscape.
mTiles.draw(gl, mCameraPosition);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
}
ProfileRecorder.sSingleton.endFrame();
}
/* Called when the size of the window changes. */
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
float ratio = (float)width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f);
mCameraDirty = true;
}
public void setCameraPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mCameraPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setCameraLookAtPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mLookAtPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setUseHardwareBuffers(boolean vbos) {
mUseHardwareBuffers = vbos;
}
/**
* Called to turn on Levels of Detail option for rendering textures
*
* @param mUseTextureLods
*/
public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) {
mUseTextureLods = useTextureLods;
mUseHardwareMips = useHardwareMips;
}
/**
* Turns on/off color the LOD bitmap textures based on their distance from view.
* This feature is useful since it helps visualize the LOD being used while viewing the scene.
*
* @param colorTextureLods
*/
public void setColorTextureLods(boolean colorTextureLods) {
this.mColorTextureLods = colorTextureLods;
}
public void setNativeRenderer(NativeRenderer render) {
mNativeRenderer = render;
}
public void setMaxTextureSize(int maxTextureSize) {
mMaxTextureSize = maxTextureSize;
}
public void setTextureFilter(int filter) {
mTextureFilter = filter;
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
int[] textureNames = null;
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
// set up some fog.
gl.glEnable(GL10.GL_FOG);
gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR);
float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f };
gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0);
gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f);
gl.glFogf(GL10.GL_FOG_START, 800.0f);
gl.glFogf(GL10.GL_FOG_END, 2048.0f);
gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// load textures and buffers here
if (mUseHardwareBuffers && mTiles != null) {
mTiles.generateHardwareBuffers(gl);
}
if (mTextureResource != 0) {
textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips );
}
if (mTextureResource2 != 0) {
mTextureId2 = loadBitmap(mContext, gl, mTextureResource2);
}
mTiles.setTextures(textureNames, mTextureId2);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false);
bitmap.recycle();
return textureName;
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @param context
* @param resourceId
* @param numLevelsOfDetail number of detail textures to generate
*
* @return a array of OpenGL texture names corresponding to the different levels of detail textures
*/
protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) {
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight());
int numLevelsOfDetail = 1;
if (generateMips) {
for (int side = minSide / 2; side > 0; side /= 2) {
numLevelsOfDetail++;
}
}
int textureNames[];
if (generateMips && !useHardwareMips) {
textureNames = new int[numLevelsOfDetail];
} else {
textureNames = new int[1];
}
textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips);
// Scale down base bitmap by powers of two to create lower resolution textures
for( int i = 1; i < numLevelsOfDetail; ++i ) {
int scale = (int)Math.pow(2, i);
int dstWidth = bitmap.getWidth() / scale;
int dstHeight = bitmap.getHeight() / scale;
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false );
// Set each LOD level to a different color to help visualization
if( mColorTextureLods ) {
int color = 0;
switch( (int)(i % 4) ) {
case 1:
color = Color.RED;
break;
case 2:
color = Color.YELLOW;
break;
case 3:
color = Color.BLUE;
break;
}
tempBitmap.eraseColor( color );
}
if (!useHardwareMips) {
textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false);
} else {
addHardwareMipmap(gl, textureNames[0], tempBitmap, i );
}
tempBitmap.recycle();
}
bitmap.recycle();
return textureNames;
}
protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @return OpenGL texture entry id
*/
protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
if (useMipmaps) {
if (mTextureFilter == FILTER_TRILINEAR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
}
} else {
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
}
}
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
}
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SimpleGLRenderer", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/SimpleGLRenderer.java
|
Java
|
asf20
| 14,372
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.os.SystemClock;
// Very simple game runtime. Implements basic movement and collision detection with the landscape.
public class Game implements Runnable {
private Vector3 mCameraPosition = new Vector3(100.0f, 128.0f, 400.0f);
private Vector3 mTargetPosition = new Vector3(350.0f, 128.0f, 650.0f);
private Vector3 mWorkVector = new Vector3();
private float mCameraXZAngle;
private float mCameraYAngle;
private float mCameraLookAtDistance = (float)Math.sqrt(mTargetPosition.distance2(mCameraPosition));
private boolean mCameraDirty = true;
private boolean mRunning = true;
private boolean mPaused = false;
private Object mPauseLock = new Object();
private LandTileMap mTileMap;
private final static float CAMERA_ORBIT_SPEED = 0.3f;
private final static float CAMERA_MOVE_SPEED = 5.0f;
private final static float VIEWER_HEIGHT = 15.0f;
private SimpleGLRenderer mSimpleRenderer;
public Game(SimpleGLRenderer renderer, LandTileMap tiles) {
mSimpleRenderer = renderer;
mTileMap = tiles;
}
public void run() {
while (mRunning) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
long startTime = SystemClock.uptimeMillis();
if (mCameraDirty) {
// snap the camera to the floor
float height = mTileMap.getHeight(mCameraPosition.x, mCameraPosition.z);
mCameraPosition.y = height + VIEWER_HEIGHT;
updateCamera();
}
long endTime = SystemClock.uptimeMillis();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
if (endTime - startTime < 16) {
// we're running too fast! sleep for a bit to let the render thread do some work.
try {
Thread.sleep(16 - (endTime - startTime));
} catch (InterruptedException e) {
// Interruptions are not a big deal here.
}
}
synchronized(mPauseLock) {
if (mPaused) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// OK if this is interrupted.
}
}
}
}
}
}
synchronized private void updateCamera() {
mWorkVector.set((float)Math.cos(mCameraXZAngle), (float)Math.sin(mCameraYAngle), (float)Math.sin(mCameraXZAngle));
mWorkVector.multiply(mCameraLookAtDistance);
mWorkVector.add(mCameraPosition);
mTargetPosition.set(mWorkVector);
mSimpleRenderer.setCameraPosition(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z);
mSimpleRenderer.setCameraLookAtPosition(mTargetPosition.x, mTargetPosition.y, mTargetPosition.z);
mCameraDirty = false;
}
synchronized public void rotate(float x, float y) {
if (x != 0.0f) {
mCameraXZAngle += x * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
if (y != 0.0f) {
mCameraYAngle += y * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
}
synchronized public void move(float amount) {
mWorkVector.set(mTargetPosition);
mWorkVector.subtract(mCameraPosition);
mWorkVector.normalize();
mWorkVector.multiply(amount * CAMERA_MOVE_SPEED);
mCameraPosition.add(mWorkVector);
mTargetPosition.add(mWorkVector);
mCameraDirty = true;
}
public void pause() {
synchronized(mPauseLock) {
mPaused = true;
}
}
public void resume() {
synchronized(mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/Game.java
|
Java
|
asf20
| 3,986
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.opengl.GLSurfaceView;
import com.android.heightmapprofiler.SimpleGLRenderer;
import com.android.heightmapprofiler.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
// The main entry point for the actual landscape rendering test.
// This class pulls options from the preferences set in the MainMenu
// activity and builds the landscape accordingly.
public class HeightMapTest extends Activity {
private GLSurfaceView mGLSurfaceView;
private SimpleGLRenderer mSimpleRenderer;
private Game mGame;
private Thread mGameThread;
private float mLastScreenX;
private float mLastScreenY;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
mGLSurfaceView.setEGLConfigChooser(true);
mSimpleRenderer = new SimpleGLRenderer(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final boolean runGame = prefs.getBoolean("runsim", true);
final boolean bigWorld = prefs.getBoolean("bigworld", true);
final boolean skybox = prefs.getBoolean("skybox", true);
final boolean texture = prefs.getBoolean("texture", true);
final boolean vertexColors = prefs.getBoolean("colors", true);
final boolean useTextureLods = prefs.getBoolean("lodTexture", true);
final boolean textureMips = prefs.getBoolean("textureMips", true);
final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false );
final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512"));
final String textureFilter = prefs.getString("textureFiltering", "bilinear");
final boolean useLods = prefs.getBoolean("lod", true);
final int complexity = Integer.parseInt(prefs.getString("complexity", "24"));
final boolean useFixedPoint = prefs.getBoolean("fixed", false);
final boolean useVbos = prefs.getBoolean("vbo", true);
final boolean useNdk = prefs.getBoolean("ndk", false);
BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap);
Bitmap heightmap = heightMapDrawable.getBitmap();
Bitmap lightmap = null;
if (vertexColors != false) {
BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap);
lightmap = lightMapDrawable.getBitmap();
}
LandTileMap tileMap = null;
if (bigWorld) {
final int tilesX = 4;
final int tilesY = 4;
tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
} else {
tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
}
if (skybox) {
BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox);
Bitmap skyboxBitmap = skyboxDrawable.getBitmap();
tileMap.setupSkybox(skyboxBitmap, useFixedPoint);
}
if (useNdk) {
NativeRenderer renderer = new NativeRenderer();
tileMap.setNativeRenderer(renderer);
mSimpleRenderer.setNativeRenderer(renderer);
}
ProfileRecorder.sSingleton.resetAll();
mSimpleRenderer.setUseHardwareBuffers(useVbos);
if (texture) {
mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture);
mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips );
mSimpleRenderer.setColorTextureLods( useColorTextureLods );
mSimpleRenderer.setMaxTextureSize(maxTextureSize);
if (textureFilter == "nearest") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR);
} else if (textureFilter == "trilinear") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR);
} else {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR);
}
} else {
mSimpleRenderer.setTiles(tileMap, 0, 0);
}
mGLSurfaceView.setRenderer(mSimpleRenderer);
setContentView(mGLSurfaceView);
if (runGame) {
mGame = new Game(mSimpleRenderer, tileMap);
mGameThread = new Thread(mGame);
mGameThread.start();
}
}
@Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
if (mGame != null) {
mGame.pause();
}
}
@Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
if (mGame != null) {
mGame.resume();
}
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (mGame != null) {
mGame.rotate(event.getRawX(), -event.getRawY());
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGame != null) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mGame.move(1.0f);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float xDelta = event.getX() - mLastScreenX;
float yDelta = event.getY() - mLastScreenY;
mGame.move(1.0f);
// Scale the values we got down to make control usable.
// A real game would probably figure out scale factors based
// on the size of the screen rather than hard-coded constants
// like this.
mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f);
}
}
mLastScreenX = event.getX();
mLastScreenY = event.getY();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGame != null) {
final float speed = 1.0f;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
mGame.rotate(0.0f, -speed);
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
mGame.rotate(-speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
mGame.rotate(speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
mGame.rotate(0.0f, speed);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/HeightMapTest.java
|
Java
|
asf20
| 7,428
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import com.android.heightmapprofiler.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
/**
* Main entry point for the HeightMapTest application.
*/
public class MainMenu extends PreferenceActivity implements Preference.OnPreferenceClickListener {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
Preference runTestButton = getPreferenceManager().findPreference("runtest");
if (runTestButton != null) {
runTestButton.setOnPreferenceClickListener(this);
}
}
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameVerts = profiler.getAverageVerts();
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n"
+ "\nVerts per frame: ~" + frameVerts + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(this, HeightMapTest.class);
startActivityForResult(i, ACTIVITY_TEST);
return true;
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/MainMenu.java
|
Java
|
asf20
| 4,939
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
private long mVertexCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public final void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public final void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public final void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public final void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
mVertexCount = 0L;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
public long getTotalVerts() {
return mVertexCount;
}
public long getAverageVerts() {
return mVertexCount / mFrameCount;
}
public void addVerts(long vertCount) {
mVertexCount += vertCount;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
if (mStartTime > 0) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/ProfileRecorder.java
|
Java
|
asf20
| 5,182
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.graphics.Bitmap;
import android.graphics.Color;
// This class generates vertex arrays based on grayscale images.
// It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point,
// and builds a mesh that represents that topology.
public class HeightMapMeshMaker {
public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) {
Grid grid = null;
final float subdivisionRange = subdivisions - 1;
final float vertexSizeX = width / subdivisionRange;
final float vertexSizeZ = height / subdivisionRange;
if (drawable != null) {
grid = new Grid(subdivisions, subdivisions, fixedPoint);
final float heightMapScaleX = drawable.getWidth() / subdivisionRange;
final float heightMapScaleY = drawable.getHeight() / subdivisionRange;
final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f;
final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f;
final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f };
for (int i = 0; i < subdivisions; i++) {
final float u = (float)(i + 1) / subdivisions;
for (int j = 0; j < subdivisions; j++) {
final float v = (float)(j + 1) / subdivisions;
final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale);
if (lightmap != null) {
final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j));
final float colorScale = 1.0f / 255.0f;
vertexColor[0] = colorScale * Color.red(lightColor);
vertexColor[1] = colorScale * Color.green(lightColor);
vertexColor[2] = colorScale * Color.blue(lightColor);
vertexColor[3] = colorScale * Color.alpha(lightColor);
}
grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor);
}
}
}
return grid;
}
// In order to get a smooth gradation between pixels from a low-resolution height map,
// this function uses a bilinear filter to calculate a weighted average of four pixels
// surrounding the requested point.
public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) {
final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1);
final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1);
final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1);
final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1);
final float topLeftWeightX = x - topLeftPixelX;
final float topLeftWeightY = y - topLeftPixelY;
final float bottomRightWeightX = 1.0f - topLeftWeightX;
final float bottomRightWeightY = 1.0f - topLeftWeightY;
final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY);
final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY);
final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY);
final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY);
final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight);
final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight);
final float red = bottomRightWeightY * red1 + topLeftWeightY * red2;
final float height = red * scale;
return height;
}
private static final int clamp(int value, int min, int max) {
return value < min ? min : (value > max ? max : value);
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/HeightMapMeshMaker.java
|
Java
|
asf20
| 4,425
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
public long getVertexCount() {
return mW * mH;
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/Grid.java
|
Java
|
asf20
| 14,432
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
// This is a central repository for all vertex arrays. It handles
// generation and invalidation of VBOs from each mesh.
public class MeshLibrary {
// This sample only has one type of mesh, Grid, but in a real game you might have
// multiple types of objects managing vertex arrays (animated objects, objects loaded from
// files, etc). This class could easily be modified to work with some basic Mesh class
// in that case.
private ArrayList<Grid[]> mMeshes = new ArrayList<Grid[]>();
public int addMesh(Grid[] lods) {
int index = mMeshes.size();
mMeshes.add(lods);
return index;
}
public Grid[] getMesh(int index) {
Grid[] mesh = null;
if (index >= 0 && index < mMeshes.size()) {
mesh = mMeshes.get(index);
}
return mesh;
}
public void generateHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.invalidateHardwareBuffers();
lod.generateHardwareBuffers(gl);
}
}
}
}
public void freeHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.releaseHardwareBuffers(gl);
}
}
}
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/MeshLibrary.java
|
Java
|
asf20
| 2,184
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class defines a single land tile. It is built from
// a height map image and may contain several meshes defining different levels
// of detail.
public class LandTile {
public final static float TILE_SIZE = 512;
private final static float HALF_TILE_SIZE = TILE_SIZE / 2;
public final static float TILE_HEIGHT_THRESHOLD = 0.4f;
private final static int MAX_SUBDIVISIONS = 24;
private final static float LOD_STEP_SIZE = 300.0f;
public final static int LOD_LEVELS = 4;
private final static float MAX_LOD_DISTANCE = LOD_STEP_SIZE * (LOD_LEVELS - 1);
private final static float MAX_LOD_DISTANCE2 = MAX_LOD_DISTANCE * MAX_LOD_DISTANCE;
private Grid mLODMeshes[];
private int mLODTextures[];
private Vector3 mPosition = new Vector3();
private Vector3 mCenterPoint = new Vector3();
private Bitmap mHeightMap;
private float mHeightMapScaleX;
private float mHeightMapScaleY;
private int mLodLevels = LOD_LEVELS;
private int mMaxSubdivisions = MAX_SUBDIVISIONS;
private float mTileSizeX = TILE_SIZE;
private float mTileSizeZ = TILE_SIZE;
private float mHalfTileSizeX = HALF_TILE_SIZE;
private float mHalfTileSizeZ = HALF_TILE_SIZE;
private float mTileHeightScale = TILE_HEIGHT_THRESHOLD;
private float mMaxLodDistance = MAX_LOD_DISTANCE;
private float mMaxLodDistance2 = MAX_LOD_DISTANCE2;
public LandTile() {
}
public LandTile(boolean useLods, int maxSubdivisions ) {
if (!useLods) {
mLodLevels = 1;
}
mMaxSubdivisions = maxSubdivisions;
}
public LandTile(float sizeX, float sizeY, float sizeZ, int lodLevelCount, int maxSubdivisions, float maxLodDistance) {
mTileSizeX = sizeX;
mTileSizeZ = sizeZ;
mTileHeightScale = (1.0f / 255.0f) * sizeY;
mLodLevels = lodLevelCount;
mMaxSubdivisions = maxSubdivisions;
mMaxLodDistance = maxLodDistance;
mMaxLodDistance2 = maxLodDistance * maxLodDistance;
mHalfTileSizeX = sizeX / 2.0f;
mHalfTileSizeZ = sizeZ / 2.0f;
}
public void setLods(Grid[] lodMeshes, Bitmap heightmap) {
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
mLODMeshes = lodMeshes;
}
public void setLODTextures( int LODTextures[] ) {
mLODTextures = LODTextures;
}
public Grid[] generateLods(Bitmap heightmap, Bitmap lightmap, boolean useFixedPoint) {
final int subdivisionSizeStep = mMaxSubdivisions / mLodLevels;
mLODMeshes = new Grid[mLodLevels];
for (int x = 0; x < mLodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (mLodLevels - x);
mLODMeshes[x] = HeightMapMeshMaker.makeGrid(heightmap, lightmap, subdivisions, mTileSizeX, mTileSizeZ, mTileHeightScale, useFixedPoint);
}
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
return mLODMeshes;
}
public final void setPosition(float x, float y, float z) {
mPosition.set(x, y, z);
mCenterPoint.set(x + mHalfTileSizeX, y, z + mHalfTileSizeZ);
}
public final void setPosition(Vector3 position) {
mPosition.set(position);
mCenterPoint.set(position.x + mHalfTileSizeX, position.y, position.z + mHalfTileSizeZ);
}
public final Vector3 getPosition() {
return mPosition;
}
public final Vector3 getCenterPoint() {
return mCenterPoint;
}
public final Grid[] getLods() {
return mLODMeshes;
}
public final float getMaxLodDistance() {
return mMaxLodDistance;
}
public float getHeight(float worldSpaceX, float worldSpaceZ) {
final float tileSpaceX = worldSpaceX - mPosition.x;
final float tileSpaceY = worldSpaceZ - mPosition.z;
final float imageSpaceX = tileSpaceX * mHeightMapScaleX;
final float imageSpaceY = tileSpaceY * mHeightMapScaleY;
float height = 0.0f;
if (imageSpaceX >= 0.0f && imageSpaceX < mHeightMap.getWidth()
&& imageSpaceY >= 0.0f && imageSpaceY < mHeightMap.getHeight()) {
height = HeightMapMeshMaker.getBilinearFilteredHeight(mHeightMap, imageSpaceX, imageSpaceY, mTileHeightScale);
}
return height;
}
public void draw(GL10 gl, Vector3 cameraPosition) {
mCenterPoint.y = cameraPosition.y; // HACK!
final float distanceFromCamera2 = cameraPosition.distance2(mCenterPoint);
int lod = mLodLevels - 1;
if (distanceFromCamera2 < mMaxLodDistance2) {
final int bucket = (int)((distanceFromCamera2 / mMaxLodDistance2) * mLodLevels);
lod = Math.min(bucket, mLodLevels - 1);
}
gl.glPushMatrix();
gl.glTranslatef(mPosition.x, mPosition.y, mPosition.z);
// TODO - should add some code to keep state of current Texture and only set it if a new texture is needed -
// may be taken care of natively by OpenGL lib.
if( mLODTextures != null ) {
// Check to see if we have different LODs to choose from (i.e. Text LOD feature is turned on). If not then
// just select the default texture
if( mLODTextures.length == 1 ) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[0]);
}
// if the LOD feature is enabled, use lod value to select correct texture to use
else {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[lod]);
}
}
ProfileRecorder.sSingleton.addVerts(mLODMeshes[lod].getVertexCount());
mLODMeshes[lod].draw(gl, true, true);
gl.glPopMatrix();
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/LandTile.java
|
Java
|
asf20
| 6,003
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class manages a regular grid of LandTile objects. In this sample,
// all the objects are the same mesh. In a real game, they would probably be
// different to create a more interesting landscape.
// This class also abstracts the concept of tiles away from the rest of the
// code, so that the collision system (amongst others) can query the height of any
// given point in the world.
public class LandTileMap {
private MeshLibrary mMeshLibrary = new MeshLibrary();
private LandTile[] mTiles;
private LandTile mSkybox;
private float mWorldWidth;
private float mWorldHeight;
private int mTilesAcross;
private int mSkyboxTexture;
private boolean mUseColors;
private boolean mUseTexture;
private NativeRenderer mNativeRenderer;
public LandTileMap(
int tilesAcross,
int tilesDown,
Bitmap heightmap,
Bitmap lightmap,
boolean useColors,
boolean useTexture,
boolean useLods,
int maxSubdivisions,
boolean useFixedPoint) {
Grid[] lodMeshes;
int lodLevels = 1;
if (useLods) {
lodLevels = LandTile.LOD_LEVELS;
}
lodMeshes = new Grid[lodLevels];
final int subdivisionSizeStep = maxSubdivisions / lodLevels;
for (int x = 0; x < lodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (lodLevels - x);
lodMeshes[x] = HeightMapMeshMaker.makeGrid(
heightmap,
lightmap,
subdivisions,
LandTile.TILE_SIZE,
LandTile.TILE_SIZE,
LandTile.TILE_HEIGHT_THRESHOLD,
useFixedPoint);
}
mMeshLibrary.addMesh(lodMeshes);
LandTile[] tiles = new LandTile[tilesAcross * tilesDown];
for (int x = 0; x < tilesAcross; x++) {
for (int y = 0; y < tilesDown; y++) {
LandTile tile = new LandTile(useLods, maxSubdivisions);
tile.setLods(lodMeshes, heightmap);
tiles[x * tilesAcross + y] = tile;
tile.setPosition(x * LandTile.TILE_SIZE, 0.0f, y * LandTile.TILE_SIZE);
}
}
mTiles = tiles;
mWorldWidth = tilesAcross * LandTile.TILE_SIZE;
mWorldHeight = tilesDown * LandTile.TILE_SIZE;
mTilesAcross = tilesAcross;
mUseColors = useColors;
mUseTexture = useTexture;
}
public void setLandTextures( int landTextures[] ) {
for( LandTile landTile : mTiles ) {
landTile.setLODTextures( landTextures );
}
}
public void setupSkybox(Bitmap heightmap, boolean useFixedPoint) {
if (mSkybox == null) {
mSkybox = new LandTile(mWorldWidth, 1024, mWorldHeight, 1, 16, 1000000.0f);
mMeshLibrary.addMesh(mSkybox.generateLods(heightmap, null, useFixedPoint));
mSkybox.setPosition(0.0f, 0.0f, 0.0f);
}
}
public float getHeight(float worldX, float worldZ) {
float height = 0.0f;
if (worldX > 0.0f && worldX < mWorldWidth && worldZ > 0.0f && worldZ < mWorldHeight) {
int tileX = (int)(worldX / LandTile.TILE_SIZE);
int tileY = (int)(worldZ / LandTile.TILE_SIZE);
height = mTiles[tileX * mTilesAcross + tileY].getHeight(worldX, worldZ);
}
return height;
}
public void setTextures(int[] landTextures, int skyboxTexture) {
setLandTextures( landTextures );
mSkyboxTexture = skyboxTexture;
if (mNativeRenderer != null) {
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mNativeRenderer.registerTile(landTextures, mTiles[x], false);
}
if (mSkybox != null) {
// Work around since registerTile() takes an array of textures
int textures[] = new int[1];
textures[0] = skyboxTexture;
mNativeRenderer.registerTile(textures, mSkybox, true);
}
}
}
public void draw(GL10 gl, Vector3 cameraPosition) {
if (mNativeRenderer != null) {
mNativeRenderer.draw(true, true);
} else {
if (mSkyboxTexture != 0) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mSkyboxTexture);
}
Grid.beginDrawing(gl, mUseTexture, mUseColors);
if (mSkybox != null) {
gl.glDepthMask(false);
gl.glDisable(GL10.GL_DEPTH_TEST);
mSkybox.draw(gl, cameraPosition);
gl.glDepthMask(true);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mTiles[x].draw(gl, cameraPosition);
}
Grid.endDrawing(gl);
}
}
public void generateHardwareBuffers(GL10 gl) {
mMeshLibrary.generateHardwareBuffers(gl);
}
public void setNativeRenderer(NativeRenderer nativeRenderer) {
mNativeRenderer = nativeRenderer;
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/LandTileMap.java
|
Java
|
asf20
| 5,197
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
/**
* Simple 3D vector class. Handles basic vector math for 3D vectors.
*/
public final class Vector3 {
public float x;
public float y;
public float z;
public static final Vector3 ZERO = new Vector3(0, 0, 0);
public Vector3() {
}
public Vector3(float xValue, float yValue, float zValue) {
set(xValue, yValue, zValue);
}
public Vector3(Vector3 other) {
set(other);
}
public final void add(Vector3 other) {
x += other.x;
y += other.y;
z += other.z;
}
public final void add(float otherX, float otherY, float otherZ) {
x += otherX;
y += otherY;
z += otherZ;
}
public final void subtract(Vector3 other) {
x -= other.x;
y -= other.y;
z -= other.z;
}
public final void multiply(float magnitude) {
x *= magnitude;
y *= magnitude;
z *= magnitude;
}
public final void multiply(Vector3 other) {
x *= other.x;
y *= other.y;
z *= other.z;
}
public final void divide(float magnitude) {
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
}
public final void set(Vector3 other) {
x = other.x;
y = other.y;
z = other.z;
}
public final void set(float xValue, float yValue, float zValue) {
x = xValue;
y = yValue;
z = zValue;
}
public final float dot(Vector3 other) {
return (x * other.x) + (y * other.y) + (z * other.z);
}
public final float length() {
return (float) Math.sqrt(length2());
}
public final float length2() {
return (x * x) + (y * y) + (z * z);
}
public final float distance2(Vector3 other) {
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return (dx * dx) + (dy * dy) + (dz * dz);
}
public final float normalize() {
final float magnitude = length();
// TODO: I'm choosing safety over speed here.
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
return magnitude;
}
public final void zero() {
set(0.0f, 0.0f, 0.0f);
}
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/Vector3.java
|
Java
|
asf20
| 3,028
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
// This is a thin interface for a renderer implemented in C++ using the NDK.
public class NativeRenderer {
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private boolean mCameraDirty = false;
static {
System.loadLibrary("heightmapprofiler");
}
public NativeRenderer() {
nativeReset();
}
public void setCamera(Vector3 camera, Vector3 lookat) {
mCameraPosition = camera;
mLookAtPosition = lookat;
mCameraDirty = true;
}
public void registerTile(int textures[], LandTile tile, boolean isSkybox) {
final Grid[] lods = tile.getLods();
final Vector3 position = tile.getPosition();
final Vector3 center = tile.getCenterPoint();
final int index = nativeAddTile(textures[0], lods.length, tile.getMaxLodDistance(), position.x, position.y, position.z, center.x, center.y, center.z);
if (index >= 0) {
for (int x = 0; x < lods.length; x++) {
nativeAddLod(index, lods[x].getVertexBuffer(), lods[x].getTextureBuffer(), lods[x].getIndexBuffer(), lods[x].getColorBuffer(), lods[x].getIndexCount(), lods[x].getFixedPoint());
}
if (isSkybox) {
nativeSetSkybox(index);
}
for( int i = 1; i < textures.length; ++i ) {
nativeAddTextureLod( index, i, textures[i]);
}
}
}
public void registerSkybox(int texture, Grid mesh, Vector3 position, Vector3 centerPoint) {
}
public void draw(boolean useTexture, boolean useColor) {
nativeRender(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, useTexture, useColor, mCameraDirty);
mCameraDirty = false;
}
private static native void nativeReset();
private static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
private static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
private static native void nativeSetSkybox(int index);
private static native void nativeRender(float cameraX, float cameraY, float cameraZ, float lookAtX, float lookAtY, float lookAtZ, boolean useTexture, boolean useColor, boolean cameraDirty);
private static native void nativeAddTextureLod(int tileIndex, int lod, int textureName);
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/src/com/android/heightmapprofiler/NativeRenderer.java
|
Java
|
asf20
| 3,021
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <GLES/gl.h>
static const char* LogTitle = "HeightMapProfiler";
#ifdef DEBUG
#define ASSERT(x) if (!(x)) { __assert(__FILE__, __LINE__, #x); }
#else
#define ASSERT(X)
#endif
#ifdef REPORTING
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LogTitle, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LogTitle, __VA_ARGS__)
#else
#define LOGE(...)
#define LOGI(...)
#endif
void __assert(const char* pFileName, const int line, const char* pMessage) {
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", "Assert Failed! %s (%s:%d)", pMessage, pFileName, line);
assert(false);
}
struct Mesh {
int vertexBuffer;
int textureBuffer;
int colorBuffer;
int indexBuffer;
int indexCount;
bool useFixedPoint;
};
struct Tile {
// Store a texture value for each texture LOD (Level of Detail)
int textures[4];
float x;
float y;
float z;
float centerX;
float centerY;
float centerZ;
int maxLodCount;
int lodCount;
Mesh lods[4];
float maxLodDistance2;
};
static const int MAX_TILES = 17; //4x4 tiles + 1 skybox. This really shouldn't be hard coded this way though.
static int sTileCount = 0;
static Tile sTiles[MAX_TILES];
static int sSkybox = -1;
static void nativeReset(JNIEnv* env, jobject thiz) {
sTileCount = 0;
sSkybox = -1;
}
// static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
static jint nativeAddTile(
JNIEnv* env,
jobject thiz,
jint texture,
jint lodCount,
jfloat maxLodDistance,
jfloat x,
jfloat y,
jfloat z,
jfloat centerX,
jfloat centerY,
jfloat centerZ) {
LOGI("nativeAddTile");
int index = -1;
if (sTileCount < MAX_TILES) {
index = sTileCount;
Tile* currentTile = &sTiles[index];
currentTile->x = x;
currentTile->y = y;
currentTile->z = z;
currentTile->centerX = centerX;
currentTile->centerY = centerY;
currentTile->centerZ = centerZ;
currentTile->lodCount = 0;
currentTile->maxLodCount = lodCount;
currentTile->maxLodDistance2 = maxLodDistance * maxLodDistance;
// Texture array size hard coded for now
currentTile->textures[0] = texture; // first element takes default LOD texture
currentTile->textures[1] = -1; // rest are set by nativeAddTextureLod() call
currentTile->textures[2] = -1;
currentTile->textures[3] = -1;
sTileCount++;
LOGI("Tile %d: (%g, %g, %g). Max lod: %d", index, x, y, z, lodCount);
}
return index;
}
static void nativeSetSkybox(
JNIEnv* env,
jobject thiz,
jint index) {
if (index < sTileCount && index >= 0) {
sSkybox = index;
}
}
// static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
static void nativeAddLod(
JNIEnv* env,
jobject thiz,
jint index,
jint vertexBuffer,
jint textureBuffer,
jint indexBuffer,
jint colorBuffer,
jint indexCount,
jboolean useFixedPoint) {
LOGI("nativeAddLod (%d)", index);
if (index < sTileCount && index >= 0) {
Tile* currentTile = &sTiles[index];
LOGI("Adding lod for tile %d (%d of %d) - %s", index, currentTile->lodCount, currentTile->maxLodCount, useFixedPoint ? "fixed" : "float");
if (currentTile->lodCount < currentTile->maxLodCount) {
const int meshIndex = currentTile->lodCount;
LOGI("Mesh %d: Index Count: %d", meshIndex, indexCount);
Mesh* lod = ¤tTile->lods[meshIndex];
lod->vertexBuffer = vertexBuffer;
lod->textureBuffer = textureBuffer;
lod->colorBuffer = colorBuffer;
lod->indexBuffer = indexBuffer;
lod->indexCount = indexCount;
lod->useFixedPoint = useFixedPoint;
currentTile->lodCount++;
}
}
}
// static native void nativeAddTextureLod(int index, int lod, int textureName);
static void nativeAddTextureLod(
JNIEnv* env,
jobject thiz,
jint tileIndex,
jint lod,
jint textureName) {
if (tileIndex < sTileCount && tileIndex >= 0) {
Tile* currentTile = &sTiles[tileIndex];
LOGI("Adding texture lod for tile %d lod %d texture name %d", tileIndex, lod, textureName);
if( lod >= sizeof(currentTile->textures)/sizeof(currentTile->textures[0]) ) {
LOGI("Error adding texture lod for tile %d lod %d is out of range ", tileIndex, lod );
}
currentTile->textures[lod] = textureName;
}
}
static void drawTile(int index, float cameraX, float cameraY, float cameraZ, bool useTexture, bool useColor) {
//LOGI("draw tile: %d", index);
if (index < sTileCount) {
Tile* currentTile = &sTiles[index];
const float dx = currentTile->centerX - cameraX;
const float dz = currentTile->centerZ - cameraZ;
const float distanceFromCamera2 = (dx * dx) + (dz * dz);
int lod = currentTile->lodCount - 1;
if (distanceFromCamera2 < currentTile->maxLodDistance2) {
const int bucket = (int)((distanceFromCamera2 / currentTile->maxLodDistance2) * currentTile->lodCount);
lod = bucket < (currentTile->lodCount - 1) ? bucket : currentTile->lodCount - 1;
}
ASSERT(lod < currentTile->lodCount);
Mesh* lodMesh = ¤tTile->lods[lod];
//LOGI("mesh %d: count: %d", index, lodMesh->indexCount);
const GLint coordinateType = lodMesh->useFixedPoint ? GL_FIXED : GL_FLOAT;
glPushMatrix();
glTranslatef(currentTile->x, currentTile->y, currentTile->z);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->vertexBuffer);
glVertexPointer(3, coordinateType, 0, 0);
if (useTexture) {
int texture = currentTile->textures[0];
if( currentTile->textures[lod] != -1 ) {
texture = currentTile->textures[lod];
}
glBindTexture(GL_TEXTURE_2D, texture);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->textureBuffer);
glTexCoordPointer(2, coordinateType, 0, 0);
}
if (useColor) {
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->colorBuffer);
glColorPointer(4, coordinateType, 0, 0);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lodMesh->indexBuffer);
glDrawElements(GL_TRIANGLES, lodMesh->indexCount,
GL_UNSIGNED_SHORT, 0);
glPopMatrix();
}
}
// Blatantly copied from the GLU ES project:
// http://code.google.com/p/glues/
static void __gluMakeIdentityf(GLfloat m[16])
{
m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0;
m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0;
m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0;
m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1;
}
static void normalize(GLfloat v[3])
{
GLfloat r;
r=(GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
if (r==0.0f)
{
return;
}
v[0]/=r;
v[1]/=r;
v[2]/=r;
}
static void cross(GLfloat v1[3], GLfloat v2[3], GLfloat result[3])
{
result[0] = v1[1]*v2[2] - v1[2]*v2[1];
result[1] = v1[2]*v2[0] - v1[0]*v2[2];
result[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
static void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx,
GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy,
GLfloat upz)
{
GLfloat forward[3], side[3], up[3];
GLfloat m[4][4];
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
up[0] = upx;
up[1] = upy;
up[2] = upz;
normalize(forward);
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
__gluMakeIdentityf(&m[0][0]);
m[0][0] = side[0];
m[1][0] = side[1];
m[2][0] = side[2];
m[0][1] = up[0];
m[1][1] = up[1];
m[2][1] = up[2];
m[0][2] = -forward[0];
m[1][2] = -forward[1];
m[2][2] = -forward[2];
glMultMatrixf(&m[0][0]);
glTranslatef(-eyex, -eyey, -eyez);
}
/* Call to render the next GL frame */
static void nativeRender(
JNIEnv* env,
jobject thiz,
jfloat cameraX,
jfloat cameraY,
jfloat cameraZ,
jfloat lookAtX,
jfloat lookAtY,
jfloat lookAtZ,
jboolean useTexture,
jboolean useColor,
jboolean cameraDirty) {
//LOGI("render");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (cameraDirty) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraX, cameraY, cameraZ,
lookAtX, lookAtY, lookAtZ,
0.0f, 1.0f, 0.0f);
}
glEnableClientState(GL_VERTEX_ARRAY);
if (useTexture) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
} else {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
if (useColor) {
glEnableClientState(GL_COLOR_ARRAY);
} else {
glDisableClientState(GL_COLOR_ARRAY);
}
if (sSkybox != -1) {
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
drawTile(sSkybox, cameraX, cameraY, cameraZ, useTexture, useColor);
glDepthMask(true);
glEnable(GL_DEPTH_TEST);
}
for (int x = 0; x < sTileCount; x++) {
if (x != sSkybox) {
drawTile(x, cameraX, cameraY, cameraZ, useTexture, useColor);
}
}
glDisableClientState(GL_VERTEX_ARRAY);
//LOGI("render complete");
}
static const char* classPathName = "com/android/heightmapprofiler/NativeRenderer";
static JNINativeMethod methods[] = {
{"nativeReset", "()V", (void*)nativeReset },
{"nativeRender", "(FFFFFFZZZ)V", (void*)nativeRender },
{"nativeAddTile", "(IIFFFFFFF)I", (void*)nativeAddTile },
{"nativeAddLod", "(IIIIIIZ)V", (void*)nativeAddLod },
{"nativeSetSkybox", "(I)V", (void*)nativeSetSkybox },
{"nativeAddTextureLod", "(III)V", (void*)nativeAddTextureLod},
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
char error[255];
sprintf(error,
"Native registration unable to find class '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
char error[255];
sprintf(error, "RegisterNatives failed for '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*/
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName,
methods, sizeof(methods) / sizeof(methods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Set some test stuff up.
*
* Returns the JNI version on success, -1 on failure.
*/
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
LOGE("ERROR: HeightMapProfiler native registration failed");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
|
zzhangumd-apps-for-android
|
HeightMapProfiler/jni/height_map.cpp
|
C++
|
asf20
| 11,671
|
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := heightmapprofiler
LOCAL_CFLAGS := -DANDROID_NDK #-DREPORTING #-DDEBUG
LOCAL_SRC_FILES := \
height_map.cpp \
LOCAL_LDLIBS := -lGLESv1_CM -ldl -llog
include $(BUILD_SHARED_LIBRARY)
|
zzhangumd-apps-for-android
|
HeightMapProfiler/jni/Android.mk
|
Makefile
|
asf20
| 257
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
/**
* Utilities for loading a bitmap from a URL
*
*/
public class BitmapUtils {
private static final String TAG = "Panoramio";
private static final int IO_BUFFER_SIZE = 4 * 1024;
/**
* Loads a bitmap from the specified url. This can take a while, so it should not
* be called from the UI thread.
*
* @param url The location of the bitmap asset
*
* @return The bitmap, or null if it could not be loaded
*/
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
/**
* Copy the content of the input stream into the output stream, using a
* temporary byte array buffer whose size is defined by
* {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/BitmapUtils.java
|
Java
|
asf20
| 3,235
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Activity which displays a single image.
*/
public class ViewImage extends Activity {
private static final String TAG = "Panoramio";
private static final int MENU_RADAR = Menu.FIRST + 1;
private static final int MENU_MAP = Menu.FIRST + 2;
private static final int MENU_AUTHOR = Menu.FIRST + 3;
private static final int MENU_VIEW = Menu.FIRST + 4;
private static final int DIALOG_NO_RADAR = 1;
PanoramioItem mItem;
private Handler mHandler;
private ImageView mImage;
private TextView mTitle;
private TextView mOwner;
private View mContent;
private int mMapZoom;
private int mMapLatitudeE6;
private int mMapLongitudeE6;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.view_image);
// Remember the user's original search area and zoom level
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
mMapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mMapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mMapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
mHandler = new Handler();
mContent = findViewById(R.id.content);
mImage = (ImageView) findViewById(R.id.image);
mTitle = (TextView) findViewById(R.id.title);
mOwner = (TextView) findViewById(R.id.owner);
mContent.setVisibility(View.GONE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
new LoadThread().start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_RADAR, 0, R.string.menu_radar)
.setIcon(R.drawable.ic_menu_radar)
.setAlphabeticShortcut('R');
menu.add(0, MENU_MAP, 0, R.string.menu_map)
.setIcon(R.drawable.ic_menu_map)
.setAlphabeticShortcut('M');
menu.add(0, MENU_AUTHOR, 0, R.string.menu_author)
.setIcon(R.drawable.ic_menu_author)
.setAlphabeticShortcut('A');
menu.add(0, MENU_VIEW, 0, R.string.menu_view)
.setIcon(android.R.drawable.ic_menu_view)
.setAlphabeticShortcut('V');
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_RADAR: {
// Launch the radar activity (if it is installed)
Intent i = new Intent("com.google.android.radar.SHOW_RADAR");
GeoPoint location = mItem.getLocation();
i.putExtra("latitude", (float)(location.getLatitudeE6() / 1000000f));
i.putExtra("longitude", (float)(location.getLongitudeE6() / 1000000f));
try {
startActivity(i);
} catch (ActivityNotFoundException ex) {
showDialog(DIALOG_NO_RADAR);
}
return true;
}
case MENU_MAP: {
// Display our custom map
Intent i = new Intent(this, ViewMap.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, mItem);
i.putExtra(ImageManager.ZOOM_EXTRA, mMapZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mMapLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mMapLongitudeE6);
startActivity(i);
return true;
}
case MENU_AUTHOR: {
// Display the author info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getOwnerUrl()));
startActivity(i);
return true;
}
case MENU_VIEW: {
// Display the photo info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getPhotoUrl()));
startActivity(i);
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_NO_RADAR:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
return builder.setTitle(R.string.no_radar_title)
.setMessage(R.string.no_radar)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok, null).create();
}
return null;
}
/**
* Utility to load a larger version of the image in a separate thread.
*
*/
private class LoadThread extends Thread {
public LoadThread() {
}
@Override
public void run() {
try {
String uri = mItem.getThumbUrl();
uri = uri.replace("thumbnail", "medium");
final Bitmap b = BitmapUtils.loadBitmap(uri);
mHandler.post(new Runnable() {
public void run() {
mImage.setImageBitmap(b);
mTitle.setText(mItem.getTitle());
mOwner.setText(mItem.getOwner());
mContent.setVisibility(View.VISIBLE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/ViewImage.java
|
Java
|
asf20
| 7,005
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
/**
* Activity which lets the user select a search area
*
*/
public class Panoramio extends MapActivity implements OnClickListener {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
private ImageManager mImageManager;
public static final int MILLION = 1000000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageManager = ImageManager.getInstance(this);
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
Button goButton = (Button) findViewById(R.id.go);
goButton.setOnClickListener(this);
// Add the map view to the frame
mMapView = new MapView(this, "Panoramio_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
// Create an overlay to show current location
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() {
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
}});
mMapView.getOverlays().add(mMyLocationOverlay);
mMapView.getController().setZoom(15);
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Add zoom controls to our frame layout
*/
private void addZoomControls(FrameLayout frame) {
// Get the zoom controls and add them to the bottom of the map
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Starts a new search when the user clicks the search button.
*/
public void onClick(View view) {
// Get the search area
int latHalfSpan = mMapView.getLatitudeSpan() >> 1;
int longHalfSpan = mMapView.getLongitudeSpan() >> 1;
// Remember how the map was displayed so we can show it the same way later
GeoPoint center = mMapView.getMapCenter();
int zoom = mMapView.getZoomLevel();
int latitudeE6 = center.getLatitudeE6();
int longitudeE6 = center.getLongitudeE6();
Intent i = new Intent(this, ImageList.class);
i.putExtra(ImageManager.ZOOM_EXTRA, zoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, latitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, longitudeE6);
float minLong = ((float) (longitudeE6 - longHalfSpan)) / MILLION;
float maxLong = ((float) (longitudeE6 + longHalfSpan)) / MILLION;
float minLat = ((float) (latitudeE6 - latHalfSpan)) / MILLION;
float maxLat = ((float) (latitudeE6 + latHalfSpan)) / MILLION;
mImageManager.clear();
// Start downloading
mImageManager.load(minLong, maxLong, minLat, maxLat);
// Show results
startActivity(i);
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/Panoramio.java
|
Java
|
asf20
| 4,712
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Holds one item returned from the Panoramio server. This includes
* the bitmap along with other meta info.
*
*/
public class PanoramioItem implements Parcelable {
private long mId;
private Bitmap mBitmap;
private GeoPoint mLocation;
private String mTitle;
private String mOwner;
private String mThumbUrl;
private String mOwnerUrl;
private String mPhotoUrl;
public PanoramioItem(Parcel in) {
mId = in.readLong();
mBitmap = Bitmap.CREATOR.createFromParcel(in);
mLocation = new GeoPoint(in.readInt(), in.readInt());
mTitle = in.readString();
mOwner = in.readString();
mThumbUrl = in.readString();
mOwnerUrl = in.readString();
mPhotoUrl = in.readString();
}
public PanoramioItem(long id, String thumbUrl, Bitmap b, int latitudeE6, int longitudeE6,
String title, String owner, String ownerUrl, String photoUrl) {
mBitmap = b;
mLocation = new GeoPoint(latitudeE6, longitudeE6);
mTitle = title;
mOwner = owner;
mThumbUrl = thumbUrl;
mOwnerUrl = ownerUrl;
mPhotoUrl = photoUrl;
}
public long getId() {
return mId;
}
public Bitmap getBitmap() {
return mBitmap;
}
public GeoPoint getLocation() {
return mLocation;
}
public String getTitle() {
return mTitle;
}
public String getOwner() {
return mOwner;
}
public String getThumbUrl() {
return mThumbUrl;
}
public String getOwnerUrl() {
return mOwnerUrl;
}
public String getPhotoUrl() {
return mPhotoUrl;
}
public static final Parcelable.Creator<PanoramioItem> CREATOR =
new Parcelable.Creator<PanoramioItem>() {
public PanoramioItem createFromParcel(Parcel in) {
return new PanoramioItem(in);
}
public PanoramioItem[] newArray(int size) {
return new PanoramioItem[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(mId);
mBitmap.writeToParcel(parcel, 0);
parcel.writeInt(mLocation.getLatitudeE6());
parcel.writeInt(mLocation.getLongitudeE6());
parcel.writeString(mTitle);
parcel.writeString(mOwner);
parcel.writeString(mThumbUrl);
parcel.writeString(mOwnerUrl);
parcel.writeString(mPhotoUrl);
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/PanoramioItem.java
|
Java
|
asf20
| 3,312
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.ArrayList;
/**
* This class is responsible for downloading and parsing the search results for
* a particular area. All of the work is done on a separate thread, and progress
* is reported back through the DataSetObserver set in
* {@link #addObserver(DataSetObserver). State is held in memory by in memory
* maintained by a single instance of the ImageManager class.
*/
public class ImageManager {
private static final String TAG = "Panoramio";
/**
* Base URL for Panoramio's web API
*/
private static final String THUMBNAIL_URL = "//www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&miny=%f&minx=%f&maxy=%f&maxx=%f&size=thumbnail";
/**
* Used to post results back to the UI thread
*/
private Handler mHandler = new Handler();
/**
* Holds the single instance of a ImageManager that is shared by the process.
*/
private static ImageManager sInstance;
/**
* Holds the images and related data that have been downloaded
*/
private ArrayList<PanoramioItem> mImages = new ArrayList<PanoramioItem>();
/**
* Observers interested in changes to the current search results
*/
private ArrayList<WeakReference<DataSetObserver>> mObservers =
new ArrayList<WeakReference<DataSetObserver>>();
/**
* True if we are in the process of loading
*/
private boolean mLoading;
private Context mContext;
/**
* Key for an Intent extra. The value is the zoom level selected by the user.
*/
public static final String ZOOM_EXTRA = "zoom";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LATITUDE_E6_EXTRA = "latitudeE6";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LONGITUDE_E6_EXTRA = "longitudeE6";
/**
* Key for an Intent extra. The value is an item to display
*/
public static final String PANORAMIO_ITEM_EXTRA = "item";
public static ImageManager getInstance(Context c) {
if (sInstance == null) {
sInstance = new ImageManager(c.getApplicationContext());
}
return sInstance;
}
private ImageManager(Context c) {
mContext = c;
}
/**
* @return True if we are still loading content
*/
public boolean isLoading() {
return mLoading;
}
/**
* Clear all downloaded content
*/
public void clear() {
mImages.clear();
notifyObservers();
}
/**
* Add an item to and notify observers of the change.
* @param item The item to add
*/
private void add(PanoramioItem item) {
mImages.add(item);
notifyObservers();
}
/**
* @return The number of items displayed so far
*/
public int size() {
return mImages.size();
}
/**
* Gets the item at the specified position
*/
public PanoramioItem get(int position) {
return mImages.get(position);
}
/**
* Adds an observer to be notified when the set of items held by this ImageManager changes.
*/
public void addObserver(DataSetObserver observer) {
WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
mObservers.add(obs);
}
/**
* Load a new set of search results for the specified area.
*
* @param minLong The minimum longitude for the search area
* @param maxLong The maximum longitude for the search area
* @param minLat The minimum latitude for the search area
* @param maxLat The minimum latitude for the search area
*/
public void load(float minLong, float maxLong, float minLat, float maxLat) {
mLoading = true;
new NetworkThread(minLong, maxLong, minLat, maxLat).start();
}
/**
* Called when something changes in our data set. Cleans up any weak references that
* are no longer valid along the way.
*/
private void notifyObservers() {
final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
final int count = observers.size();
for (int i = count - 1; i >= 0; i--) {
WeakReference<DataSetObserver> weak = observers.get(i);
DataSetObserver obs = weak.get();
if (obs != null) {
obs.onChanged();
} else {
observers.remove(i);
}
}
}
/**
* This thread does the actual work of downloading and parsing data.
*
*/
private class NetworkThread extends Thread {
private float mMinLong;
private float mMaxLong;
private float mMinLat;
private float mMaxLat;
public NetworkThread(float minLong, float maxLong, float minLat, float maxLat) {
mMinLong = minLong;
mMaxLong = maxLong;
mMinLat = minLat;
mMaxLat = maxLat;
}
@Override
public void run() {
String url = THUMBNAIL_URL;
url = String.format(url, mMinLat, mMinLong, mMaxLat, mMaxLong);
try {
URI uri = new URI("http", url, null);
HttpGet get = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String str = convertStreamToString(entity.getContent());
JSONObject json = new JSONObject(str);
parse(json);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void parse(JSONObject json) {
try {
JSONArray array = json.getJSONArray("photos");
int count = array.length();
for (int i = 0; i < count; i++) {
JSONObject obj = array.getJSONObject(i);
long id = obj.getLong("photo_id");
String title = obj.getString("photo_title");
String owner = obj.getString("owner_name");
String thumb = obj.getString("photo_file_url");
String ownerUrl = obj.getString("owner_url");
String photoUrl = obj.getString("photo_url");
double latitude = obj.getDouble("latitude");
double longitude = obj.getDouble("longitude");
Bitmap b = BitmapUtils.loadBitmap(thumb);
if (title == null) {
title = mContext.getString(R.string.untitled);
}
final PanoramioItem item = new PanoramioItem(id, thumb, b,
(int) (latitude * Panoramio.MILLION),
(int) (longitude * Panoramio.MILLION), title, owner,
ownerUrl, photoUrl);
final boolean done = i == count - 1;
mHandler.post(new Runnable() {
public void run() {
sInstance.mLoading = !done;
sInstance.add(item);
}
});
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/ImageManager.java
|
Java
|
asf20
| 9,706
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Adapter used to bind data for the main list of photos
*/
public class ImageAdapter extends BaseAdapter {
/**
* Maintains the state of our data
*/
private ImageManager mImageManager;
private Context mContext;
private MyDataSetObserver mObserver;
/**
* Used by the {@link ImageManager} to report changes in the list back to
* this adapter.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
public ImageAdapter(Context c) {
mImageManager = ImageManager.getInstance(c);
mContext = c;
mObserver = new MyDataSetObserver();
mImageManager.addObserver(mObserver);
}
/**
* Returns the number of images to display
*
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return mImageManager.size();
}
/**
* Returns the image at a specified position
*
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return mImageManager.get(position);
}
/**
* Returns the id of an image at a specified position
*
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
PanoramioItem s = mImageManager.get(position);
return s.getId();
}
/**
* Returns a view to display the image at a specified position
*
* @param position The position to display
* @param convertView An existing view that we can reuse. May be null.
* @param parent The parent view that will eventually hold the view we return.
* @return A view to display the image at a specified position
*/
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
// Make up a new view
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.image_item, null);
} else {
// Use convertView if it is available
view = convertView;
}
PanoramioItem s = mImageManager.get(position);
ImageView i = (ImageView) view.findViewById(R.id.image);
i.setImageBitmap(s.getBitmap());
i.setBackgroundResource(R.drawable.picture_frame);
TextView t = (TextView) view.findViewById(R.id.title);
t.setText(s.getTitle());
t = (TextView) view.findViewById(R.id.owner);
t.setText(s.getOwner());
return view;
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/ImageAdapter.java
|
Java
|
asf20
| 3,758
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
/**
* Activity which displays the list of images.
*/
public class ImageList extends ListActivity {
ImageManager mImageManager;
private MyDataSetObserver mObserver = new MyDataSetObserver();
/**
* The zoom level the user chose when picking the search area
*/
private int mZoom;
/**
* The latitude of the center of the search area chosen by the user
*/
private int mLatitudeE6;
/**
* The longitude of the center of the search area chosen by the user
*/
private int mLongitudeE6;
/**
* Observer used to turn the progress indicator off when the {@link ImageManager} is
* done downloading.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
if (!mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
}
@Override
public void onInvalidated() {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
mImageManager = ImageManager.getInstance(this);
ListView listView = getListView();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View footer = inflater.inflate(R.layout.list_footer, listView, false);
listView.addFooterView(footer, null, false);
setListAdapter(new ImageAdapter(this));
// Theme.Light sets a background on our list.
listView.setBackgroundDrawable(null);
if (mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
mImageManager.addObserver(mObserver);
}
// Read the user's search area from the intent
Intent i = getIntent();
mZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
PanoramioItem item = mImageManager.get(position);
// Create an intent to show a particular item.
// Pass the user's search area along so the next activity can use it
Intent i = new Intent(this, ViewImage.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, item);
i.putExtra(ImageManager.ZOOM_EXTRA, mZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mLongitudeE6);
startActivity(i);
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/ImageList.java
|
Java
|
asf20
| 3,901
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a custom map which shows our current location and the location
* where the photo was taken.
*/
public class ViewMap extends MapActivity {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
ArrayList<PanoramioItem> mItems = null;
private PanoramioItem mItem;
private Drawable mMarker;
private int mMarkerXOffset;
private int mMarkerYOffset;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
mMapView = new MapView(this, "MapViewCompassDemo_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setContentView(frame);
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMarker = getResources().getDrawable(R.drawable.map_pin);
// Make sure to give mMarker bounds so it will draw in the overlay
final int intrinsicWidth = mMarker.getIntrinsicWidth();
final int intrinsicHeight = mMarker.getIntrinsicHeight();
mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight);
mMarkerXOffset = -(intrinsicWidth / 2);
mMarkerYOffset = -intrinsicHeight;
// Read the item we are displaying from the intent, along with the
// parameters used to set up the map
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
int mapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
int mapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
int mapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
final List<Overlay> overlays = mMapView.getOverlays();
overlays.add(mMyLocationOverlay);
overlays.add(new PanoramioOverlay());
final MapController controller = mMapView.getController();
if (mapZoom != Integer.MIN_VALUE && mapLatitudeE6 != Integer.MIN_VALUE
&& mapLongitudeE6 != Integer.MIN_VALUE) {
controller.setZoom(mapZoom);
controller.setCenter(new GeoPoint(mapLatitudeE6, mapLongitudeE6));
} else {
controller.setZoom(15);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
controller.animateTo(mMyLocationOverlay.getMyLocation());
}
});
}
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Get the zoom controls and add them to the bottom of the map
*/
private void addZoomControls(FrameLayout frame) {
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Custom overlay to display the Panoramio pushpin
*/
public class PanoramioOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (!shadow) {
Point point = new Point();
Projection p = mapView.getProjection();
p.toPixels(mItem.getLocation(), point);
super.draw(canvas, mapView, shadow);
drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y + mMarkerYOffset, shadow);
}
}
}
}
|
zzhangumd-apps-for-android
|
Panoramio/src/com/google/android/panoramio/ViewMap.java
|
Java
|
asf20
| 5,413
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// An array of things to draw every frame.
private GLSprite[] mSprites;
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
private int[] mCropWorkspace;
// A reference to the application context.
private Context mContext;
// Determines the use of vertex arrays.
private boolean mUseVerts;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
mCropWorkspace = new int[4];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE };
return configSpec;
}
public void setSprites(GLSprite[] sprites) {
mSprites = sprites;
}
/**
* Changes the vertex mode used for drawing.
* @param useVerts Specifies whether to use a vertex array. If false, the
* DrawTexture extension is used.
* @param useHardwareBuffers Specifies whether to store vertex arrays in
* main memory or on the graphics card. Ignored if useVerts is false.
*/
public void setVertMode(boolean useVerts, boolean useHardwareBuffers) {
mUseVerts = useVerts;
mUseHardwareBuffers = useVerts ? useHardwareBuffers : false;
}
/** Draws the sprites. */
public void drawFrame(GL10 gl) {
if (mSprites != null) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
if (mUseVerts) {
Grid.beginDrawing(gl, true, false);
}
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(gl);
}
if (mUseVerts) {
Grid.endDrawing(gl);
}
}
}
/* Called when the size of the window changes. */
public void sizeChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glEnable(GL10.GL_TEXTURE_2D);
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void surfaceCreated(GL10 gl) {
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glShadeModel(GL10.GL_FLAT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* By default, OpenGL enables features that improve quality but reduce
* performance. One might want to tweak that especially on software
* renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
if (mSprites != null) {
// If we are using hardware buffers and the screen lost context
// then the buffer indexes that we recorded previously are now
// invalid. Forget them here and recreate them below.
if (mUseHardwareBuffers) {
for (int x = 0; x < mSprites.length; x++) {
// Ditch old buffer indexes.
mSprites[x].getGrid().invalidateHardwareBuffers();
}
}
// Load our texture and set its texture name on all sprites.
// To keep this sample simple we will assume that sprites that share
// the same texture are grouped together in our sprite list. A real
// app would probably have another level of texture management,
// like a texture hash.
int lastLoadedResource = -1;
int lastTextureId = -1;
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastLoadedResource) {
lastTextureId = loadBitmap(mContext, gl, resource);
lastLoadedResource = resource;
}
mSprites[x].setTextureName(lastTextureId);
if (mUseHardwareBuffers) {
Grid currentGrid = mSprites[x].getGrid();
if (!currentGrid.usingHardwareBuffers()) {
currentGrid.generateHardwareBuffers(gl);
}
//mSprites[x].getGrid().generateHardwareBuffers(gl);
}
}
}
}
/**
* Called when the rendering thread shuts down. This is a good place to
* release OpenGL ES resources.
* @param gl
*/
public void shutdown(GL10 gl) {
if (mSprites != null) {
int lastFreedResource = -1;
int[] textureToDelete = new int[1];
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastFreedResource) {
textureToDelete[0] = mSprites[x].getTextureName();
gl.glDeleteTextures(1, textureToDelete, 0);
mSprites[x].setTextureName(0);
}
if (mUseHardwareBuffers) {
mSprites[x].getGrid().releaseHardwareBuffers(gl);
}
}
}
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
mCropWorkspace[0] = 0;
mCropWorkspace[1] = bitmap.getHeight();
mCropWorkspace[2] = bitmap.getWidth();
mCropWorkspace[3] = -bitmap.getHeight();
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SpriteMethodTest", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/SimpleGLRenderer.java
|
Java
|
asf20
| 10,357
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
/**
* Main entry point for the SpriteMethodTest application. This application
* provides a simple interface for testing the relative speed of 2D rendering
* systems available on Android, namely the Canvas system and OpenGL ES. It
* also serves as an example of how SurfaceHolders can be used to create an
* efficient rendering thread for drawing.
*/
public class SpriteMethodTest extends Activity {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Sets up a click listener for the Run Test button.
Button button;
button = (Button) findViewById(R.id.runTest);
button.setOnClickListener(mRunTestListener);
// Turns on one item by default in our radio groups--as it should be!
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
group.setOnCheckedChangeListener(mMethodChangedListener);
group.check(R.id.methodCanvas);
RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings);
glSettings.check(R.id.settingVerts);
}
/** Passes preferences about the test via its intent. */
protected void initializeIntent(Intent i) {
final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites);
final boolean animate = checkBox.isChecked();
final EditText editText = (EditText) findViewById(R.id.spriteCount);
final String spriteCountText = editText.getText().toString();
final int stringCount = Integer.parseInt(spriteCountText);
i.putExtra("animate", animate);
i.putExtra("spriteCount", stringCount);
}
/**
* Responds to a click on the Run Test button by launching a new test
* activity.
*/
View.OnClickListener mRunTestListener = new OnClickListener() {
public void onClick(View v) {
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
Intent i;
if (group.getCheckedRadioButtonId() == R.id.methodCanvas) {
i = new Intent(v.getContext(), CanvasTestActivity.class);
} else {
i = new Intent(v.getContext(), OpenGLTestActivity.class);
RadioGroup glSettings =
(RadioGroup)findViewById(R.id.GLSettings);
if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) {
i.putExtra("useVerts", true);
} else if (glSettings.getCheckedRadioButtonId()
== R.id.settingVBO) {
i.putExtra("useVerts", true);
i.putExtra("useHardwareBuffers", true);
}
}
initializeIntent(i);
startActivityForResult(i, ACTIVITY_TEST);
}
};
/**
* Enables or disables OpenGL ES-specific settings controls when the render
* method option changes.
*/
RadioGroup.OnCheckedChangeListener mMethodChangedListener
= new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.methodCanvas) {
findViewById(R.id.settingDrawTexture).setEnabled(false);
findViewById(R.id.settingVerts).setEnabled(false);
findViewById(R.id.settingVBO).setEnabled(false);
} else {
findViewById(R.id.settingDrawTexture).setEnabled(true);
findViewById(R.id.settingVerts).setEnabled(true);
findViewById(R.id.settingVBO).setEnabled(true);
}
}
};
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long flipTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMin =
profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Page Flip: " + flipTime + "ms\n"
+ "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/SpriteMethodTest.java
|
Java
|
asf20
| 8,313
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* This is the OpenGL ES version of a sprite. It is more complicated than the
* CanvasSprite class because it can be used in more than one way. This class
* can draw using a grid of verts, a grid of verts stored in VBO objects, or
* using the DrawTexture extension.
*/
public class GLSprite extends Renderable {
// The OpenGL ES texture handle to draw.
private int mTextureName;
// The id of the original resource that mTextureName is based on.
private int mResourceId;
// If drawing with verts or VBO verts, the grid object defining those verts.
private Grid mGrid;
public GLSprite(int resourceId) {
super();
mResourceId = resourceId;
}
public void setTextureName(int name) {
mTextureName = name;
}
public int getTextureName() {
return mTextureName;
}
public void setResourceId(int id) {
mResourceId = id;
}
public int getResourceId() {
return mResourceId;
}
public void setGrid(Grid grid) {
mGrid = grid;
}
public Grid getGrid() {
return mGrid;
}
public void draw(GL10 gl) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName);
if (mGrid == null) {
// Draw using the DrawTexture extension.
((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height);
} else {
// Draw using verts or VBO verts.
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glTranslatef(
x,
y,
z);
mGrid.draw(gl, true, false);
gl.glPopMatrix();
}
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/GLSprite.java
|
Java
|
asf20
| 2,489
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.graphics.Canvas;
import com.android.spritemethodtest.CanvasSurfaceView.Renderer;
/**
* An extremely simple renderer based on the CanvasSurfaceView drawing
* framework. Simply draws a list of sprites to a canvas every frame.
*/
public class SimpleCanvasRenderer implements Renderer {
private CanvasSprite[] mSprites;
public void setSprites(CanvasSprite[] sprites) {
mSprites = sprites;
}
public void drawFrame(Canvas canvas) {
if (mSprites != null) {
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(canvas);
}
}
}
public void sizeChanged(int width, int height) {
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/SimpleCanvasRenderer.java
|
Java
|
asf20
| 1,384
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to display the scene.
public static final int PROFILE_PAGE_FLIP = 1;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/ProfileRecorder.java
|
Java
|
asf20
| 4,931
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing OpenGL ES drawing speed. This activity sets up sprites
* and passes them off to an OpenGLSurfaceView for rendering and movement.
*/
public class OpenGLTestActivity extends Activity {
private final static int SPRITE_WIDTH = 64;
private final static int SPRITE_HEIGHT = 64;
private GLSurfaceView mGLSurfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this);
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
final boolean useVerts =
callingIntent.getBooleanExtra("useVerts", false);
final boolean useHardwareBuffers =
callingIntent.getBooleanExtra("useHardwareBuffers", false);
// Allocate space for the robot sprites + one background sprite.
GLSprite[] spriteArray = new GLSprite[robotCount + 1];
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
GLSprite background = new GLSprite(R.drawable.background);
BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
Bitmap backgoundBitmap = backgroundImage.getBitmap();
background.width = backgoundBitmap.getWidth();
background.height = backgoundBitmap.getHeight();
if (useVerts) {
// Setup the background grid. This is just a quad.
Grid backgroundGrid = new Grid(2, 2, false);
backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null);
backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null);
backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null);
backgroundGrid.set(1, 1, background.width, background.height, 0.0f,
1.0f, 0.0f, null );
background.setGrid(backgroundGrid);
}
spriteArray[0] = background;
Grid spriteGrid = null;
if (useVerts) {
// Setup a quad for the sprites to use. All sprites will use the
// same sprite grid intance.
spriteGrid = new Grid(2, 2, false);
spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null);
spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null);
spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null);
spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null);
}
// This list of things to move. It points to the same content as the
// sprite list except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
GLSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new GLSprite(R.drawable.skate1);
} else if (x < robotBucketSize * 2) {
robot = new GLSprite(R.drawable.skate2);
} else {
robot = new GLSprite(R.drawable.skate3);
}
robot.width = SPRITE_WIDTH;
robot.height = SPRITE_HEIGHT;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// All sprites can reuse the same grid. If we're running the
// DrawTexture extension test, this is null.
robot.setGrid(spriteGrid);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
spriteRenderer.setVertMode(useVerts, useHardwareBuffers);
mGLSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mGLSurfaceView.setEvent(simulationRuntime);
}
setContentView(mGLSurfaceView);
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/OpenGLTestActivity.java
|
Java
|
asf20
| 6,189
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.os.SystemClock;
/**
* A simple runnable that updates the position of each sprite on the screen
* every frame by applying a very simple gravity and bounce simulation. The
* sprites are jumbled with random velocities every once and a while.
*/
public class Mover implements Runnable {
private Renderable[] mRenderables;
private long mLastTime;
private long mLastJumbleTime;
private int mViewWidth;
private int mViewHeight;
static final float COEFFICIENT_OF_RESTITUTION = 0.75f;
static final float SPEED_OF_GRAVITY = 150.0f;
static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000;
static final float MAX_VELOCITY = 8000.0f;
public void run() {
// Perform a single simulation step.
if (mRenderables != null) {
final long time = SystemClock.uptimeMillis();
final long timeDelta = time - mLastTime;
final float timeDeltaSeconds =
mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f;
mLastTime = time;
// Check to see if it's time to jumble again.
final boolean jumble =
(time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY);
if (jumble) {
mLastJumbleTime = time;
}
for (int x = 0; x < mRenderables.length; x++) {
Renderable object = mRenderables[x];
// Jumble! Apply random velocities.
if (jumble) {
object.velocityX += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
object.velocityY += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
}
// Move.
object.x = object.x + (object.velocityX * timeDeltaSeconds);
object.y = object.y + (object.velocityY * timeDeltaSeconds);
object.z = object.z + (object.velocityZ * timeDeltaSeconds);
// Apply Gravity.
object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds;
// Bounce.
if ((object.x < 0.0f && object.velocityX < 0.0f)
|| (object.x > mViewWidth - object.width
&& object.velocityX > 0.0f)) {
object.velocityX =
-object.velocityX * COEFFICIENT_OF_RESTITUTION;
object.x = Math.max(0.0f,
Math.min(object.x, mViewWidth - object.width));
if (Math.abs(object.velocityX) < 0.1f) {
object.velocityX = 0.0f;
}
}
if ((object.y < 0.0f && object.velocityY < 0.0f)
|| (object.y > mViewHeight - object.height
&& object.velocityY > 0.0f)) {
object.velocityY =
-object.velocityY * COEFFICIENT_OF_RESTITUTION;
object.y = Math.max(0.0f,
Math.min(object.y, mViewHeight - object.height));
if (Math.abs(object.velocityY) < 0.1f) {
object.velocityY = 0.0f;
}
}
}
}
}
public void setRenderables(Renderable[] renderables) {
mRenderables = renderables;
}
public void setViewSize(int width, int height) {
mViewHeight = height;
mViewWidth = width;
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/Mover.java
|
Java
|
asf20
| 4,381
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/Grid.java
|
Java
|
asf20
| 14,378
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing Canvas drawing speed. This activity sets up sprites and
* passes them off to a CanvasSurfaceView for rendering and movement. It is
* very similar to OpenGLTestActivity. Note that Bitmap objects come out of a
* pool and must be explicitly recycled on shutdown. See onDestroy().
*/
public class CanvasTestActivity extends Activity {
private CanvasSurfaceView mCanvasSurfaceView;
// Describes the image format our bitmaps should be converted to.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
private Bitmap[] mBitmaps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCanvasSurfaceView = new CanvasSurfaceView(this);
SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer();
// Sets our preferred image format to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
// Allocate space for the robot sprites + one background sprite.
CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1];
mBitmaps = new Bitmap[4];
mBitmaps[0] = loadBitmap(this, R.drawable.background);
mBitmaps[1] = loadBitmap(this, R.drawable.skate1);
mBitmaps[2] = loadBitmap(this, R.drawable.skate2);
mBitmaps[3] = loadBitmap(this, R.drawable.skate3);
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// Make the background.
// Note that the background image is larger than the screen,
// so some clipping will occur when it is drawn.
CanvasSprite background = new CanvasSprite(mBitmaps[0]);
background.width = mBitmaps[0].getWidth();
background.height = mBitmaps[0].getHeight();
spriteArray[0] = background;
// This list of things to move. It points to the same content as
// spriteArray except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
CanvasSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new CanvasSprite(mBitmaps[1]);
} else if (x < robotBucketSize * 2) {
robot = new CanvasSprite(mBitmaps[2]);
} else {
robot = new CanvasSprite(mBitmaps[3]);
}
robot.width = 64;
robot.height = 64;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
mCanvasSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mCanvasSurfaceView.setEvent(simulationRuntime);
}
setContentView(mCanvasSurfaceView);
}
/** Recycles all of the bitmaps loaded in onCreate(). */
@Override
protected void onDestroy() {
super.onDestroy();
mCanvasSurfaceView.clearEvent();
mCanvasSurfaceView.stopDrawing();
for (int x = 0; x < mBitmaps.length; x++) {
mBitmaps[x].recycle();
mBitmaps[x] = null;
}
}
/**
* Loads a bitmap from a resource and converts it to a bitmap. This is
* a much-simplified version of the loadBitmap() that appears in
* SimpleGLRenderer.
* @param context The application context.
* @param resourceId The id of the resource to load.
* @return A bitmap containing the image contents of the resource, or null
* if there was an error.
*/
protected Bitmap loadBitmap(Context context, int resourceId) {
Bitmap bitmap = null;
if (context != null) {
InputStream is = context.getResources().openRawResource(resourceId);
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
}
return bitmap;
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/CanvasTestActivity.java
|
Java
|
asf20
| 6,609
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file was lifted from the APIDemos sample. See:
// http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html
package com.android.spritemethodtest;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public GLSurfaceView(Context context) {
super(context);
init();
}
public GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
mGLThread.setEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Called when the rendering thread is about to shut down. This is a
* good place to release OpenGL ES resources (textures, buffers, etc).
* @param gl
*/
void shutdown(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
if (mEvent != null) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
/* draw a frame here */
mRenderer.drawFrame(gl);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mEglHelper.swap();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.endFrame();
}
/*
* clean-up everything...
*/
if (gl != null) {
mRenderer.shutdown(gl);
}
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/GLSurfaceView.java
|
Java
|
asf20
| 16,883
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Implements a surface view which writes updates to the surface's canvas using
* a separate rendering thread. This class is based heavily on GLSurfaceView.
*/
public class CanvasSurfaceView extends SurfaceView
implements SurfaceHolder.Callback {
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private CanvasThread mCanvasThread;
public CanvasSurfaceView(Context context) {
super(context);
init();
}
public CanvasSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
/** Sets the user's renderer and kicks off the rendering thread. */
public void setRenderer(Renderer renderer) {
mCanvasThread = new CanvasThread(mHolder, renderer);
mCanvasThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mCanvasThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mCanvasThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mCanvasThread.onWindowResize(w, h);
}
/** Inform the view that the activity is paused.*/
public void onPause() {
mCanvasThread.onPause();
}
/** Inform the view that the activity is resumed. */
public void onResume() {
mCanvasThread.onResume();
}
/** Inform the view that the window focus has changed. */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mCanvasThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
mCanvasThread.setEvent(r);
}
/** Clears the runnable event, if any, from the rendering thread. */
public void clearEvent() {
mCanvasThread.clearEvent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mCanvasThread.requestExitAndWait();
}
protected void stopDrawing() {
mCanvasThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
/** A generic renderer interface. */
public interface Renderer {
/**
* Surface changed size.
* Called after the surface is created and whenever
* the surface size changes. Set your viewport here.
* @param width
* @param height
*/
void sizeChanged(int width, int height);
/**
* Draw the current frame.
* @param canvas The target canvas to draw into.
*/
void drawFrame(Canvas canvas);
}
/**
* A generic Canvas rendering Thread. Delegates to a Renderer instance to do
* the actual drawing.
*/
class CanvasThread extends Thread {
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private SurfaceHolder mSurfaceHolder;
CanvasThread(SurfaceHolder holder, Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
mSurfaceHolder = holder;
setName("CanvasThread");
}
@Override
public void run() {
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
while (!mDone) {
profiler.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w;
int h;
synchronized (this) {
// If the user has set a runnable to run in this thread,
// execute it and record the amount of time it takes to
// run.
if (mEvent != null) {
profiler.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
profiler.stop(ProfileRecorder.PROFILE_SIM);
}
if(needToWait()) {
while (needToWait()) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
if (mDone) {
break;
}
tellRendererSurfaceChanged = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
// Get ready to draw.
// We record both lockCanvas() and unlockCanvasAndPost()
// as part of "page flip" time because either may block
// until the previous frame is complete.
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
Canvas canvas = mSurfaceHolder.lockCanvas();
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
if (canvas != null) {
// Draw a frame!
profiler.start(ProfileRecorder.PROFILE_DRAW);
mRenderer.drawFrame(canvas);
profiler.stop(ProfileRecorder.PROFILE_DRAW);
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mSurfaceHolder.unlockCanvasAndPost(canvas);
profiler.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
}
profiler.stop(ProfileRecorder.PROFILE_FRAME);
profiler.endFrame();
}
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from CanvasThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/CanvasSurfaceView.java
|
Java
|
asf20
| 10,171
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* The Canvas version of a sprite. This class keeps a pointer to a bitmap
* and draws it at the Sprite's current location.
*/
public class CanvasSprite extends Renderable {
private Bitmap mBitmap;
public CanvasSprite(Bitmap bitmap) {
mBitmap = bitmap;
}
public void draw(Canvas canvas) {
// The Canvas system uses a screen-space coordinate system, that is,
// 0,0 is the top-left point of the canvas. But in order to align
// with OpenGL's coordinate space (which places 0,0 and the lower-left),
// for this test I flip the y coordinate.
canvas.drawBitmap(mBitmap, x, canvas.getHeight() - (y + height), null);
}
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/CanvasSprite.java
|
Java
|
asf20
| 1,425
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
/**
* Base class defining the core set of information necessary to render (and move
* an object on the screen. This is an abstract type and must be derived to
* add methods to actually draw (see CanvasSprite and GLSprite).
*/
public abstract class Renderable {
// Position.
public float x;
public float y;
public float z;
// Velocity.
public float velocityX;
public float velocityY;
public float velocityZ;
// Size.
public float width;
public float height;
}
|
zzhangumd-apps-for-android
|
SpriteMethodTest/src/com/android/spritemethodtest/Renderable.java
|
Java
|
asf20
| 1,179
|
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amazed;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
/**
* Maze drawn on screen, each new level is loaded once the previous level has
* been completed.
*/
public class Maze {
// maze tile size and dimension
private final static int TILE_SIZE = 16;
private final static int MAZE_COLS = 20;
private final static int MAZE_ROWS = 26;
// tile types
public final static int PATH_TILE = 0;
public final static int VOID_TILE = 1;
public final static int EXIT_TILE = 2;
// tile colors
private final static int VOID_COLOR = Color.BLACK;
// maze level data
private static int[] mMazeData;
// number of level
public final static int MAX_LEVELS = 10;
// current tile attributes
private Rect mRect = new Rect();
private int mRow;
private int mCol;
private int mX;
private int mY;
// tile bitmaps
private Bitmap mImgPath;
private Bitmap mImgExit;
/**
* Maze constructor.
*
* @param context
* Application context used to load images.
*/
Maze(Activity activity) {
// load bitmaps.
mImgPath = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(),
R.drawable.path);
mImgExit = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(),
R.drawable.exit);
}
/**
* Load specified maze level.
*
* @param activity
* Activity controlled the maze, we use this load the level data
* @param newLevel
* Maze level to be loaded.
*/
void load(Activity activity, int newLevel) {
// maze data is stored in the assets folder as level1.txt, level2.txt
// etc....
String mLevel = "level" + newLevel + ".txt";
InputStream is = null;
try {
// construct our maze data array.
mMazeData = new int[MAZE_ROWS * MAZE_COLS];
// attempt to load maze data.
is = activity.getAssets().open(mLevel);
// we need to loop through the input stream and load each tile for
// the current maze.
for (int i = 0; i < mMazeData.length; i++) {
// data is stored in unicode so we need to convert it.
mMazeData[i] = Character.getNumericValue(is.read());
// skip the "," and white space in our human readable file.
is.read();
is.read();
}
} catch (Exception e) {
Log.i("Maze", "load exception: " + e);
} finally {
closeStream(is);
}
}
/**
* Draw the maze.
*
* @param canvas
* Canvas object to draw too.
* @param paint
* Paint object used to draw with.
*/
public void draw(Canvas canvas, Paint paint) {
// loop through our maze and draw each tile individually.
for (int i = 0; i < mMazeData.length; i++) {
// calculate the row and column of the current tile.
mRow = i / MAZE_COLS;
mCol = i % MAZE_COLS;
// convert the row and column into actual x,y co-ordinates so we can
// draw it on screen.
mX = mCol * TILE_SIZE;
mY = mRow * TILE_SIZE;
// draw the actual tile based on type.
if (mMazeData[i] == PATH_TILE)
canvas.drawBitmap(mImgPath, mX, mY, paint);
else if (mMazeData[i] == EXIT_TILE)
canvas.drawBitmap(mImgExit, mX, mY, paint);
else if (mMazeData[i] == VOID_TILE) {
// since our "void" tile is purely black lets draw a rectangle
// instead of using an image.
// tile attributes we are going to paint.
mRect.left = mX;
mRect.top = mY;
mRect.right = mX + TILE_SIZE;
mRect.bottom = mY + TILE_SIZE;
paint.setColor(VOID_COLOR);
canvas.drawRect(mRect, paint);
}
}
}
/**
* Determine which cell the marble currently occupies.
*
* @param x
* Current x co-ordinate.
* @param y
* Current y co-ordinate.
* @return The actual cell occupied by the marble.
*/
public int getCellType(int x, int y) {
// convert the x,y co-ordinate into row and col values.
int mCellCol = x / TILE_SIZE;
int mCellRow = y / TILE_SIZE;
// location is the row,col coordinate converted so we know where in the
// maze array to look.
int mLocation = 0;
// if we are beyond the 1st row need to multiple by the number of
// columns.
if (mCellRow > 0)
mLocation = mCellRow * MAZE_COLS;
// add the column location.
mLocation += mCellCol;
return mMazeData[mLocation];
}
/**
* Closes the specified stream.
*
* @param stream
* The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
|
zzhangumd-apps-for-android
|
Amazed/src/com/example/amazed/Maze.java
|
Java
|
asf20
| 6,298
|
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amazed;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
/**
* Custom view used to draw the maze and marble. Responds to accelerometer
* updates to roll the marble around the screen.
*/
public class AmazedView extends View {
// Game objects
private Marble mMarble;
private Maze mMaze;
private Activity mActivity;
// canvas we paint to.
private Canvas mCanvas;
private Paint mPaint;
private Typeface mFont = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
private int mTextPadding = 10;
private int mHudTextY = 440;
// game states
private final static int NULL_STATE = -1;
private final static int GAME_INIT = 0;
private final static int GAME_RUNNING = 1;
private final static int GAME_OVER = 2;
private final static int GAME_COMPLETE = 3;
private final static int GAME_LANDSCAPE = 4;
// current state of the game
private static int mCurState = NULL_STATE;
// game strings
private final static int TXT_LIVES = 0;
private final static int TXT_LEVEL = 1;
private final static int TXT_TIME = 2;
private final static int TXT_TAP_SCREEN = 3;
private final static int TXT_GAME_COMPLETE = 4;
private final static int TXT_GAME_OVER = 5;
private final static int TXT_TOTAL_TIME = 6;
private final static int TXT_GAME_OVER_MSG_A = 7;
private final static int TXT_GAME_OVER_MSG_B = 8;
private final static int TXT_RESTART = 9;
private final static int TXT_LANDSCAPE_MODE = 10;
private static String mStrings[];
// this prevents the user from dying instantly when they start a level if
// the device is tilted.
private boolean mWarning = false;
// screen dimensions
private int mCanvasWidth = 0;
private int mCanvasHeight = 0;
private int mCanvasHalfWidth = 0;
private int mCanvasHalfHeight = 0;
// are we running in portrait mode.
private boolean mPortrait;
// current level
private int mlevel = 1;
// timing used for scoring.
private long mTotalTime = 0;
private long mStartTime = 0;
private long mEndTime = 0;
// sensor manager used to control the accelerometer sensor.
private SensorManager mSensorManager;
// accelerometer sensor values.
private float mAccelX = 0;
private float mAccelY = 0;
private float mAccelZ = 0; // this is never used but just in-case future
// versions make use of it.
// accelerometer buffer, currently set to 0 so even the slightest movement
// will roll the marble.
private float mSensorBuffer = 0;
// http://code.google.com/android/reference/android/hardware/SensorManager.html#SENSOR_ACCELEROMETER
// for an explanation on the values reported by SENSOR_ACCELEROMETER.
private final SensorListener mSensorAccelerometer = new SensorListener() {
// method called whenever new sensor values are reported.
public void onSensorChanged(int sensor, float[] values) {
// grab the values required to respond to user movement.
mAccelX = values[0];
mAccelY = values[1];
mAccelZ = values[2];
}
// reports when the accuracy of sensor has change
// SENSOR_STATUS_ACCURACY_HIGH = 3
// SENSOR_STATUS_ACCURACY_LOW = 1
// SENSOR_STATUS_ACCURACY_MEDIUM = 2
// SENSOR_STATUS_UNRELIABLE = 0 //calibration required.
public void onAccuracyChanged(int sensor, int accuracy) {
// currently not used
}
};
/**
* Custom view constructor.
*
* @param context
* Application context
* @param activity
* Activity controlling the view
*/
public AmazedView(Context context, Activity activity) {
super(context);
mActivity = activity;
// init paint and make is look "nice" with anti-aliasing.
mPaint = new Paint();
mPaint.setTextSize(14);
mPaint.setTypeface(mFont);
mPaint.setAntiAlias(true);
// setup accelerometer sensor manager.
mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
// register our accelerometer so we can receive values.
// SENSOR_DELAY_GAME is the recommended rate for games
mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
// setup our maze and marble.
mMaze = new Maze(mActivity);
mMarble = new Marble(this);
// load array from /res/values/strings.xml
mStrings = getResources().getStringArray(R.array.gameStrings);
// set the starting state of the game.
switchGameState(GAME_INIT);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// get new screen dimensions.
mCanvasWidth = w;
mCanvasHeight = h;
mCanvasHalfWidth = w / 2;
mCanvasHalfHeight = h / 2;
// are we in portrait or landscape mode now?
// you could use bPortrait = !bPortrait however in the future who know's
// how many different ways a device screen may be rotated.
if (mCanvasHeight > mCanvasWidth)
mPortrait = true;
else {
mPortrait = false;
switchGameState(GAME_LANDSCAPE);
}
}
/**
* Called every cycle, used to process current game state.
*/
public void gameTick() {
// very basic state machine, makes a good foundation for a more complex
// game.
switch (mCurState) {
case GAME_INIT:
// prepare a new game for the user.
initNewGame();
switchGameState(GAME_RUNNING);
case GAME_RUNNING:
// update our marble.
if (!mWarning)
updateMarble();
break;
}
// redraw the screen once our tick function is complete.
invalidate();
}
/**
* Reset game variables in preparation for a new game.
*/
public void initNewGame() {
mMarble.setLives(5);
mTotalTime = 0;
mlevel = 0;
initLevel();
}
/**
* Initialize the next level.
*/
public void initLevel() {
if (mlevel < mMaze.MAX_LEVELS) {
// setup the next level.
mWarning = true;
mlevel++;
mMaze.load(mActivity, mlevel);
mMarble.init();
} else {
// user has finished the game, update state machine.
switchGameState(GAME_COMPLETE);
}
}
/**
* Called from gameTick(), update marble x,y based on latest values obtained
* from the Accelerometer sensor. AccelX and accelY are values received from
* the accelerometer, higher values represent the device tilted at a more
* acute angle.
*/
public void updateMarble() {
// we CAN give ourselves a buffer to stop the marble from rolling even
// though we think the device is "flat".
if (mAccelX > mSensorBuffer || mAccelX < -mSensorBuffer)
mMarble.updateX(mAccelX);
if (mAccelY > mSensorBuffer || mAccelY < -mSensorBuffer)
mMarble.updateY(mAccelY);
// check which cell the marble is currently occupying.
if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.VOID_TILE) {
// user entered the "void".
if (mMarble.getLives() > 0) {
// user still has some lives remaining, restart the level.
mMarble.death();
mMarble.init();
mWarning = true;
} else {
// user has no more lives left, end of game.
mEndTime = System.currentTimeMillis();
mTotalTime += mEndTime - mStartTime;
switchGameState(GAME_OVER);
}
} else if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.EXIT_TILE) {
// user has reached the exit tiles, prepare the next level.
mEndTime = System.currentTimeMillis();
mTotalTime += mEndTime - mStartTime;
initLevel();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// we only want to handle down events .
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mCurState == GAME_OVER || mCurState == GAME_COMPLETE) {
// re-start the game.
mCurState = GAME_INIT;
} else if (mCurState == GAME_RUNNING) {
// in-game, remove the pop-up text so user can play.
mWarning = false;
mStartTime = System.currentTimeMillis();
}
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// quit application if user presses the back key.
if (keyCode == KeyEvent.KEYCODE_BACK)
cleanUp();
return true;
}
@Override
public void onDraw(Canvas canvas) {
// update our canvas reference.
mCanvas = canvas;
// clear the screen.
mPaint.setColor(Color.WHITE);
mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint);
// simple state machine, draw screen depending on the current state.
switch (mCurState) {
case GAME_RUNNING:
// draw our maze first since everything else appears "on top" of it.
mMaze.draw(mCanvas, mPaint);
// draw our marble and hud.
mMarble.draw(mCanvas, mPaint);
// draw hud
drawHUD();
break;
case GAME_OVER:
drawGameOver();
break;
case GAME_COMPLETE:
drawGameComplete();
break;
case GAME_LANDSCAPE:
drawLandscapeMode();
break;
}
gameTick();
}
/**
* Called from onDraw(), draws the in-game HUD
*/
public void drawHUD() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.LEFT);
mCanvas.drawText(mStrings[TXT_TIME] + ": " + (mTotalTime / 1000), mTextPadding, mHudTextY,
mPaint);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_LEVEL] + ": " + mlevel, mCanvasHalfWidth, mHudTextY, mPaint);
mPaint.setTextAlign(Paint.Align.RIGHT);
mCanvas.drawText(mStrings[TXT_LIVES] + ": " + mMarble.getLives(), mCanvasWidth - mTextPadding,
mHudTextY, mPaint);
// do we need to display the warning message to save the user from
// possibly dying instantly.
if (mWarning) {
mPaint.setColor(Color.BLUE);
mCanvas
.drawRect(0, mCanvasHalfHeight - 15, mCanvasWidth, mCanvasHalfHeight + 5,
mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_TAP_SCREEN], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
}
}
/**
* Called from onDraw(), draws the game over screen.
*/
public void drawGameOver() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_GAME_OVER], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s",
mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint);
mCanvas.drawText(mStrings[TXT_GAME_OVER_MSG_A] + " " + (mlevel - 1) + " "
+ mStrings[TXT_GAME_OVER_MSG_B], mCanvasHalfWidth, mCanvasHalfHeight
+ (mPaint.getFontSpacing() * 2), mPaint);
mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight
- (mPaint.getFontSpacing() * 3), mPaint);
}
/**
* Called from onDraw(), draws the game complete screen.
*/
public void drawGameComplete() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[GAME_COMPLETE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s",
mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint);
mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight
- (mPaint.getFontSpacing() * 3), mPaint);
}
/**
* Called from onDraw(), displays a message asking the user to return the
* device back to portrait mode.
*/
public void drawLandscapeMode() {
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint);
mPaint.setColor(Color.BLACK);
mCanvas.drawText(mStrings[TXT_LANDSCAPE_MODE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
}
/**
* Updates the current game state with a new state. At the moment this is
* very basic however if the game was to get more complicated the code
* required for changing game states could grow quickly.
*
* @param newState
* New game state
*/
public void switchGameState(int newState) {
mCurState = newState;
}
/**
* Register the accelerometer sensor so we can use it in-game.
*/
public void registerListener() {
mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
}
/**
* Unregister the accelerometer sensor otherwise it will continue to operate
* and report values.
*/
public void unregisterListener() {
mSensorManager.unregisterListener(mSensorAccelerometer);
}
/**
* Clean up the custom view and exit the application.
*/
public void cleanUp() {
mMarble = null;
mMaze = null;
mStrings = null;
unregisterListener();
mActivity.finish();
}
}
|
zzhangumd-apps-for-android
|
Amazed/src/com/example/amazed/AmazedView.java
|
Java
|
asf20
| 15,197
|
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amazed;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
/**
* Activity responsible for controlling the application.
*/
public class AmazedActivity extends Activity {
// custom view
private AmazedView mView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title bar.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setup our view, give it focus and display.
mView = new AmazedView(getApplicationContext(), this);
mView.setFocusable(true);
setContentView(mView);
}
@Override
protected void onResume() {
super.onResume();
mView.registerListener();
}
@Override
public void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
mView.unregisterListener();
}
}
|
zzhangumd-apps-for-android
|
Amazed/src/com/example/amazed/AmazedActivity.java
|
Java
|
asf20
| 1,535
|
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amazed;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
/**
* Marble drawn in the maze.
*/
public class Marble {
// View controlling the marble.
private View mView;
// marble attributes
// x,y are private because we need boundary checking on any new values to
// make sure they are valid.
private int mX = 0;
private int mY = 0;
private int mRadius = 8;
private int mColor = Color.WHITE;
private int mLives = 5;
/**
* Marble constructor.
*
* @param view
* View controlling the marble
*/
public Marble(View view) {
this.mView = view;
init();
}
/**
* Setup marble starting co-ords.
*/
public void init() {
mX = mRadius * 6;
mY = mRadius * 6;
}
/**
* Draw the marble.
*
* @param canvas
* Canvas object to draw too.
* @param paint
* Paint object used to draw with.
*/
public void draw(Canvas canvas, Paint paint) {
paint.setColor(mColor);
canvas.drawCircle(mX, mY, mRadius, paint);
}
/**
* Attempt to update the marble with a new x value, boundary checking
* enabled to make sure the new co-ordinate is valid.
*
* @param newX
* Incremental value to add onto current x co-ordinate.
*/
public void updateX(float newX) {
mX += newX;
// boundary checking, don't want the marble rolling off-screen.
if (mX + mRadius >= mView.getWidth())
mX = mView.getWidth() - mRadius;
else if (mX - mRadius < 0)
mX = mRadius;
}
/**
* Attempt to update the marble with a new y value, boundary checking
* enabled to make sure the new co-ordinate is valid.
*
* @param newY
* Incremental value to add onto current y co-ordinate.
*/
public void updateY(float newY) {
mY -= newY;
// boundary checking, don't want the marble rolling off-screen.
if (mY + mRadius >= mView.getHeight())
mY = mView.getHeight() - mRadius;
else if (mY - mRadius < 0)
mY = mRadius;
}
/**
* Marble has died
*/
public void death() {
mLives--;
}
/**
* Set the number of lives for the marble
*
* @param Number
* of lives
*/
public void setLives(int val) {
mLives = val;
}
/**
* @return Number of lives left
*/
public int getLives() {
return mLives;
}
/**
* @return Current x co-ordinate.
*/
public int getX() {
return mX;
}
/**
* @return Current y co-ordinate.
*/
public int getY() {
return mY;
}
}
|
zzhangumd-apps-for-android
|
Amazed/src/com/example/amazed/Marble.java
|
Java
|
asf20
| 3,482
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.android.rings_extended;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.util.SparseIntArray;
/**
* This class essentially helps in building an index of section boundaries of a
* sorted column of a cursor. For instance, if a cursor contains a data set
* sorted by first name of a person or the title of a song, this class will
* perform a binary search to identify the first row that begins with a
* particular letter. The search is case-insensitive. The class caches the index
* such that subsequent queries for the same letter will return right away.
*
* <p>This file was copied from the Contacts application. In the future it
* should be provided as a standard part of the Android framework.
*/
public class AlphabetIndexer extends DataSetObserver {
protected Cursor mDataCursor;
protected int mColumnIndex;
protected Object[] mAlphabetArray;
private SparseIntArray mAlphaMap;
private java.text.Collator mCollator;
/**
* Constructs the indexer.
* @param cursor the cursor containing the data set
* @param columnIndex the column number in the cursor that is sorted
* alphabetically
* @param sections the array of objects that represent the sections. The
* toString() method of each item is called and the first letter of the
* String is used as the letter to search for.
*/
public AlphabetIndexer(Cursor cursor, int columnIndex, Object[] sections) {
mDataCursor = cursor;
mColumnIndex = columnIndex;
mAlphabetArray = sections;
mAlphaMap = new SparseIntArray(26 /* Optimize for English */);
if (cursor != null) {
cursor.registerDataSetObserver(this);
}
// Get a Collator for the current locale for string comparisons.
mCollator = java.text.Collator.getInstance();
mCollator.setStrength(java.text.Collator.PRIMARY);
}
/**
* Sets a new cursor as the data set and resets the cache of indices.
* @param cursor the new cursor to use as the data set
*/
public void setCursor(Cursor cursor) {
if (mDataCursor != null) {
mDataCursor.unregisterDataSetObserver(this);
}
mDataCursor = cursor;
if (cursor != null) {
mDataCursor.registerDataSetObserver(this);
}
mAlphaMap.clear();
}
/**
* Performs a binary search or cache lookup to find the first row that
* matches a given section's starting letter.
* @param sectionIndex the section to search for
* @return the row index of the first occurrence, or the nearest next letter.
* For instance, if searching for "T" and no "T" is found, then the first
* row starting with "U" or any higher letter is returned. If there is no
* data following "T" at all, then the list size is returned.
*/
public int indexOf(int sectionIndex) {
final SparseIntArray alphaMap = mAlphaMap;
final Cursor cursor = mDataCursor;
if (cursor == null || mAlphabetArray == null) {
return 0;
}
// Check bounds
if (sectionIndex <= 0) {
return 0;
}
if (sectionIndex >= mAlphabetArray.length) {
sectionIndex = mAlphabetArray.length - 1;
}
int savedCursorPos = cursor.getPosition();
int count = cursor.getCount();
int start = 0;
int end = count;
int pos;
String letter = mAlphabetArray[sectionIndex].toString();
letter = letter.toUpperCase();
int key = letter.charAt(0);
// Check map
if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) {
// Is it approximate? Using negative value to indicate that it's
// an approximation and positive value when it is the accurate
// position.
if (pos < 0) {
pos = -pos;
end = pos;
} else {
// Not approximate, this is the confirmed start of section, return it
return pos;
}
}
// Do we have the position of the previous section?
if (sectionIndex > 0) {
int prevLetter =
mAlphabetArray[sectionIndex - 1].toString().charAt(0);
int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE);
if (prevLetterPos != Integer.MIN_VALUE) {
start = Math.abs(prevLetterPos);
}
}
// Now that we have a possibly optimized start and end, let's binary search
pos = (end + start) / 2;
while (pos < end) {
// Get letter at pos
cursor.moveToPosition(pos);
String curName = cursor.getString(mColumnIndex);
if (curName == null) {
if (pos == 0) {
break;
} else {
pos--;
continue;
}
}
int curLetter = Character.toUpperCase(curName.charAt(0));
if (curLetter != key) {
// Enter approximation in hash if a better solution doesn't exist
int curPos = alphaMap.get(curLetter, Integer.MIN_VALUE);
if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) {
// Negative pos indicates that it is an approximation
alphaMap.put(curLetter, -pos);
}
if (mCollator.compare(curName, letter) < 0) {
start = pos + 1;
if (start >= count) {
pos = count;
break;
}
} else {
end = pos;
}
} else {
// They're the same, but that doesn't mean it's the start
if (start == pos) {
// This is it
break;
} else {
// Need to go further lower to find the starting row
end = pos;
}
}
pos = (start + end) / 2;
}
alphaMap.put(key, pos);
cursor.moveToPosition(savedCursorPos);
return pos;
}
@Override
public void onChanged() {
super.onChanged();
mAlphaMap.clear();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mAlphaMap.clear();
}
}
|
zzhangumd-apps-for-android
|
RingsExtended/src/com/example/android/rings_extended/AlphabetIndexer.java
|
Java
|
asf20
| 7,177
|
package com.example.android.rings_extended;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Config;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The RingsExtended application, implementing an advanced ringtone picker.
* This is a ListActivity display an adapter of dynamic state built by the
* activity: at the top are simple options the user can be picked, next an
* item to run the built-in ringtone picker, and next are any other activities
* that can supply music Uris.
*/
public class RingsExtended extends ListActivity
implements View.OnClickListener, MediaPlayer.OnCompletionListener {
static final boolean DBG = false;
static final String TAG = "RingsExtended";
/**
* Request code when we are launching an activity to handle our same
* original Intent, meaning we can propagate its result back to our caller
* as-is.
*/
static final int REQUEST_ORIGINAL = 2;
/**
* Request code when launching an activity that returns an audio Uri,
* meaning we need to translate its result into one that our caller
* expects.
*/
static final int REQUEST_SOUND = 1;
Adapter mAdapter;
private View mOkayButton;
private View mCancelButton;
/** Where the silent option item is in the list, or -1 if there is none. */
private int mSilentItemIdx = -1;
/** The Uri to play when the 'Default' item is clicked. */
private Uri mUriForDefaultItem;
/** Where the default option item is in the list, or -1 if there is none. */
private int mDefaultItemIdx = -1;
/** The Uri to place a checkmark next to. */
private Uri mExistingUri;
/** Where the existing option item is in the list. */
private int mExistingItemIdx;
/** Currently selected options in the radio buttons, if any. */
private long mSelectedItem = -1;
/** Loaded ringtone for the existing URI. */
private Ringtone mExistingRingtone;
/** Id of option that is currently playing. */
private long mPlayingId = -1;
/** Used for playing previews of ring tones. */
private MediaPlayer mMediaPlayer;
/**
* Information about one static item in the list. This is used for items
* that are added and handled manually, which don't have an Intent
* associated with them.
*/
final static class ItemInfo {
final CharSequence name;
final CharSequence subtitle;
final Drawable icon;
ItemInfo(CharSequence _name, CharSequence _subtitle, Drawable _icon) {
name = _name;
subtitle = _subtitle;
icon = _icon;
}
}
/**
* Our special adapter implementation, merging the various kinds of items
* that we will display into one list. There are two sections to the
* list of items:
* (1) First are any fixed items as described by ItemInfo objects.
* (2) Next are any activities that do the same thing as our own.
* (3) Finally are any activities that can execute a different Intent.
*/
private final class Adapter extends BaseAdapter {
private final List<ItemInfo> mInitialItems;
private final Intent mIntent;
private final Intent mOrigIntent;
private final LayoutInflater mInflater;
private List<ResolveInfo> mList;
private int mRealListStart = 0;
class ViewHolder {
ImageView icon;
RadioButton radio;
TextView textSingle;
TextView textDouble1;
TextView textDouble2;
ImageView more;
}
/**
* Create a new adapter with the items to be displayed.
*
* @param context The Context we are running in.
* @param initialItems A fixed set of items that appear at the
* top of the list.
* @param origIntent The original Intent that was used to launch this
* activity, used to find all activities that can do the same thing.
* @param excludeOrigIntent Our component name, to exclude from the
* origIntent list since that is what the user is already running!
* @param intent An Intent used to query for additional items to
* appear in the rest of the list.
*/
public Adapter(Context context, List<ItemInfo> initialItems,
Intent origIntent, ComponentName excludeOrigIntent, Intent intent) {
mInitialItems = initialItems;
mIntent = new Intent(intent);
mIntent.setComponent(null);
mIntent.setFlags(0);
if (origIntent != null) {
mOrigIntent = new Intent(origIntent);
mOrigIntent.setComponent(null);
mOrigIntent.setFlags(0);
} else {
mOrigIntent = null;
}
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mList = getActivities(context, mIntent, null);
if (origIntent != null) {
List<ResolveInfo> orig = getActivities(context, mOrigIntent,
excludeOrigIntent);
if (orig != null && orig.size() > 0) {
mRealListStart = orig.size();
orig.addAll(mList);
mList = orig;
}
}
}
/**
* If the position is within the range of initial items, return the
* corresponding index into that array. Otherwise return -1.
*/
public int initialItemForPosition(int position) {
if (position >= getIntentStartIndex()) {
return -1;
}
return position;
}
/**
* Returns true if the given position is for one of the
* "original intent" items.
*/
public boolean isOrigIntentPosition(int position) {
position -= getIntentStartIndex();
return position >= 0 && position < mRealListStart;
}
/**
* Returns the ResolveInfo corresponding to the given position, or null
* if that position is not an Intent item (that is if it is one
* of the static list items).
*/
public ResolveInfo resolveInfoForPosition(int position) {
position -= getIntentStartIndex();
if (mList == null || position < 0) {
return null;
}
return mList.get(position);
}
/**
* Returns the Intent corresponding to the given position, or null
* if that position is not an Intent item (that is if it is one
* of the static list items).
*/
public Intent intentForPosition(int position) {
position -= getIntentStartIndex();
if (mList == null || position < 0) {
return null;
}
Intent intent = new Intent(
position >= mRealListStart ? mIntent : mOrigIntent);
ActivityInfo ai = mList.get(position).activityInfo;
intent.setComponent(new ComponentName(
ai.applicationInfo.packageName, ai.name));
return intent;
}
public int getCount() {
return getIntentStartIndex() + (mList != null ? mList.size() : 0);
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.list_item, parent, false);
ViewHolder vh = new ViewHolder();
vh.icon = (ImageView)view.findViewById(R.id.icon);
vh.radio = (RadioButton)view.findViewById(R.id.radio);
vh.textSingle = (TextView)view.findViewById(R.id.textSingle);
vh.textDouble1 = (TextView)view.findViewById(R.id.textDouble1);
vh.textDouble2 = (TextView)view.findViewById(R.id.textDouble2);
vh.more = (ImageView)view.findViewById(R.id.more);
view.setTag(vh);
} else {
view = convertView;
}
int intentStart = getIntentStartIndex();
if (position < intentStart) {
bindView(view, position, mInitialItems.get(position));
} else {
bindView(view, mList.get(position-intentStart));
}
return view;
}
private final int getIntentStartIndex() {
return mInitialItems != null ? mInitialItems.size() : 0;
}
private final void bindView(View view, ResolveInfo info) {
PackageManager pm = getPackageManager();
ViewHolder vh = (ViewHolder)view.getTag();
CharSequence label = info.loadLabel(pm);
if (label == null) label = info.activityInfo.name;
bindTextViews(vh, label, null);
vh.icon.setImageDrawable(info.loadIcon(pm));
vh.icon.setVisibility(View.VISIBLE);
vh.radio.setVisibility(View.GONE);
vh.more.setImageResource(R.drawable.icon_more);
vh.more.setVisibility(View.VISIBLE);
}
private final void bindTextViews(ViewHolder vh, CharSequence txt1,
CharSequence txt2) {
if (txt2 == null) {
vh.textSingle.setText(txt1);
vh.textSingle.setVisibility(View.VISIBLE);
vh.textDouble1.setVisibility(View.INVISIBLE);
vh.textDouble2.setVisibility(View.INVISIBLE);
} else {
vh.textDouble1.setText(txt1);
vh.textDouble1.setVisibility(View.VISIBLE);
vh.textDouble2.setText(txt2);
vh.textDouble2.setVisibility(View.VISIBLE);
vh.textSingle.setVisibility(View.INVISIBLE);
}
}
private final void bindView(View view, int position, ItemInfo inf) {
ViewHolder vh = (ViewHolder)view.getTag();
bindTextViews(vh, inf.name, inf.subtitle);
// Set the standard icon and radio button. When the radio button
// is displayed, we mark it if this is the currently selected row,
// meaning we need to invalidate the view list whenever the
// selection changes.
if (inf.icon != null) {
vh.icon.setImageDrawable(inf.icon);
vh.icon.setVisibility(View.VISIBLE);
vh.radio.setVisibility(View.GONE);
} else {
vh.icon.setVisibility(View.GONE);
vh.radio.setVisibility(View.VISIBLE);
vh.radio.setChecked(position == mSelectedItem);
}
// Show the "now playing" icon if this item is playing. Doing this
// means that we need to invalidate the displayed views when the
// playing state changes.
if (mPlayingId == position) {
vh.more.setImageResource(R.drawable.now_playing);
vh.more.setVisibility(View.VISIBLE);
} else {
vh.more.setVisibility(View.GONE);
}
}
}
/**
* Retrieve a list of all of the activities that can handle the given Intent,
* optionally excluding the explicit component 'exclude'. The returned list
* is sorted by the label for reach resolved activity.
*/
static final List<ResolveInfo> getActivities(Context context, Intent intent,
ComponentName exclude) {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list != null) {
int N = list.size();
if (exclude != null) {
for (int i=0; i<N; i++) {
ResolveInfo ri = list.get(i);
if (ri.activityInfo.packageName.equals(exclude.getPackageName())
|| ri.activityInfo.name.equals(exclude.getClassName())) {
list.remove(i);
N--;
}
}
}
if (N > 1) {
// Only display the first matches that are either of equal
// priority or have asked to be default options.
ResolveInfo r0 = list.get(0);
for (int i=1; i<N; i++) {
ResolveInfo ri = list.get(i);
if (Config.LOGV) Log.v(
"ResolveListActivity",
r0.activityInfo.name + "=" +
r0.priority + "/" + r0.isDefault + " vs " +
ri.activityInfo.name + "=" +
ri.priority + "/" + ri.isDefault);
if (r0.priority != ri.priority ||
r0.isDefault != ri.isDefault) {
while (i < N) {
list.remove(i);
N--;
}
}
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
}
}
return list;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rings_extended);
mOkayButton = findViewById(R.id.okayButton);
mOkayButton.setOnClickListener(this);
mCancelButton = findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(this);
Intent intent = getIntent();
/*
* Get whether to show the 'Default' item, and the URI to play when the
* default is clicked
*/
mUriForDefaultItem = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI);
if (mUriForDefaultItem == null) {
mUriForDefaultItem = Settings.System.DEFAULT_RINGTONE_URI;
}
// Get the URI whose list item should have a checkmark
mExistingUri = intent
.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
// We are now going to build the set of static items.
ArrayList<ItemInfo> initialItems = new ArrayList<ItemInfo>();
// If the caller has asked to allow the user to select "silent", then
// show an option for that.
if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)) {
mSilentItemIdx = initialItems.size();
initialItems.add(new ItemInfo(getText(R.string.silentLabel),
null, null));
}
// If the caller has asked to allow the user to select "default", then
// show an option for that.
if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)) {
mDefaultItemIdx = initialItems.size();
Ringtone defRing = RingtoneManager.getRingtone(this, mUriForDefaultItem);
initialItems.add(new ItemInfo(getText(R.string.defaultRingtoneLabel),
defRing.getTitle(this), null));
}
// If the caller has supplied a currently selected Uri, then show an
// open for keeping that.
if (mExistingUri != null) {
mExistingRingtone = RingtoneManager.getRingtone(this, mExistingUri);
mExistingItemIdx = initialItems.size();
initialItems.add(new ItemInfo(getText(R.string.existingRingtoneLabel),
mExistingRingtone.getTitle(this), null));
}
if (DBG) {
Log.v(TAG, "default=" + mUriForDefaultItem);
Log.v(TAG, "existing=" + mExistingUri);
}
// Figure out which of the static items should start out with its
// radio button checked.
if (mExistingUri == null) {
if (mSilentItemIdx >= 0) {
mSelectedItem = mSilentItemIdx;
}
} else if (mDefaultItemIdx >= 0 && mExistingUri.equals(mUriForDefaultItem)) {
mSelectedItem = mDefaultItemIdx;
} else {
mSelectedItem = mExistingItemIdx;
}
if (mSelectedItem >= 0) {
mOkayButton.setEnabled(true);
}
mAdapter = new Adapter(this, initialItems, getIntent(), getComponentName(),
new Intent(Intent.ACTION_GET_CONTENT).setType("audio/mp3")
.addCategory(Intent.CATEGORY_OPENABLE));
this.setListAdapter(mAdapter);
}
@Override public void onPause() {
super.onPause();
stopMediaPlayer();
}
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayer == mp) {
mp.stop();
mp.release();
mMediaPlayer = null;
mPlayingId = -1;
getListView().invalidateViews();
}
}
private void stopMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mPlayingId = -1;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
int initialItem = mAdapter.initialItemForPosition((int)id);
if (initialItem >= 0) {
// If the selected item is from our static list, then take
// care of handling it.
mSelectedItem = initialItem;
Uri uri = getSelectedUri();
// If a new item has been selected, then play it for the user.
if (uri != null && (id != mPlayingId || mMediaPlayer == null)) {
stopMediaPlayer();
mMediaPlayer = new MediaPlayer();
try {
if (DBG) Log.v(TAG, "Playing: " + uri);
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.prepare();
mMediaPlayer.start();
mPlayingId = id;
getListView().invalidateViews();
} catch (IOException e) {
Log.w("MusicPicker", "Unable to play track", e);
}
// Otherwise stop any currently playing item.
} else if (mMediaPlayer != null) {
stopMediaPlayer();
getListView().invalidateViews();
}
getListView().invalidateViews();
mOkayButton.setEnabled(true);
} else if (mAdapter.isOrigIntentPosition((int)id)) {
// If the item is one of the original intent activities, then
// launch it with the result code to simply propagate its result
// back to our caller.
Intent intent = mAdapter.intentForPosition((int)id);
startActivityForResult(intent, REQUEST_ORIGINAL);
} else {
// If the item is one of the music retrieval activities, then launch
// it with the result code to transform its result into our caller's
// expected result.
Intent intent = mAdapter.intentForPosition((int)id);
intent.putExtras(getIntent());
startActivityForResult(intent, REQUEST_SOUND);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SOUND && resultCode == RESULT_OK) {
Intent resultIntent = new Intent();
Uri uri = data != null ? data.getData() : null;
resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);
setResult(RESULT_OK, resultIntent);
finish();
} else if (requestCode == REQUEST_ORIGINAL && resultCode == RESULT_OK) {
setResult(RESULT_OK, data);
finish();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.okayButton:
Intent resultIntent = new Intent();
Uri uri = getSelectedUri();
resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);
setResult(RESULT_OK, resultIntent);
finish();
break;
case R.id.cancelButton:
finish();
break;
}
}
private Uri getSelectedUri() {
if (mSelectedItem == mSilentItemIdx) {
// The null uri is silent.
return null;
} else if (mSelectedItem == mDefaultItemIdx) {
return mUriForDefaultItem;
} else if (mSelectedItem == mExistingItemIdx) {
return mExistingUri;
}
return null;
}
}
|
zzhangumd-apps-for-android
|
RingsExtended/src/com/example/android/rings_extended/RingsExtended.java
|
Java
|
asf20
| 22,239
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.android.rings_extended;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
/**
* FastScrollView is meant for embedding {@link ListView}s that contain a large number of
* items that can be indexed in some fashion. It displays a special scroll bar that allows jumping
* quickly to indexed sections of the list in touch-mode. Only one child can be added to this
* view group and it must be a {@link ListView}, with an adapter that is derived from
* {@link BaseAdapter}.
*
* <p>This file was copied from the Contacts application. In the future it
* should be provided as a standard part of the Android framework.
*/
public class FastScrollView extends FrameLayout
implements OnScrollListener, OnHierarchyChangeListener {
private Drawable mCurrentThumb;
private Drawable mOverlayDrawable;
private int mThumbH;
private int mThumbW;
private int mThumbY;
private RectF mOverlayPos;
// Hard coding these for now
private int mOverlaySize = 104;
private boolean mDragging;
private ListView mList;
private boolean mScrollCompleted;
private boolean mThumbVisible;
private int mVisibleItem;
private Paint mPaint;
private int mListOffset;
private Object [] mSections;
private String mSectionText;
private boolean mDrawOverlay;
private ScrollFade mScrollFade;
private Handler mHandler = new Handler();
private BaseAdapter mListAdapter;
private boolean mChangedBounds;
interface SectionIndexer {
Object[] getSections();
int getPositionForSection(int section);
int getSectionForPosition(int position);
}
public FastScrollView(Context context) {
super(context);
init(context);
}
public FastScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FastScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void useThumbDrawable(Drawable drawable) {
mCurrentThumb = drawable;
mThumbW = 64; //mCurrentThumb.getIntrinsicWidth();
mThumbH = 52; //mCurrentThumb.getIntrinsicHeight();
mChangedBounds = true;
}
private void init(Context context) {
// Get both the scrollbar states drawables
final Resources res = context.getResources();
useThumbDrawable(res.getDrawable(
R.drawable.scrollbar_handle_accelerated_anim2));
mOverlayDrawable = res.getDrawable(android.R.drawable.alert_dark_frame);
mScrollCompleted = true;
setWillNotDraw(false);
// Need to know when the ListView is added
setOnHierarchyChangeListener(this);
mOverlayPos = new RectF();
mScrollFade = new ScrollFade();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(mOverlaySize / 2);
mPaint.setColor(0xFFFFFFFF);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
}
private void removeThumb() {
mThumbVisible = false;
// Draw one last time to remove thumb
invalidate();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (!mThumbVisible) {
// No need to draw the rest
return;
}
final int y = mThumbY;
final int viewWidth = getWidth();
final FastScrollView.ScrollFade scrollFade = mScrollFade;
int alpha = -1;
if (scrollFade.mStarted) {
alpha = scrollFade.getAlpha();
if (alpha < ScrollFade.ALPHA_MAX / 2) {
mCurrentThumb.setAlpha(alpha * 2);
}
int left = viewWidth - (mThumbW * alpha) / ScrollFade.ALPHA_MAX;
mCurrentThumb.setBounds(left, 0, viewWidth, mThumbH);
mChangedBounds = true;
}
canvas.translate(0, y);
mCurrentThumb.draw(canvas);
canvas.translate(0, -y);
// If user is dragging the scroll bar, draw the alphabet overlay
if (mDragging && mDrawOverlay) {
mOverlayDrawable.draw(canvas);
final Paint paint = mPaint;
float descent = paint.descent();
final RectF rectF = mOverlayPos;
canvas.drawText(mSectionText, (int) (rectF.left + rectF.right) / 2,
(int) (rectF.bottom + rectF.top) / 2 + mOverlaySize / 4 - descent, paint);
} else if (alpha == 0) {
scrollFade.mStarted = false;
removeThumb();
} else {
invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mCurrentThumb != null) {
mCurrentThumb.setBounds(w - mThumbW, 0, w, mThumbH);
}
final RectF pos = mOverlayPos;
pos.left = (w - mOverlaySize) / 2;
pos.right = pos.left + mOverlaySize;
pos.top = h / 10; // 10% from top
pos.bottom = pos.top + mOverlaySize;
mOverlayDrawable.setBounds((int) pos.left, (int) pos.top,
(int) pos.right, (int) pos.bottom);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (totalItemCount - visibleItemCount > 0 && !mDragging) {
mThumbY = ((getHeight() - mThumbH) * firstVisibleItem) / (totalItemCount - visibleItemCount);
if (mChangedBounds) {
final int viewWidth = getWidth();
mCurrentThumb.setBounds(viewWidth - mThumbW, 0, viewWidth, mThumbH);
mChangedBounds = false;
}
}
mScrollCompleted = true;
if (firstVisibleItem == mVisibleItem) {
return;
}
mVisibleItem = firstVisibleItem;
if (!mThumbVisible || mScrollFade.mStarted) {
mThumbVisible = true;
mCurrentThumb.setAlpha(ScrollFade.ALPHA_MAX);
}
mHandler.removeCallbacks(mScrollFade);
mScrollFade.mStarted = false;
if (!mDragging) {
mHandler.postDelayed(mScrollFade, 1500);
}
}
private void getSections() {
Adapter adapter = mList.getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
mListOffset = ((HeaderViewListAdapter)adapter).getHeadersCount();
adapter = ((HeaderViewListAdapter)adapter).getWrappedAdapter();
}
if (adapter instanceof SectionIndexer) {
mListAdapter = (BaseAdapter) adapter;
mSections = ((SectionIndexer) mListAdapter).getSections();
}
}
public void onChildViewAdded(View parent, View child) {
if (child instanceof ListView) {
mList = (ListView)child;
mList.setOnScrollListener(this);
getSections();
}
}
public void onChildViewRemoved(View parent, View child) {
if (child == mList) {
mList = null;
mListAdapter = null;
mSections = null;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mThumbVisible && ev.getAction() == MotionEvent.ACTION_DOWN) {
if (ev.getX() > getWidth() - mThumbW && ev.getY() >= mThumbY &&
ev.getY() <= mThumbY + mThumbH) {
mDragging = true;
return true;
}
}
return false;
}
private void scrollTo(float position) {
int count = mList.getCount();
mScrollCompleted = false;
final Object[] sections = mSections;
int sectionIndex;
if (sections != null && sections.length > 1) {
final int nSections = sections.length;
int section = (int) (position * nSections);
if (section >= nSections) {
section = nSections - 1;
}
sectionIndex = section;
final SectionIndexer baseAdapter = (SectionIndexer) mListAdapter;
int index = baseAdapter.getPositionForSection(section);
// Given the expected section and index, the following code will
// try to account for missing sections (no names starting with..)
// It will compute the scroll space of surrounding empty sections
// and interpolate the currently visible letter's range across the
// available space, so that there is always some list movement while
// the user moves the thumb.
int nextIndex = count;
int prevIndex = index;
int prevSection = section;
int nextSection = section + 1;
// Assume the next section is unique
if (section < nSections - 1) {
nextIndex = baseAdapter.getPositionForSection(section + 1);
}
// Find the previous index if we're slicing the previous section
if (nextIndex == index) {
// Non-existent letter
while (section > 0) {
section--;
prevIndex = baseAdapter.getPositionForSection(section);
if (prevIndex != index) {
prevSection = section;
sectionIndex = section;
break;
}
}
}
// Find the next index, in case the assumed next index is not
// unique. For instance, if there is no P, then request for P's
// position actually returns Q's. So we need to look ahead to make
// sure that there is really a Q at Q's position. If not, move
// further down...
int nextNextSection = nextSection + 1;
while (nextNextSection < nSections &&
baseAdapter.getPositionForSection(nextNextSection) == nextIndex) {
nextNextSection++;
nextSection++;
}
// Compute the beginning and ending scroll range percentage of the
// currently visible letter. This could be equal to or greater than
// (1 / nSections).
float fPrev = (float) prevSection / nSections;
float fNext = (float) nextSection / nSections;
index = prevIndex + (int) ((nextIndex - prevIndex) * (position - fPrev)
/ (fNext - fPrev));
// Don't overflow
if (index > count - 1) index = count - 1;
mList.setSelectionFromTop(index + mListOffset, 0);
} else {
int index = (int) (position * count);
mList.setSelectionFromTop(index + mListOffset, 0);
sectionIndex = -1;
}
if (sectionIndex >= 0) {
String text = mSectionText = sections[sectionIndex].toString();
mDrawOverlay = (text.length() != 1 || text.charAt(0) != ' ') &&
sectionIndex < sections.length;
} else {
mDrawOverlay = false;
}
}
private void cancelFling() {
// Cancel the list fling
MotionEvent cancelFling = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mList.onTouchEvent(cancelFling);
cancelFling.recycle();
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
if (me.getX() > getWidth() - mThumbW
&& me.getY() >= mThumbY
&& me.getY() <= mThumbY + mThumbH) {
mDragging = true;
if (mListAdapter == null && mList != null) {
getSections();
}
cancelFling();
return true;
}
} else if (me.getAction() == MotionEvent.ACTION_UP) {
if (mDragging) {
mDragging = false;
final Handler handler = mHandler;
handler.removeCallbacks(mScrollFade);
handler.postDelayed(mScrollFade, 1000);
return true;
}
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (mDragging) {
final int viewHeight = getHeight();
mThumbY = (int) me.getY() - mThumbH + 10;
if (mThumbY < 0) {
mThumbY = 0;
} else if (mThumbY + mThumbH > viewHeight) {
mThumbY = viewHeight - mThumbH;
}
// If the previous scrollTo is still pending
if (mScrollCompleted) {
scrollTo((float) mThumbY / (viewHeight - mThumbH));
}
return true;
}
}
return super.onTouchEvent(me);
}
public class ScrollFade implements Runnable {
long mStartTime;
long mFadeDuration;
boolean mStarted;
static final int ALPHA_MAX = 255;
static final long FADE_DURATION = 200;
void startFade() {
mFadeDuration = FADE_DURATION;
mStartTime = SystemClock.uptimeMillis();
mStarted = true;
}
int getAlpha() {
if (!mStarted) {
return ALPHA_MAX;
}
int alpha;
long now = SystemClock.uptimeMillis();
if (now > mStartTime + mFadeDuration) {
alpha = 0;
} else {
alpha = (int) (ALPHA_MAX - ((now - mStartTime) * ALPHA_MAX) / mFadeDuration);
}
return alpha;
}
public void run() {
if (!mStarted) {
startFade();
invalidate();
}
if (getAlpha() > 0) {
final int y = mThumbY;
final int viewWidth = getWidth();
invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH);
} else {
mStarted = false;
removeThumb();
}
}
}
}
|
zzhangumd-apps-for-android
|
RingsExtended/src/com/example/android/rings_extended/FastScrollView.java
|
Java
|
asf20
| 15,855
|
package com.example.android.rings_extended;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.io.IOException;
import java.text.Collator;
import java.util.Formatter;
import java.util.Locale;
/**
* Activity allowing the user to select a music track on the device, and
* return it to its caller. The music picker user interface is fairly
* extensive, providing information about each track like the music
* application (title, author, album, duration), as well as the ability to
* previous tracks and sort them in different orders.
*
* <p>This class also illustrates how you can load data from a content
* provider asynchronously, providing a good UI while doing so, perform
* indexing of the content for use inside of a {@link FastScrollView}, and
* perform filtering of the data as the user presses keys.
*/
public class MusicPicker extends ListActivity
implements View.OnClickListener, MediaPlayer.OnCompletionListener {
static final boolean DBG = false;
static final String TAG = "MusicPicker";
/** Holds the previous state of the list, to restore after the async
* query has completed. */
static final String LIST_STATE_KEY = "liststate";
/** Remember whether the list last had focus for restoring its state. */
static final String FOCUS_KEY = "focused";
/** Remember the last ordering mode for restoring state. */
static final String SORT_MODE_KEY = "sortMode";
/** Arbitrary number, doesn't matter since we only do one query type. */
final int MY_QUERY_TOKEN = 42;
/** Menu item to sort the music list by track title. */
static final int TRACK_MENU = Menu.FIRST;
/** Menu item to sort the music list by album title. */
static final int ALBUM_MENU = Menu.FIRST+1;
/** Menu item to sort the music list by artist name. */
static final int ARTIST_MENU = Menu.FIRST+2;
/** These are the columns in the music cursor that we are interested in. */
static final String[] CURSOR_COLS = new String[] {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TITLE_KEY,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.TRACK
};
/** Formatting optimization to avoid creating many temporary objects. */
static StringBuilder sFormatBuilder = new StringBuilder();
/** Formatting optimization to avoid creating many temporary objects. */
static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
/** Formatting optimization to avoid creating many temporary objects. */
static final Object[] sTimeArgs = new Object[5];
/** Uri to the directory of all music being displayed. */
Uri mBaseUri;
/** This is the adapter used to display all of the tracks. */
TrackListAdapter mAdapter;
/** Our instance of QueryHandler used to perform async background queries. */
QueryHandler mQueryHandler;
/** Used to keep track of the last scroll state of the list. */
Parcelable mListState = null;
/** Used to keep track of whether the list last had focus. */
boolean mListHasFocus;
/** The current cursor on the music that is being displayed. */
Cursor mCursor;
/** The actual sort order the user has selected. */
int mSortMode = -1;
/** SQL order by string describing the currently selected sort order. */
String mSortOrder;
/** Container of the in-screen progress indicator, to be able to hide it
* when done loading the initial cursor. */
View mProgressContainer;
/** Container of the list view hierarchy, to be able to show it when done
* loading the initial cursor. */
View mListContainer;
/** Set to true when the list view has been shown for the first time. */
boolean mListShown;
/** View holding the okay button. */
View mOkayButton;
/** View holding the cancel button. */
View mCancelButton;
/** Which track row ID the user has last selected. */
long mSelectedId = -1;
/** Completel Uri that the user has last selected. */
Uri mSelectedUri;
/** If >= 0, we are currently playing a track for preview, and this is its
* row ID. */
long mPlayingId = -1;
/** This is used for playing previews of the music files. */
MediaPlayer mMediaPlayer;
/**
* A special implementation of SimpleCursorAdapter that knows how to bind
* our cursor data to our list item structure, and takes care of other
* advanced features such as indexing and filtering.
*/
class TrackListAdapter extends SimpleCursorAdapter
implements FastScrollView.SectionIndexer {
final ListView mListView;
private final StringBuilder mBuilder = new StringBuilder();
private final String mUnknownArtist;
private final String mUnknownAlbum;
private int mIdIdx;
private int mTitleIdx;
private int mArtistIdx;
private int mAlbumIdx;
private int mDurationIdx;
private int mAudioIdIdx;
private int mTrackIdx;
private boolean mLoading = true;
private String [] mAlphabet;
private int mIndexerSortMode;
private boolean mIndexerOutOfDate;
private AlphabetIndexer mIndexer;
class ViewHolder {
TextView line1;
TextView line2;
TextView duration;
RadioButton radio;
ImageView play_indicator;
CharArrayBuffer buffer1;
char [] buffer2;
}
TrackListAdapter(Context context, ListView listView, int layout,
String[] from, int[] to) {
super(context, layout, null, from, to);
mListView = listView;
mUnknownArtist = context.getString(R.string.unknownArtistName);
mUnknownAlbum = context.getString(R.string.unknownAlbumName);
getAlphabet(context);
}
/**
* The mLoading flag is set while we are performing a background
* query, to avoid displaying the "No music" empty view during
* this time.
*/
public void setLoading(boolean loading) {
mLoading = loading;
}
@Override
public boolean isEmpty() {
if (mLoading) {
// We don't want the empty state to show when loading.
return false;
} else {
return super.isEmpty();
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.duration = (TextView) v.findViewById(R.id.duration);
vh.radio = (RadioButton) v.findViewById(R.id.radio);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.buffer1 = new CharArrayBuffer(100);
vh.buffer2 = new char[200];
v.setTag(vh);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder vh = (ViewHolder) view.getTag();
cursor.copyStringToBuffer(mTitleIdx, vh.buffer1);
vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied);
int secs = cursor.getInt(mDurationIdx) / 1000;
if (secs == 0) {
vh.duration.setText("");
} else {
vh.duration.setText(makeTimeString(context, secs));
}
final StringBuilder builder = mBuilder;
builder.delete(0, builder.length());
String name = cursor.getString(mAlbumIdx);
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
builder.append(mUnknownAlbum);
} else {
builder.append(name);
}
builder.append('\n');
name = cursor.getString(mArtistIdx);
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
builder.append(mUnknownArtist);
} else {
builder.append(name);
}
int len = builder.length();
if (vh.buffer2.length < len) {
vh.buffer2 = new char[len];
}
builder.getChars(0, len, vh.buffer2, 0);
vh.line2.setText(vh.buffer2, 0, len);
// Update the checkbox of the item, based on which the user last
// selected. Note that doing it this way means we must have the
// list view update all of its items when the selected item
// changes.
final long id = cursor.getLong(mIdIdx);
vh.radio.setChecked(id == mSelectedId);
if (DBG) Log.v(TAG, "Binding id=" + id + " sel=" + mSelectedId
+ " playing=" + mPlayingId + " cursor=" + cursor);
// Likewise, display the "now playing" icon if this item is
// currently being previewed for the user.
ImageView iv = vh.play_indicator;
if (id == mPlayingId) {
iv.setImageResource(R.drawable.now_playing);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.GONE);
}
}
/**
* This method is called whenever we receive a new cursor due to
* an async query, and must take care of plugging the new one in
* to the adapter.
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
if (DBG) Log.v(TAG, "Setting cursor to: " + cursor
+ " from: " + MusicPicker.this.mCursor);
MusicPicker.this.mCursor = cursor;
if (cursor != null) {
// Retrieve indices of the various columns we are interested in.
mIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
mTitleIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
mArtistIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
mAlbumIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mDurationIdx = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
int audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
if (audioIdIdx < 0) {
audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
}
mAudioIdIdx = audioIdIdx;
mTrackIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK);
}
// The next time the indexer is needed, we will need to rebind it
// to this cursor.
mIndexerOutOfDate = true;
// Ensure that the list is shown (and initial progress indicator
// hidden) in case this is the first cursor we have gotten.
makeListShown();
}
/**
* This method is called from a background thread by the list view
* when the user has typed a letter that should result in a filtering
* of the displayed items. It returns a Cursor, when will then be
* handed to changeCursor.
*/
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (DBG) Log.v(TAG, "Getting new cursor...");
return doQuery(true, constraint.toString());
}
/**
* Build a list of alphabetic characters appropriate for the
* current locale.
*/
private void getAlphabet(Context context) {
String alphabetString = context.getResources().getString(R.string.alphabet);
mAlphabet = new String[alphabetString.length()];
for (int i = 0; i < mAlphabet.length; i++) {
mAlphabet[i] = String.valueOf(alphabetString.charAt(i));
}
}
public int getPositionForSection(int section) {
Cursor cursor = getCursor();
if (cursor == null) {
// No cursor, the section doesn't exist so just return 0
return 0;
}
// If the sort mode has changed, or we haven't yet created an
// indexer one, then create a new one that is indexing the
// appropriate column based on the sort mode.
if (mIndexerSortMode != mSortMode || mIndexer == null) {
mIndexerSortMode = mSortMode;
int idx = mTitleIdx;
switch (mIndexerSortMode) {
case ARTIST_MENU:
idx = mArtistIdx;
break;
case ALBUM_MENU:
idx = mAlbumIdx;
break;
}
mIndexer = new AlphabetIndexer(cursor, idx, mAlphabet);
// If we have a valid indexer, but the cursor has changed since
// its last use, then point it to the current cursor.
} else if (mIndexerOutOfDate) {
mIndexer.setCursor(cursor);
}
mIndexerOutOfDate = false;
return mIndexer.indexOf(section);
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
return mAlphabet;
}
}
/**
* This is our specialization of AsyncQueryHandler applies new cursors
* to our state as they become available.
*/
private final class QueryHandler extends AsyncQueryHandler {
public QueryHandler(Context context) {
super(context.getContentResolver());
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
if (!isFinishing()) {
// Update the adapter: we are no longer loading, and have
// a new cursor for it.
mAdapter.setLoading(false);
mAdapter.changeCursor(cursor);
setProgressBarIndeterminateVisibility(false);
// Now that the cursor is populated again, it's possible to restore the list state
if (mListState != null) {
getListView().onRestoreInstanceState(mListState);
if (mListHasFocus) {
getListView().requestFocus();
}
mListHasFocus = false;
mListState = null;
}
} else {
cursor.close();
}
}
}
public static String makeTimeString(Context context, long secs) {
String durationformat = context.getString(R.string.durationformat);
/* Provide multiple arguments so the format can be changed easily
* by modifying the xml.
*/
sFormatBuilder.setLength(0);
final Object[] timeArgs = sTimeArgs;
timeArgs[0] = secs / 3600;
timeArgs[1] = secs / 60;
timeArgs[2] = (secs / 60) % 60;
timeArgs[3] = secs;
timeArgs[4] = secs % 60;
return sFormatter.format(durationformat, timeArgs).toString();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTitle(R.string.musicPickerTitle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
int sortMode = TRACK_MENU;
if (icicle == null) {
mSelectedUri = getIntent().getParcelableExtra(
RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
} else {
mSelectedUri = (Uri)icicle.getParcelable(
RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
// Retrieve list state. This will be applied after the
// QueryHandler has run
mListState = icicle.getParcelable(LIST_STATE_KEY);
mListHasFocus = icicle.getBoolean(FOCUS_KEY);
sortMode = icicle.getInt(SORT_MODE_KEY, sortMode);
}
if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) {
mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else {
mBaseUri = getIntent().getData();
if (mBaseUri == null) {
Log.w("MusicPicker", "No data URI given to PICK action");
finish();
return;
}
}
setContentView(R.layout.music_picker);
mSortOrder = MediaStore.Audio.Media.TITLE_KEY;
final ListView listView = getListView();
listView.setItemsCanFocus(false);
mAdapter = new TrackListAdapter(this, listView,
R.layout.track_list_item, new String[] {},
new int[] {});
setListAdapter(mAdapter);
listView.setTextFilterEnabled(true);
// We manually save/restore the listview state
listView.setSaveEnabled(false);
mQueryHandler = new QueryHandler(this);
mProgressContainer = findViewById(R.id.progressContainer);
mListContainer = findViewById(R.id.listContainer);
mOkayButton = findViewById(R.id.okayButton);
mOkayButton.setOnClickListener(this);
mCancelButton = findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(this);
// If there is a currently selected Uri, then try to determine who
// it is.
if (mSelectedUri != null) {
Uri.Builder builder = mSelectedUri.buildUpon();
String path = mSelectedUri.getEncodedPath();
int idx = path.lastIndexOf('/');
if (idx >= 0) {
path = path.substring(0, idx);
}
builder.encodedPath(path);
Uri baseSelectedUri = builder.build();
if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri);
if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri);
if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri);
if (baseSelectedUri.equals(mBaseUri)) {
// If the base Uri of the selected Uri is the same as our
// content's base Uri, then use the selection!
mSelectedId = ContentUris.parseId(mSelectedUri);
}
}
setSortMode(sortMode);
}
@Override public void onRestart() {
super.onRestart();
doQuery(false, null);
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
if (setSortMode(item.getItemId())) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, TRACK_MENU, Menu.NONE, R.string.sortByTrack);
menu.add(Menu.NONE, ALBUM_MENU, Menu.NONE, R.string.sortByAlbum);
menu.add(Menu.NONE, ARTIST_MENU, Menu.NONE, R.string.sortByArtist);
return true;
}
@Override protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
// Save list state in the bundle so we can restore it after the
// QueryHandler has run
icicle.putParcelable(LIST_STATE_KEY, getListView().onSaveInstanceState());
icicle.putBoolean(FOCUS_KEY, getListView().hasFocus());
icicle.putInt(SORT_MODE_KEY, mSortMode);
}
@Override public void onPause() {
super.onPause();
stopMediaPlayer();
}
@Override public void onStop() {
super.onStop();
// We don't want the list to display the empty state, since when we
// resume it will still be there and show up while the new query is
// happening. After the async query finishes in response to onResume()
// setLoading(false) will be called.
mAdapter.setLoading(true);
mAdapter.changeCursor(null);
}
/**
* Changes the current sort order, building the appropriate query string
* for the selected order.
*/
boolean setSortMode(int sortMode) {
if (sortMode != mSortMode) {
switch (sortMode) {
case TRACK_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.TITLE_KEY;
doQuery(false, null);
return true;
case ALBUM_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.ALBUM_KEY + " ASC, "
+ MediaStore.Audio.Media.TRACK + " ASC, "
+ MediaStore.Audio.Media.TITLE_KEY + " ASC";
doQuery(false, null);
return true;
case ARTIST_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.ARTIST_KEY + " ASC, "
+ MediaStore.Audio.Media.ALBUM_KEY + " ASC, "
+ MediaStore.Audio.Media.TRACK + " ASC, "
+ MediaStore.Audio.Media.TITLE_KEY + " ASC";
doQuery(false, null);
return true;
}
}
return false;
}
/**
* The first time this is called, we hide the large progress indicator
* and show the list view, doing fade animations between them.
*/
void makeListShown() {
if (!mListShown) {
mListShown = true;
mProgressContainer.startAnimation(AnimationUtils.loadAnimation(
this, android.R.anim.fade_out));
mProgressContainer.setVisibility(View.GONE);
mListContainer.startAnimation(AnimationUtils.loadAnimation(
this, android.R.anim.fade_in));
mListContainer.setVisibility(View.VISIBLE);
}
}
/**
* Common method for performing a query of the music database, called for
* both top-level queries and filtering.
*
* @param sync If true, this query should be done synchronously and the
* resulting cursor returned. If false, it will be done asynchronously and
* null returned.
* @param filterstring If non-null, this is a filter to apply to the query.
*/
Cursor doQuery(boolean sync, String filterstring) {
// Cancel any pending queries
mQueryHandler.cancelOperation(MY_QUERY_TOKEN);
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filterstring != null) {
String [] searchWords = filterstring.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
where.append(MediaStore.Audio.Media.ALBUM_KEY + "||");
where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?");
}
}
// We want to show all audio files, even recordings. Enforcing the
// following condition would hide recordings.
//where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1");
if (sync) {
try {
return getContentResolver().query(mBaseUri, CURSOR_COLS,
where.toString(), keywords, mSortOrder);
} catch (UnsupportedOperationException ex) {
}
} else {
mAdapter.setLoading(true);
setProgressBarIndeterminateVisibility(true);
mQueryHandler.startQuery(MY_QUERY_TOKEN, null, mBaseUri, CURSOR_COLS,
where.toString(), keywords, mSortOrder);
}
return null;
}
@Override protected void onListItemClick(ListView l, View v, int position,
long id) {
mCursor.moveToPosition(position);
if (DBG) Log.v(TAG, "Click on " + position + " (id=" + id
+ ", cursid="
+ mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID))
+ ") in cursor " + mCursor
+ " adapter=" + l.getAdapter());
setSelected(mCursor);
}
void setSelected(Cursor c) {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID));
mSelectedUri = ContentUris.withAppendedId(uri, newId);
mSelectedId = newId;
if (newId != mPlayingId || mMediaPlayer == null) {
stopMediaPlayer();
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(this, mSelectedUri);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.prepare();
mMediaPlayer.start();
mPlayingId = newId;
getListView().invalidateViews();
} catch (IOException e) {
Log.w("MusicPicker", "Unable to play track", e);
}
} else if (mMediaPlayer != null) {
stopMediaPlayer();
getListView().invalidateViews();
}
}
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayer == mp) {
mp.stop();
mp.release();
mMediaPlayer = null;
mPlayingId = -1;
getListView().invalidateViews();
}
}
void stopMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mPlayingId = -1;
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.okayButton:
if (mSelectedId >= 0) {
setResult(RESULT_OK, new Intent().setData(mSelectedUri));
finish();
}
break;
case R.id.cancelButton:
finish();
break;
}
}
}
|
zzhangumd-apps-for-android
|
RingsExtended/src/com/example/android/rings_extended/MusicPicker.java
|
Java
|
asf20
| 28,234
|
package com.example.android.rings_extended;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* A special variation of RelativeLayout that can be used as a checkable object.
* This allows it to be used as the top-level view of a list view item, which
* also supports checking. Otherwise, it works identically to a RelativeLayout.
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked
};
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
public void toggle() {
setChecked(!mChecked);
}
public boolean isChecked() {
return mChecked;
}
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
}
|
zzhangumd-apps-for-android
|
RingsExtended/src/com/example/android/rings_extended/CheckableRelativeLayout.java
|
Java
|
asf20
| 1,352
|
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.globaltime;
public class LatLongSphere extends Sphere {
public LatLongSphere(float centerX, float centerY, float centerZ,
float radius, int lats, int longs,
float minLongitude, float maxLongitude,
boolean emitTextureCoordinates,
boolean emitNormals,
boolean emitColors,
boolean flatten) {
super(emitTextureCoordinates, emitNormals, emitColors);
int tris = 2 * (lats - 1) * (longs - 1);
int[] vertices = new int[3 * lats * longs];
int[] texcoords = new int[2 * lats * longs];
int[] colors = new int[4 * lats * longs];
int[] normals = new int[3 * lats * longs];
short[] indices = new short[3 * tris];
int vidx = 0;
int tidx = 0;
int nidx = 0;
int cidx = 0;
int iidx = 0;
minLongitude *= DEGREES_TO_RADIANS;
maxLongitude *= DEGREES_TO_RADIANS;
for (int i = 0; i < longs; i++) {
float fi = (float) i / (longs - 1);
// theta is the longitude
float theta =
(maxLongitude - minLongitude) * (1.0f - fi) + minLongitude;
float sinTheta = (float) Math.sin(theta);
float cosTheta = (float) Math.cos(theta);
for (int j = 0; j < lats; j++) {
float fj = (float) j / (lats - 1);
// phi is the latitude
float phi = PI * fj;
float sinPhi = (float) Math.sin(phi);
float cosPhi = (float) Math.cos(phi);
float x = cosTheta * sinPhi;
float y = cosPhi;
float z = sinTheta * sinPhi;
if (flatten) {
// Place vertices onto a flat projection
vertices[vidx++] = toFixed(2.0f * fi - 1.0f);
vertices[vidx++] = toFixed(0.5f - fj);
vertices[vidx++] = toFixed(0.0f);
} else {
// Place vertices onto the surface of a sphere
// with the given center and radius
vertices[vidx++] = toFixed(x * radius + centerX);
vertices[vidx++] = toFixed(y * radius + centerY);
vertices[vidx++] = toFixed(z * radius + centerZ);
}
if (emitTextureCoordinates) {
texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI)));
texcoords[tidx++] = toFixed(fj);
}
if (emitNormals) {
float norm = 1.0f / Shape.length(x, y, z);
normals[nidx++] = toFixed(x * norm);
normals[nidx++] = toFixed(y * norm);
normals[nidx++] = toFixed(z * norm);
}
// 0 == black, 65536 == white
if (emitColors) {
colors[cidx++] = (i % 2) * 65536;
colors[cidx++] = 0;
colors[cidx++] = (j % 2) * 65536;
colors[cidx++] = 65536;
}
}
}
for (int i = 0; i < longs - 1; i++) {
for (int j = 0; j < lats - 1; j++) {
int base = i * lats + j;
// Ensure both triangles have the same final vertex
// since this vertex carries the color for flat
// shading
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + 1);
indices[iidx++] = (short) (base + lats + 1);
indices[iidx++] = (short) (base + lats);
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + lats + 1);
}
}
allocateBuffers(vertices, texcoords, normals, colors, indices);
}
}
|
zzhangumd-apps-for-android
|
AndroidGlobalTime/src/com/android/globaltime/LatLongSphere.java
|
Java
|
asf20
| 4,464
|
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.globaltime;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
/**
* A class representing a city, with an associated position, time zone name,
* and raw offset from UTC.
*/
public class City implements Comparable<City> {
private static Map<String,City> cities = new HashMap<String,City>();
private static City[] citiesByRawOffset;
private String name;
private String timeZoneID;
private TimeZone timeZone = null;
private int rawOffset;
private float latitude, longitude;
private float x, y, z;
/**
* Loads the city database. The cities must be stored in order by raw
* offset from UTC.
*/
public static void loadCities(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
int numCities = dis.readInt();
citiesByRawOffset = new City[numCities];
byte[] buf = new byte[24];
for (int i = 0; i < numCities; i++) {
String name = dis.readUTF();
String tzid = dis.readUTF();
dis.read(buf);
// The code below is a faster version of:
// int rawOffset = dis.readInt();
// float latitude = dis.readFloat();
// float longitude = dis.readFloat();
// float cx = dis.readFloat();
// float cy = dis.readFloat();
// float cz = dis.readFloat();
int rawOffset =
(buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) |
((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff);
int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) |
((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff);
int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) |
((buf[10] & 0xff) << 8) | (buf[11] & 0xff);
int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) |
((buf[14] & 0xff) << 8) | (buf[15] & 0xff);
int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) |
((buf[18] & 0xff) << 8) | (buf[19] & 0xff);
int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) |
((buf[22] & 0xff) << 8) | (buf[23] & 0xff);
float latitude = Float.intBitsToFloat(ilat);
float longitude = Float.intBitsToFloat(ilon);
float cx = Float.intBitsToFloat(icx);
float cy = Float.intBitsToFloat(icy);
float cz = Float.intBitsToFloat(icz);
City city = new City(name, tzid, rawOffset,
latitude, longitude, cx, cy, cz);
cities.put(name, city);
citiesByRawOffset[i] = city;
}
}
/**
* Returns the cities, ordered by name.
*/
public static City[] getCitiesByName() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities);
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This requires reading the entire time zone database
* behind the scenes.
*/
public static City[] getCitiesByOffset() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities, new Comparator<City>() {
public int compare(City c1, City c2) {
long now = System.currentTimeMillis();
TimeZone tz1 = c1.getTimeZone();
TimeZone tz2 = c2.getTimeZone();
int off1 = tz1.getOffset(now);
int off2 = tz2.getOffset(now);
if (off1 == off2) {
float dlat = c2.getLatitude() - c1.getLatitude();
if (dlat < 0.0f) return -1;
if (dlat > 0.0f) return 1;
return 0;
}
return off1 - off2;
}
});
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This does not require reading the time zone database
* since the cities are pre-sorted.
*/
public static City[] getCitiesByRawOffset() {
return citiesByRawOffset;
}
/**
* Returns an Iterator over all cities, in raw offset order.
*/
public static Iterator<City> iterator() {
return cities.values().iterator();
}
/**
* Returns the total number of cities.
*/
public static int numCities() {
return cities.size();
}
/**
* Constructs a city with the given name, time zone name, raw offset,
* latitude, longitude, and 3D (X, Y, Z) coordinate.
*/
public City(String name, String timeZoneID,
int rawOffset,
float latitude, float longitude,
float x, float y, float z) {
this.name = name;
this.timeZoneID = timeZoneID;
this.rawOffset = rawOffset;
this.latitude = latitude;
this.longitude = longitude;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() {
return name;
}
public TimeZone getTimeZone() {
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone;
}
public float getLongitude() {
return longitude;
}
public float getLatitude() {
return latitude;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRawOffset() {
return rawOffset / 3600000.0f;
}
public int getRawOffsetMillis() {
return rawOffset;
}
/**
* Returns this city's offset from UTC, taking summer/daylight savigns
* time into account.
*/
public float getOffset() {
long now = System.currentTimeMillis();
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone.getOffset(now) / 3600000.0f;
}
/**
* Compares this city to another by name.
*/
public int compareTo(City o) {
return name.compareTo(o.name);
}
}
|
zzhangumd-apps-for-android
|
AndroidGlobalTime/src/com/android/globaltime/City.java
|
Java
|
asf20
| 7,219
|