修改z-stack协议栈基础代码

This commit is contained in:
LitterDryFish
2019-08-19 18:48:35 +08:00
parent 5068d7e8ee
commit 2bdfd643b1
1405 changed files with 2078155 additions and 0 deletions

View File

@@ -0,0 +1,308 @@
/**************************************************************************************************
Filename: hal_assert.c
Revised: $Date: 2010-11-22 08:13:43 -0800 (Mon, 22 Nov 2010) $
Revision: $Revision: 24480 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_assert.h"
#include "hal_types.h"
#include "hal_board.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#if (defined HAL_MCU_AVR) || (defined HAL_MCU_CC2430) || (defined HAL_MCU_CC2530) || \
(defined HAL_MCU_CC2533) || (defined HAL_MCU_MSP430)
/* for access to debug data */
#include "mac_rx.h"
#include "mac_tx.h"
#endif
/* ------------------------------------------------------------------------------------------------
* Local Prototypes
* ------------------------------------------------------------------------------------------------
*/
void halAssertHazardLights(void);
/**************************************************************************************************
* @fn halAssertHandler
*
* @brief Logic to handle an assert.
*
* @param none
*
* @return none
**************************************************************************************************
*/
void halAssertHandler(void)
{
/* execute code that handles asserts */
#ifdef ASSERT_RESET
HAL_SYSTEM_RESET();
#elif !defined ASSERT_WHILE
halAssertHazardLights();
#else
while(1);
#endif
}
#if !defined ASSERT_WHILE
/**************************************************************************************************
* @fn halAssertHazardLights
*
* @brief Blink LEDs to indicate an error.
*
* @param none
*
* @return none
**************************************************************************************************
*/
void halAssertHazardLights(void)
{
enum
{
DEBUG_DATA_RSTACK_HIGH_OFS,
DEBUG_DATA_RSTACK_LOW_OFS,
DEBUG_DATA_TX_ACTIVE_OFS,
DEBUG_DATA_RX_ACTIVE_OFS,
#if (defined HAL_MCU_AVR) || (defined HAL_MCU_CC2430)
DEBUG_DATA_INT_MASK_OFS,
#elif (defined HAL_MCU_CC2530) || (defined HAL_MCU_CC2533)
DEBUG_DATA_INT_MASK0_OFS,
DEBUG_DATA_INT_MASK1_OFS,
#endif
DEBUG_DATA_SIZE
};
uint8 buttonHeld;
uint8 debugData[DEBUG_DATA_SIZE];
/* disable all interrupts before anything else */
HAL_DISABLE_INTERRUPTS();
/*-------------------------------------------------------------------------------
* Initialize LEDs and turn them off.
*/
HAL_BOARD_INIT();
HAL_TURN_OFF_LED1();
HAL_TURN_OFF_LED2();
HAL_TURN_OFF_LED3();
HAL_TURN_OFF_LED4();
/*-------------------------------------------------------------------------------
* Master infinite loop.
*/
for (;;)
{
buttonHeld = 0;
/*-------------------------------------------------------------------------------
* "Hazard lights" loop. A held keypress will exit this loop.
*/
do
{
HAL_LED_BLINK_DELAY();
/* toggle LEDS, the #ifdefs are in case HAL has logically remapped non-existent LEDs */
#if (HAL_NUM_LEDS >= 1)
HAL_TOGGLE_LED1();
#if (HAL_NUM_LEDS >= 2)
HAL_TOGGLE_LED2();
#if (HAL_NUM_LEDS >= 3)
HAL_TOGGLE_LED3();
#if (HAL_NUM_LEDS >= 4)
HAL_TOGGLE_LED4();
#endif
#endif
#endif
#endif
/* escape hatch to continue execution, set escape to '1' to continue execution */
{
static uint8 escape = 0;
if (escape)
{
escape = 0;
return;
}
}
/* break out of loop if button is held long enough */
if (HAL_PUSH_BUTTON1())
{
buttonHeld++;
}
else
{
buttonHeld = 0;
}
}
while (buttonHeld != 10); /* loop until button is held specified number of loops */
/*-------------------------------------------------------------------------------
* Just exited from "hazard lights" loop.
*/
/* turn off all LEDs */
HAL_TURN_OFF_LED1();
HAL_TURN_OFF_LED2();
HAL_TURN_OFF_LED3();
HAL_TURN_OFF_LED4();
/* wait for button release */
HAL_DEBOUNCE(!HAL_PUSH_BUTTON1());
/*-------------------------------------------------------------------------------
* Load debug data into memory.
*/
#ifdef HAL_MCU_AVR
{
uint8 * pStack;
pStack = (uint8 *) SP;
pStack++; /* point to return address on stack */
debugData[DEBUG_DATA_RSTACK_HIGH_OFS] = *pStack;
pStack++;
debugData[DEBUG_DATA_RSTACK_LOW_OFS] = *pStack;
}
debugData[DEBUG_DATA_INT_MASK_OFS] = EIMSK;
#endif
#if (defined HAL_MCU_CC2430)
debugData[DEBUG_DATA_INT_MASK_OFS] = RFIM;
#elif (defined HAL_MCU_CC2530) || (defined HAL_MCU_CC2533)
debugData[DEBUG_DATA_INT_MASK0_OFS] = RFIRQM0;
debugData[DEBUG_DATA_INT_MASK1_OFS] = RFIRQM1;
#endif
#if (defined HAL_MCU_AVR) || (defined HAL_MCU_CC2430) || (defined HAL_MCU_CC2530) || \
(defined HAL_MCU_CC2533) || (defined HAL_MCU_MSP430)
debugData[DEBUG_DATA_TX_ACTIVE_OFS] = macTxActive;
debugData[DEBUG_DATA_RX_ACTIVE_OFS] = macRxActive;
#endif
/* initialize for data dump loop */
{
uint8 iBit;
uint8 iByte;
iBit = 0;
iByte = 0;
/*-------------------------------------------------------------------------------
* Data dump loop. A button press cycles data bits to an LED.
*/
while (iByte < DEBUG_DATA_SIZE)
{
/* wait for key press */
while(!HAL_PUSH_BUTTON1());
/* turn on all LEDs for first bit of byte, turn on three LEDs if not first bit */
HAL_TURN_ON_LED1();
HAL_TURN_ON_LED2();
HAL_TURN_ON_LED3();
if (iBit == 0)
{
HAL_TURN_ON_LED4();
}
else
{
HAL_TURN_OFF_LED4();
}
/* wait for debounced key release */
HAL_DEBOUNCE(!HAL_PUSH_BUTTON1());
/* turn off all LEDs */
HAL_TURN_OFF_LED1();
HAL_TURN_OFF_LED2();
HAL_TURN_OFF_LED3();
HAL_TURN_OFF_LED4();
/* output value of data bit to LED1 */
if (debugData[iByte] & (1 << (7 - iBit)))
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
/* advance to next bit */
iBit++;
if (iBit == 8)
{
iBit = 0;
iByte++;
}
}
}
/*
* About to enter "hazard lights" loop again. Turn off LED1 in case the last bit
* displayed happened to be one. This guarantees all LEDs are off at the start of
* the flashing loop which uses a toggle operation to change LED states.
*/
HAL_TURN_OFF_LED1();
}
}
#endif
/* ------------------------------------------------------------------------------------------------
* Compile Time Assertions
* ------------------------------------------------------------------------------------------------
*/
/* integrity check of type sizes */
HAL_ASSERT_SIZE( int8, 1);
HAL_ASSERT_SIZE( uint8, 1);
HAL_ASSERT_SIZE( int16, 2);
HAL_ASSERT_SIZE(uint16, 2);
HAL_ASSERT_SIZE( int32, 4);
HAL_ASSERT_SIZE(uint32, 4);
/**************************************************************************************************
*/

View File

@@ -0,0 +1,305 @@
/**************************************************************************************************
Filename: hal_drivers.c
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: This file contains the interface to the Drivers Service.
Copyright 2005-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_types.h"
#include "OSAL.h"
#include "hal_drivers.h"
#include "hal_adc.h"
#if (defined HAL_DMA) && (HAL_DMA == TRUE)
#include "hal_dma.h"
#endif
#include "hal_key.h"
#include "hal_lcd.h"
#include "hal_led.h"
#include "hal_io.h"
#include "hal_timer.h"
#include "hal_uart.h"
#include "hal_sleep.h"
#if (defined HAL_AES) && (HAL_AES == TRUE)
#include "hal_aes.h"
#endif
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
#include "hal_spi.h"
#endif
#if (defined HAL_HID) && (HAL_HID == TRUE)
#include "usb_hid.h"
#endif
#ifdef CC2591_COMPRESSION_WORKAROUND
#include "mac_rx.h"
#endif
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
uint8 Hal_TaskID;
extern void HalLedUpdate( void ); /* Notes: This for internal only so it shouldn't be in hal_led.h */
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/**************************************************************************************************
* @fn Hal_Init
*
* @brief Hal Initialization function.
*
* @param task_id - Hal TaskId
*
* @return None
**************************************************************************************************/
void Hal_Init( uint8 task_id )
{
/* Register task ID */
Hal_TaskID = task_id;
#ifdef CC2591_COMPRESSION_WORKAROUND
osal_start_reload_timer( Hal_TaskID, PERIOD_RSSI_RESET_EVT, PERIOD_RSSI_RESET_TIMEOUT );
#endif
}
/**************************************************************************************************
* @fn Hal_DriverInit
*
* @brief Initialize HW - These need to be initialized before anyone.
*
* @param task_id - Hal TaskId
*
* @return None
**************************************************************************************************/
void HalDriverInit (void)
{
/* TIMER */
#if (defined HAL_TIMER) && (HAL_TIMER == TRUE)
#error "The hal timer driver module is removed."
#endif
/* ADC */
#if (defined HAL_ADC) && (HAL_ADC == TRUE)
HalAdcInit();
#endif
/* DMA */
#if (defined HAL_DMA) && (HAL_DMA == TRUE)
// Must be called before the init call to any module that uses DMA.
HalDmaInit();
#endif
/* AES */
#if (defined HAL_AES) && (HAL_AES == TRUE)
HalAesInit();
#endif
/* LCD */
#if (defined HAL_LCD) && (HAL_LCD == TRUE)
HalLcdInit();
#endif
/* LED */
#if (defined HAL_LED) && (HAL_LED == TRUE)
HalLedInit();
#endif
/* UART */
#if (defined HAL_UART) && (HAL_UART == TRUE)
HalUARTInit();
#endif
/* KEY */
#if (defined HAL_KEY) && (HAL_KEY == TRUE)
HalKeyInit();
#endif
/* SPI */
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
HalSpiInit();
#endif
/* HID */
#if (defined HAL_HID) && (HAL_HID == TRUE)
usbHidInit();
#endif
}
/**************************************************************************************************
* @fn Hal_ProcessEvent
*
* @brief Hal Process Event
*
* @param task_id - Hal TaskId
* events - events
*
* @return None
**************************************************************************************************/
uint16 Hal_ProcessEvent( uint8 task_id, uint16 events )
{
uint8 *msgPtr;
(void)task_id; // Intentionally unreferenced parameter
if ( events & SYS_EVENT_MSG )
{
msgPtr = osal_msg_receive(Hal_TaskID);
while (msgPtr)
{
/* Do something here - for now, just deallocate the msg and move on */
/* De-allocate */
osal_msg_deallocate( msgPtr );
/* Next */
msgPtr = osal_msg_receive( Hal_TaskID );
}
return events ^ SYS_EVENT_MSG;
}
if ( events & HAL_LED_BLINK_EVENT )
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
HalLedUpdate();
#endif /* BLINK_LEDS && HAL_LED */
return events ^ HAL_LED_BLINK_EVENT;
}
if (events & HAL_KEY_EVENT)
{
#if (defined HAL_KEY) && (HAL_KEY == TRUE)
/* Check for keys */
HalKeyPoll();
/* if interrupt disabled, do next polling */
if (!Hal_KeyIntEnable)
{
osal_start_timerEx( Hal_TaskID, HAL_KEY_EVENT, 100);
}
#endif // HAL_KEY
return events ^ HAL_KEY_EVENT;
}
#ifdef POWER_SAVING
if ( events & HAL_SLEEP_TIMER_EVENT )
{
halRestoreSleepLevel();
return events ^ HAL_SLEEP_TIMER_EVENT;
}
#endif
#ifdef CC2591_COMPRESSION_WORKAROUND
if ( events & PERIOD_RSSI_RESET_EVT )
{
macRxResetRssi();
return (events ^ PERIOD_RSSI_RESET_EVT);
}
#endif
/* Nothing interested, discard the message */
return 0;
}
/**************************************************************************************************
* @fn Hal_ProcessPoll
*
* @brief This routine will be called by OSAL to poll UART, TIMER...
*
* @param task_id - Hal TaskId
*
* @return None
**************************************************************************************************/
void Hal_ProcessPoll ()
{
/* Timer Poll */
#if (defined HAL_TIMER) && (HAL_TIMER == TRUE)
#error "The hal timer driver module is removed."
#endif
/* UART Poll */
#if (defined HAL_UART) && (HAL_UART == TRUE)
HalUARTPoll();
#endif
HalIOPortPoll();
/* SPI Poll */
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
HalSpiPoll();
#endif
/* HID poll */
#if (defined HAL_HID) && (HAL_HID == TRUE)
usbHidProcessEvents();
#endif
#if defined( POWER_SAVING )
/* Allow sleep before the next OSAL event loop */
ALLOW_SLEEP_MODE();
#endif
}
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,51 @@
/***********************************************************
** FileName: IR.h
** Introductions: Sunplusapp CC2530 ZigBee Node IR Romoter Signal Send Functions
** Last Modify time: 2013.05.21
** Modify: 去掉了头文件中没用的宏定义,添加注释
** Author: GuoZhenjiang <zhenjiang.guo@sunplusapp.com>
***********************************************************/
#ifndef __IR_H__
#define __IR_H__
#include <hal_board.h>
// 红外发送引脚[P1.3]端口控制相关寄存器
#define PSEL_IR_SEND P1SEL
#define PDIR_IR_SEND P1DIR
#define POUT_IR_SEND P1
// 红外发送引脚位序号
#define BIT_IR_SEND 3
// 红外编码发送状态枚举
typedef enum
{
IRSta_Guide, // 引导码产生中
IRSta_T3PWM, // Timer3产生38kHz调制波
IRSta_Data0, // IR引脚输出低电平
IRSta_Stop, // 发送停止位
}IRSendSta_t;
enum
{
IRGuideLen_9ms = 1, // 红外引导码长度9.0ms
IRGuideLen_13ms = 2, // 红外引导码长度13.5ms
};
// 位序列操作宏定义
#define BIT_1(x) ( BV(x))
#define BIT_0(x) (~BV(x))
#define SET_IOB_BIT POUT_IR_SEND |= BIT_1(BIT_IR_SEND)
#define CLR_IOB_BIT POUT_IR_SEND &= BIT_0(BIT_IR_SEND)
#define IR_SEL_IOOUT PSEL_IR_SEND &= BIT_0(BIT_IR_SEND); PDIR_IR_SEND |= BIT_1(BIT_IR_SEND);
#define IR_SEL_T3PWM PSEL_IR_SEND |= BIT_1(BIT_IR_SEND)
#define STOP_T1_T3 T3CTL = 0x00; T1CTL = 0x00
// 红外编码发送初始化
void IRSendInit(void);
// 红外编码发送函数
int GenIR(uint8 *IRData , uint8 Mode , uint8 CodeLen );
#endif // __IR_H__

View File

@@ -0,0 +1,142 @@
/**************************************************************************************************
Filename: hal_adc.h
Revised: $Date: 2010-02-25 15:22:29 -0800 (Thu, 25 Feb 2010) $
Revision: $Revision: 21800 $
Description: This file contains the interface to the ADC Service.
Copyright 2005-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_ADC_H
#define HAL_ADC_H
#ifdef __cplusplus
extern "C"
{
#endif
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_board.h"
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/* Resolution */
#define HAL_ADC_RESOLUTION_8 0x01
#define HAL_ADC_RESOLUTION_10 0x02
#define HAL_ADC_RESOLUTION_12 0x03
#define HAL_ADC_RESOLUTION_14 0x04
/* Channels */
#define HAL_ADC_CHANNEL_0 0x00
#define HAL_ADC_CHANNEL_1 0x01
#define HAL_ADC_CHANNEL_2 0x02
#define HAL_ADC_CHANNEL_3 0x03
#define HAL_ADC_CHANNEL_4 0x04
#define HAL_ADC_CHANNEL_5 0x05
#define HAL_ADC_CHANNEL_6 0x06
#define HAL_ADC_CHANNEL_7 0x07
#define HAL_ADC_CHN_AIN0 0x00 /* AIN0 */
#define HAL_ADC_CHN_AIN1 0x01 /* AIN1 */
#define HAL_ADC_CHN_AIN2 0x02 /* AIN2 */
#define HAL_ADC_CHN_AIN3 0x03 /* AIN3 */
#define HAL_ADC_CHN_AIN4 0x04 /* AIN4 */
#define HAL_ADC_CHN_AIN5 0x05 /* AIN5 */
#define HAL_ADC_CHN_AIN6 0x06 /* AIN6 */
#define HAL_ADC_CHN_AIN7 0x07 /* AIN7 */
#define HAL_ADC_CHN_A0A1 0x08 /* AIN0,AIN1 */
#define HAL_ADC_CHN_A2A3 0x09 /* AIN2,AIN3 */
#define HAL_ADC_CHN_A4A5 0x0a /* AIN4,AIN5 */
#define HAL_ADC_CHN_A6A7 0x0b /* AIN6,AIN7 */
#define HAL_ADC_CHN_GND 0x0c /* GND */
#define HAL_ADC_CHN_VREF 0x0d /* Positive voltage reference */
#define HAL_ADC_CHN_TEMP 0x0e /* Temperature sensor */
#define HAL_ADC_CHN_VDD3 0x0f /* VDD/3 */
#define HAL_ADC_CHN_BITS 0x0f /* Bits [3:0] */
#define HAL_ADC_CHANNEL_TEMP HAL_ADC_CHN_TEMP
#define HAL_ADC_CHANNEL_VDD HAL_ADC_CHN_VDD3 /* channel VDD divided by 3 */
/* Vdd Limits */
#define HAL_ADC_VDD_LIMIT_0 0x00
#define HAL_ADC_VDD_LIMIT_1 0x01
#define HAL_ADC_VDD_LIMIT_2 0x02
#define HAL_ADC_VDD_LIMIT_3 0x03
#define HAL_ADC_VDD_LIMIT_4 0x04
#define HAL_ADC_VDD_LIMIT_5 0x05
#define HAL_ADC_VDD_LIMIT_6 0x06
#define HAL_ADC_VDD_LIMIT_7 0x07
/* Reference Voltages */
#define HAL_ADC_REF_125V 0x00 /* Internal Reference (1.25V-CC2430)(1.15V-CC2530) */
#define HAL_ADC_REF_AIN7 0x40 /* AIN7 Reference */
#define HAL_ADC_REF_AVDD 0x80 /* AVDD_SOC Pin Reference */
#define HAL_ADC_REF_DIFF 0xc0 /* AIN7,AIN6 Differential Reference */
#define HAL_ADC_REF_BITS 0xc0 /* Bits [7:6] */
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/*
* Initialize ADC Service with reference set to default value
*/
extern void HalAdcInit ( void );
/*
* Read value from a specified ADC Channel at the given resolution
*/
extern uint16 HalAdcRead ( uint8 channel, uint8 resolution );
/*
* Set the reference voltage for the ADC
*/
extern void HalAdcSetReference ( uint8 reference );
/*
* Check for minimum Vdd specified.
*/
extern bool HalAdcCheckVdd(uint8 vdd);
/**************************************************************************************************
**************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,110 @@
/**************************************************************************************************
Filename: hal_assert.h
Revised: $Date: 2009-02-16 18:03:22 -0800 (Mon, 16 Feb 2009) $
Revision: $Revision: 19172 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_ASSERT_H
#define HAL_ASSERT_H
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/*
* HAL_ASSERT( expression ) - The given expression must evaluate as "true" or else the assert
* handler is called. From here, the call stack feature of the debugger can pinpoint where
* the problem occurred.
*
* HAL_ASSERT_FORCED( ) - If asserts are in use, immediately calls the assert handler.
*
* HAL_ASSERT_STATEMENT( statement ) - Inserts the given C statement but only when asserts
* are in use. This macros allows debug code that is not part of an expression.
*
* HAL_ASSERT_DECLARATION( declaration ) - Inserts the given C declaration but only when asserts
* are in use. This macros allows debug code that is not part of an expression.
*
* Asserts can be disabled for optimum performance and minimum code size (ideal for
* finalized, debugged production code). To disable, define the preprocessor
* symbol HALNODEBUG at the project level.
*/
#ifdef HALNODEBUG
#define HAL_ASSERT(expr)
#define HAL_ASSERT_FORCED()
#define HAL_ASSERT_STATEMENT(statement)
#define HAL_ASSERT_DECLARATION(declaration)
#else
#define HAL_ASSERT(expr) st( if (!( expr )) halAssertHandler(); )
#define HAL_ASSERT_FORCED() halAssertHandler()
#define HAL_ASSERT_STATEMENT(statement) st( statement )
#define HAL_ASSERT_DECLARATION(declaration) declaration
#endif
/*
* This macro compares the size of the first parameter to the integer value
* of the second parameter. If they do not match, a compile time error for
* negative array size occurs (even gnu chokes on negative array size).
*
* This compare is done by creating a typedef for an array. No variables are
* created and no memory is consumed with this check. The created type is
* used for checking only and is not for use by any other code. The value
* of 10 in this macro is arbitrary, it just needs to be a value larger
* than one to result in a positive number for the array size.
*/
#define HAL_ASSERT_SIZE(x,y) typedef char x ## _assert_size_t[-1+10*(sizeof(x) == (y))]
/* ------------------------------------------------------------------------------------------------
* Prototypes
* ------------------------------------------------------------------------------------------------
*/
void halAssertHandler(void);
/**************************************************************************************************
*/
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
extern void halAssertHazardLights(void);
#endif

View File

@@ -0,0 +1 @@
#include "hal_board_cfg.h"

View File

@@ -0,0 +1,49 @@
/**************************************************************************************************
Filename: hal_ccm.h
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: Describe the purpose and contents of the file.
Copyright 2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_CCM_H_
#define HAL_CCM_H_
Status_t SSP_CCM_Auth (uint8, uint8 *, uint8 *, uint16, uint8 *, uint16, uint8 *, uint8 *);
Status_t SSP_CCM_Encrypt (uint8, uint8 *, uint8 *, uint16, uint8 *, uint8 *);
Status_t SSP_CCM_Decrypt (uint8, uint8 *, uint8 *, uint16, uint8 *, uint8 *);
Status_t SSP_CCM_InvAuth (uint8, uint8 *, uint8 *, uint16, uint8 *, uint16, uint8 *, uint8 *);
#endif // HAL_CCM_H_

View File

@@ -0,0 +1,128 @@
/**************************************************************************************************
Filename: hal_defs.h
Revised: $Date: 2008-10-07 14:47:15 -0700 (Tue, 07 Oct 2008) $
Revision: $Revision: 18212 $
Description: This file contains useful macros and data types
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_DEFS_H
#define HAL_DEFS_H
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
#ifndef BV
#define BV(n) (1 << (n))
#endif
#ifndef SETBIT
#define SETBIT(a,x) ((a) |= BV(x))
#endif
#ifndef CLRBIT
#define CLRBIT(a,x) ((a) &=~BV(x))
#endif
#ifndef BF
#define BF(x,b,s) (((x) & (b)) >> (s))
#endif
#ifndef MIN
#define MIN(n,m) (((n) < (m)) ? (n) : (m))
#endif
#ifndef MAX
#define MAX(n,m) (((n) < (m)) ? (m) : (n))
#endif
#ifndef ABS
#define ABS(n) (((n) < 0) ? -(n) : (n))
#endif
/* takes a byte out of a uint32 : var - uint32, ByteNum - byte to take out (0 - 3) */
#define BREAK_UINT32( var, ByteNum ) \
(uint8)((uint32)(((var) >>((ByteNum) * 8)) & 0x00FF))
#define BUILD_UINT32(Byte0, Byte1, Byte2, Byte3) \
((uint32)((uint32)((Byte0) & 0x00FF) \
+ ((uint32)((Byte1) & 0x00FF) << 8) \
+ ((uint32)((Byte2) & 0x00FF) << 16) \
+ ((uint32)((Byte3) & 0x00FF) << 24)))
#define BUILD_UINT16(loByte, hiByte) \
((uint16)(((loByte) & 0x00FF) + (((hiByte) & 0x00FF) << 8)))
#define HI_UINT16(a) (((a) >> 8) & 0xFF)
#define LO_UINT16(a) ((a) & 0xFF)
#define BUILD_UINT8(hiByte, loByte) \
((uint8)(((loByte) & 0x0F) + (((hiByte) & 0x0F) << 4)))
#define HI_UINT8(a) (((a) >> 4) & 0x0F)
#define LO_UINT8(a) ((a) & 0x0F)
/*
* This macro is for use by other macros to form a fully valid C statement.
* Without this, the if/else conditionals could show unexpected behavior.
*
* For example, use...
* #define SET_REGS() st( ioreg1 = 0; ioreg2 = 0; )
* instead of ...
* #define SET_REGS() { ioreg1 = 0; ioreg2 = 0; }
* or
* #define SET_REGS() ioreg1 = 0; ioreg2 = 0;
* The last macro would not behave as expected in the if/else construct.
* The second to last macro will cause a compiler error in certain uses
* of if/else construct
*
* It is not necessary, or recommended, to use this macro where there is
* already a valid C statement. For example, the following is redundant...
* #define CALL_FUNC() st( func(); )
* This should simply be...
* #define CALL_FUNC() func()
*
* (The while condition below evaluates false without generating a
* constant-controlling-loop type of warning on most compilers.)
*/
#define st(x) do { x } while (__LINE__ == -1)
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,110 @@
/**************************************************************************************************
Filename: hal_drivers.h
Revised: $Date: 2010-10-05 11:47:04 -0700 (Tue, 05 Oct 2010) $
Revision: $Revision: 23996 $
Description: This file contains the interface to the Drivers service.
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_DRIVER_H
#define HAL_DRIVER_H
#ifdef __cplusplus
extern "C"
{
#endif
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_KEY_EVENT 0x0001
#define HAL_LED_BLINK_EVENT 0x0002
#define HAL_SLEEP_TIMER_EVENT 0x0004
#define PERIOD_RSSI_RESET_EVT 0x0008
#define PERIOD_RSSI_RESET_TIMEOUT 10
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
extern uint8 Hal_TaskID;
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/**************************************************************************************************
* Serial Port Initialization
**************************************************************************************************/
extern void Hal_Init ( uint8 task_id );
/*
* Process Serial Buffer
*/
extern uint16 Hal_ProcessEvent ( uint8 task_id, uint16 events );
/*
* Process Polls
*/
extern void Hal_ProcessPoll (void);
/*
* Initialize HW
*/
extern void HalDriverInit (void);
/**************************************************************************************************
**************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,122 @@
/**************************************************************************************************
Filename: hal_flash.h
Revised: $Date:$
Revision: $Revision:$
Description: This file contains the interface to the Flash Service.
Copyright 2005-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_FLASH_H
#define HAL_FLASH_H
#ifdef __cplusplus
extern "C"
{
#endif
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board.h"
#include "hal_types.h"
/**************************************************************************************************
* @fn HalFlashRead
*
* @brief This function reads 'cnt' bytes from the internal flash.
*
* input parameters
*
* @param pg - Valid HAL flash page number (ie < 128).
* @param offset - Valid offset into the page (so < HAL_NV_PAGE_SIZE and byte-aligned is ok).
* @param buf - Valid buffer space at least as big as the 'cnt' parameter.
* @param cnt - Valid number of bytes to read: a read cannot cross into the next 32KB bank.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashRead(uint8 pg, uint16 offset, uint8 *buf, uint16 cnt);
/**************************************************************************************************
* @fn HalFlashWrite
*
* @brief This function reads 'cnt' bytes from the internal flash.
*
* input parameters
*
* @param addr - Valid HAL flash write address: actual addr / 4 and quad-aligned.
* @param buf - Valid buffer space at least as big as the 'cnt' parameter.
* @param cnt - Valid number of bytes to write: a write cannot cross into the next 32KB bank.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashWrite(uint16 addr, uint8 *buf, uint16 cnt);
/**************************************************************************************************
* @fn HalFlashErase
*
* @brief This function erases 'cnt' pages of the internal flash.
*
* input parameters
*
* @param pg - Valid HAL flash page number (ie < 128) to erase.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashErase(uint8 pg);
#ifdef __cplusplus
};
#endif
#endif
/**************************************************************************************************
*/

View File

@@ -0,0 +1,51 @@
#ifndef __HAL_IO_H__
#define __HAL_IO_H__
#include <ioCC2530.h>
#include "OSAL.h"
#define IOPORT_INT_EVENT 0xF0 //IO口中断事件
#define HAL_IOPORT(group, bit) (((group) << 3) | (bit))
#define MAX_IOGROUP 2
#define MAX_IOPORT HAL_IOPORT(MAX_IOGROUP, 4)
typedef struct
{
osal_event_hdr_t hdr; //事件类型及状态
uint8 endPoint;
void *arg;
} OSALIOIntData_t;
//端口作为输入时内部上下拉选择
typedef enum
{
Pull_None, //三态输入
Pull_Up, //上拉使能
Pull_Down, //下拉使能
}PullSet_t;
/***********************************************************
** CC2530每个通用IO引脚都可以产生中断
** 复位后所有中断关闭,根据需要打开即可
***********************************************************/
typedef enum //中断触发方式选择
{
IOInt_None, //关闭相应中断
IOInt_Rising, //上升沿触发
IOInt_Falling, //下降沿触发
}IntSel_t;
void HalIOInit(uint8 taskId);
//设置端口输入模式
void HalIOSetInput(uint8 group, uint8 bit, PullSet_t pull);
void HalIOSetOutput(uint8 group, uint8 bit);
uint8 HalIOGetLevel(uint8 group, uint8 bit);
void HalIOSetLevel(uint8 group, uint8 bit, uint8 value);
//设置端口中断触发方式
void HalIOIntSet(uint8 endPoint, uint8 group, uint8 bit, IntSel_t trigger, void *arg);
//轮询IO端口中断标志
void HalIOPortPoll(void);
#endif //__HAL_IO_H__

View File

@@ -0,0 +1,98 @@
/***********************************************************
** FileName: IRDecode.h
** Introductions: IR Remote decode for MCU of CC2530
** Last Modify time: 2013.05.20
** Modify: 修改定时器4辅助判断解码中的超时失效
** Author: GuoZhenjiang <zhenjiang.guo@sunplusapp.com>
***********************************************************/
/***********************解码原理****************************
* 1、定时器1的通道0(Alt.2 = P1.2)是红外信号接收输入引脚
* 2、采用定时器1通道0上升沿输入捕获模式获取红外信号
* 3、定时器1计数频率1MHz
* 4、每当上升沿捕获后获取当前计数值(周期),然后清零计数值并重新开始计数
* 5、获取的每一小周期按照时间阀值判断是引导码、数据0、数据1
* 5、解码过程中利用定时器4辅助判断是否超时
***********************************************************/
#ifndef __IRDECODE_H__
#define __IRDECODE_H__
#include "OSAL.h"
#define IRDEC_INT_EVENT 0xF1 //IO端口中断采用0xF0
typedef struct {
uint8 irLen;
uint8 irCode[15];
} OSALIRDecData_t;
typedef struct
{
osal_event_hdr_t hdr; //事件类型及状态
uint8 endPoint;
OSALIRDecData_t *data;
} OSALIRDecIntData_t;
#define CLR_T1CNT T1CNTL = 0 // 向T1CNTL寄存器中写任何值会导致T1CNT清零。
// T1CTL
// 定时器1时钟预分频
typedef enum
{
Tdiv_1 = 0X00, //标记频率/1
Tdiv_8 = 0X04, //标记频率/8
Tdiv_32 = 0X08, //标记频率/32
Tdiv_128 = 0X0C, //标记频率/128
}Timer1Div_t;
// 定时器1运行模式
typedef enum
{
Tmod_stop = 0X00, //暂停运行
Tmod_free = 0X01, //自由运行
Tmod_Mod = 0X02, //模模式
Tmod_PN = 0X03, //正/倒计数模式
}Timer1Mod_t;
// T1CCTLx(x = 0,1,2,3,4,5)
// 定时器1通道配置
typedef enum
{
TCCSet = 0X00, //比较匹配时置位
TCCClear = 0X08, //比较匹配时清零
TCCExch = 0X02, //模模式
TCCSet0Clr = 0X03, //正/倒计数模式
}Timer1CC_t;
// 红外遥控编码解调后周期 in us
// 4.500ms引导码判断阀值
#define T_IR_GUIDE4_MIN 8000 //4.5ms引导码 理论时间9.000ms
#define T_IR_GUIDE4_MAX 9500
// 9.000ms引导码判断阀值
#define T_IR_GUIDE9_MIN 12000 //9ms引导码 理论时间13.500ms
#define T_IR_GUIDE9_MAX 14000
// 数据位0判断阀值
#define T_IR_0_MIN 1000 //位0 理论时间1.125ms
#define T_IR_0_MAX 1500
// 数据位1判断阀值
#define T_IR_1_MIN 2000 //位1 理论时间2.250ms
#define T_IR_1_MAX 2300
// 用于判断一次红外信号结束的周期阀值
#define T_IR_ENDED 50 // 比位1的周期稍微长点,不在引导码范围内
typedef enum
{
WaitForGuideTrig1, // 等待引导码第一个上升沿
WaitForGuideTrig2, // 等待引导码第二个上升沿
Decoding, // 位0位1解码过程中
Decode_GuideOverTime, // 引导码结束等待超时
Decode_bitOverTime, // 位0 位1 结束等待超时
Decode_BufOverflow, // 接收队列溢出导致解码结束
Decode_OverUnknow, // 未知原因导致解码结束
}IRDecodeSta_t;
// 中断处理法红外遥控解码初始化
void IRDecodeT1Init(unsigned char taskid, unsigned char ep);
#endif //__IRDECODE_H__

View File

@@ -0,0 +1,141 @@
/**************************************************************************************************
Filename: hal_key.h
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: This file contains the interface to the KEY Service.
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_KEY_H
#define HAL_KEY_H
#ifdef __cplusplus
extern "C"
{
#endif
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_board.h"
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/* Interrupt option - Enable or disable */
#define HAL_KEY_INTERRUPT_DISABLE 0x00
#define HAL_KEY_INTERRUPT_ENABLE 0x01
/* Key state - shift or nornal */
#define HAL_KEY_STATE_NORMAL 0x00
#define HAL_KEY_STATE_SHIFT 0x01
/* Switches (keys) */
#define HAL_KEY_SW_1 0x01 // Joystick up
#define HAL_KEY_SW_2 0x02 // Joystick right
#define HAL_KEY_SW_5 0x04 // Joystick center
#define HAL_KEY_SW_4 0x08 // Joystick left
#define HAL_KEY_SW_3 0x10 // Joystick down
#define HAL_KEY_SW_6 0x20 // Button S1 if available
#define HAL_KEY_SW_7 0x40 // Button S2 if available
/* Joystick */
#define HAL_KEY_UP 0x01 // Joystick up
#define HAL_KEY_RIGHT 0x02 // Joystick right
#define HAL_KEY_CENTER 0x04 // Joystick center
#define HAL_KEY_LEFT 0x08 // Joystick left
#define HAL_KEY_DOWN 0x10 // Joystick down
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
typedef void (*halKeyCBack_t) (uint8 keys, uint8 state);
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
extern bool Hal_KeyIntEnable;
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/*
* Initialize the Key Service
*/
extern void HalKeyInit( void );
/*
* Configure the Key Service
*/
extern void HalKeyConfig( bool interruptEnable, const halKeyCBack_t cback);
/*
* Read the Key status
*/
extern uint8 HalKeyRead( void);
/*
* Enter sleep mode, store important values
*/
extern void HalKeyEnterSleep ( void );
/*
* Exit sleep mode, retore values
*/
extern uint8 HalKeyExitSleep ( void );
/*
* This is for internal used by hal_driver
*/
extern void HalKeyPoll ( void );
/*
* This is for internal used by hal_sleep
*/
extern bool HalKeyPressed( void );
/**************************************************************************************************
**************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,137 @@
/**************************************************************************************************
Filename: hal_lcd.h
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: This file contains the interface to the LCD Service.
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_LCD_H
#define HAL_LCD_H
#ifdef __cplusplus
extern "C"
{
#endif
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_board.h"
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/* These are used to specify which line the text will be printed */
#define HAL_LCD_LINE_1 0x01
#define HAL_LCD_LINE_2 0x02
/*
This to support LCD with extended number of lines (more than 2).
Don't use these if LCD doesn't support more than 2 lines
*/
#define HAL_LCD_LINE_3 0x03
#define HAL_LCD_LINE_4 0x04
#define HAL_LCD_LINE_5 0x05
#define HAL_LCD_LINE_6 0x06
#define HAL_LCD_LINE_7 0x07
#define HAL_LCD_LINE_8 0x08
/* Max number of chars on a single LCD line */
#define HAL_LCD_MAX_CHARS 16
#define HAL_LCD_MAX_BUFF 25
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/*
* Initialize LCD Service
*/
extern void HalLcdInit(void);
/*
* Write a string to the LCD
*/
extern void HalLcdWriteString ( char *str, uint8 option);
/*
* Write a value to the LCD
*/
extern void HalLcdWriteValue ( uint32 value, const uint8 radix, uint8 option);
/*
* Write a value to the LCD
*/
extern void HalLcdWriteScreen( char *line1, char *line2 );
/*
* Write a string followed by a value to the LCD
*/
extern void HalLcdWriteStringValue( char *title, uint16 value, uint8 format, uint8 line );
/*
* Write a string followed by 2 values to the LCD
*/
extern void HalLcdWriteStringValueValue( char *title, uint16 value1, uint8 format1, uint16 value2, uint8 format2, uint8 line );
/*
* Write a percentage bar to the LCD
*/
extern void HalLcdDisplayPercentBar( char *title, uint8 value );
/**************************************************************************************************
**************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,129 @@
/**************************************************************************************************
Filename: hal_led.h
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: This file contains the interface to the LED Service.
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_LED_H
#define HAL_LED_H
#ifdef __cplusplus
extern "C"
{
#endif
/*********************************************************************
* INCLUDES
*/
#include "hal_board.h"
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
/* LEDS - The LED number is the same as the bit position */
#define HAL_LED_1 0x01
#define HAL_LED_2 0x02
#if 0
#define HAL_LED_3 0x04
#define HAL_LED_4 0x08
#endif
#define HAL_LED_ALL (HAL_LED_1 | HAL_LED_2/* | HAL_LED_3 | HAL_LED_4*/)
/* Modes */
#define HAL_LED_MODE_OFF 0x00
#define HAL_LED_MODE_ON 0x01
#define HAL_LED_MODE_BLINK 0x02
#define HAL_LED_MODE_FLASH 0x04
#define HAL_LED_MODE_TOGGLE 0x08
/* Defaults */
#define HAL_LED_DEFAULT_MAX_LEDS 4
#define HAL_LED_DEFAULT_DUTY_CYCLE 5
#define HAL_LED_DEFAULT_FLASH_COUNT 50
#define HAL_LED_DEFAULT_FLASH_TIME 1000
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
/*
* Initialize LED Service.
*/
extern void HalLedInit( void );
/*
* Set the LED ON/OFF/TOGGLE.
*/
extern uint8 HalLedSet( uint8 led, uint8 mode );
/*
* Blink the LED.
*/
extern void HalLedBlink( uint8 leds, uint8 cnt, uint8 duty, uint16 time );
/*
* Put LEDs in sleep state - store current values
*/
extern void HalLedEnterSleep( void );
/*
* Retore LEDs from sleep state
*/
extern void HalLedExitSleep( void );
/*
* Return LED state
*/
extern uint8 HalLedGetState ( void );
/*********************************************************************
*********************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,79 @@
/**************************************************************************************************
Filename: hal_sleep.h
Revised: $Date: 2010-01-29 13:41:50 -0800 (Fri, 29 Jan 2010) $
Revision: $Revision: 21620 $
Description: This file contains the interface to the power management service.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_SLEEP_H
#define HAL_SLEEP_H
#ifdef __cplusplus
extern "C"
{
#endif
/*********************************************************************
* FUNCTIONS
*/
/*
* Execute power management procedure
*/
extern void halSleep( uint16 osal_timer );
/*
* Used in mac_mcu
*/
extern void halSleepWait(uint16 duration);
/*
* Used in hal_drivers, AN044 - DELAY EXTERNAL INTERRUPTS
*/
extern void halRestoreSleepLevel( void );
/*
* Used by the interrupt routines to exit from sleep.
*/
extern void halSleepExit(void);
/*********************************************************************
*********************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,190 @@
/**************************************************************************************************
Filename: hal_timer.h
Revised: $Date: 2007-07-06 10:42:24 -0700 (Fri, 06 Jul 2007) $
Revision: $Revision: 13579 $
Description: This file contains the interface to the Timer Service.
Copyright 2005-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_TIMER_H
#define HAL_TIMER_H
#ifdef __cplusplus
extern "C"
{
#endif
/***************************************************************************************************
* INCLUDES
***************************************************************************************************/
#include "hal_board.h"
/***************************************************************************************************
* MACROS
***************************************************************************************************/
/***************************************************************************************************
* CONSTANTS
***************************************************************************************************/
/* Timer ID definitions */
#define HAL_TIMER_0 0x00 // 8bit timer
#define HAL_TIMER_1 0x01 // 16bit Mac timer
#define HAL_TIMER_2 0x02 // 8bit timer
#define HAL_TIMER_3 0x03 // 16bit timer
#define HAL_TIMER_MAX 4 // Max number of timer
/* Operation Modes for timer */
#define HAL_TIMER_MODE_NORMAL 0x01 // Normal Mode
#define HAL_TIMER_MODE_CTC 0x02 // Clear Timer On Compare
#define HAL_TIMER_MODE_MASK (HAL_TIMER_MODE_NORMAL | HAL_TIMER_MODE_CTC)
/* Channel definitions */
#define HAL_TIMER_CHANNEL_SINGLE 0x01 // Single Channel - default
#define HAL_TIMER_CHANNEL_A 0x02 // Channel A
#define HAL_TIMER_CHANNEL_B 0x04 // Channel B
#define HAL_TIMER_CHANNEL_C 0x08 // Channel C
#define HAL_TIMER_CHANNEL_MASK (HAL_TIMER_CHANNEL_SINGLE | \
HAL_TIMER_CHANNEL_A | \
HAL_TIMER_CHANNEL_B | \
HAL_TIMER_CHANNEL_C)
/* Channel mode definitions */
#define HAL_TIMER_CH_MODE_INPUT_CAPTURE 0x01 // Channel Mode Input-Capture
#define HAL_TIMER_CH_MODE_OUTPUT_COMPARE 0x02 // Channel Mode Output_Compare
#define HAL_TIMER_CH_MODE_OVERFLOW 0x04 // Channel Mode Overflow
#define HAL_TIMER_CH_MODE_MASK (HAL_TIMER_CH_MODE_INPUT_CAPTURE | \
HAL_TIMER_CH_MODE_OUTPUT_COMPARE | \
HAL_TIMER_CH_MODE_OVERFLOW)
/* Error Code */
#define HAL_TIMER_OK 0x00
#define HAL_TIMER_NOT_OK 0x01
#define HAL_TIMER_PARAMS_ERROR 0x02
#define HAL_TIMER_NOT_CONFIGURED 0x03
#define HAL_TIMER_INVALID_ID 0x04
#define HAL_TIMER_INVALID_CH_MODE 0x05
#define HAL_TIMER_INVALID_OP_MODE 0x06
/* Timer clock pre-scaler definitions for 16bit timer1 and timer3 */
#define HAL_TIMER3_16_TC_STOP 0x00 // No clock, timer stopped
#define HAL_TIMER3_16_TC_DIV1 0x01 // No clock pre-scaling
#define HAL_TIMER3_16_TC_DIV8 0x02 // Clock pre-scaled by 8
#define HAL_TIMER3_16_TC_DIV64 0x03 // Clock pre-scaled by 64
#define HAL_TIMER3_16_TC_DIV256 0x04 // Clock pre-scaled by 256
#define HAL_TIMER3_16_TC_DIV1024 0x05 // Clock pre-scaled by 1024
#define HAL_TIMER3_16_TC_EXTFE 0x06 // External clock (T2), falling edge
#define HAL_TIMER3_16_TC_EXTRE 0x07 // External clock (T2), rising edge
/* Timer clock pre-scaler definitions for 8bit timer0 and timer2 */
#define HAL_TIMER0_8_TC_STOP 0x00 // No clock, timer stopped
#define HAL_TIMER0_8_TC_DIV1 0x01 // No clock pre-scaling
#define HAL_TIMER0_8_TC_DIV8 0x02 // Clock pre-scaled by 8
#define HAL_TIMER0_8_TC_DIV32 0x03 // Clock pre-scaled by 32
#define HAL_TIMER0_8_TC_DIV64 0x04 // Clock pre-scaled by 64
#define HAL_TIMER0_8_TC_DIV128 0x05 // Clock pre-scaled by 128
#define HAL_TIMER0_8_TC_DIV256 0x06 // Clock pre-scaled by 256
#define HAL_TIMER0_8_TC_DIV1024 0x07 // Clock pre-scaled by 1024
/* Timer clock pre-scaler definitions for 8bit timer2 */
#define HAL_TIMER2_8_TC_STOP 0x00 // No clock, timer stopped
#define HAL_TIMER2_8_TC_DIV1 0x01 // No clock pre-scaling
#define HAL_TIMER2_8_TC_DIV8 0x02 // Clock pre-scaled by 8
#define HAL_TIMER2_8_TC_DIV64 0x03 // Clock pre-scaled by 32
#define HAL_TIMER2_8_TC_DIV256 0x04 // Clock pre-scaled by 64
#define HAL_TIMER2_8_TC_DIV1024 0x05 // Clock pre-scaled by 128
#define HAL_TIMER2_8_TC_EXTFE 0x06 // External clock (T2), falling edge
#define HAL_TIMER2_8_TC_EXTRE 0x07 // External clock (T2), rising edge
/***************************************************************************************************
* TYPEDEFS
***************************************************************************************************/
typedef void (*halTimerCBack_t) (uint8 timerId, uint8 channel, uint8 channelMode);
/***************************************************************************************************
* GLOBAL VARIABLES
***************************************************************************************************/
/***************************************************************************************************
* FUNCTIONS - API
***************************************************************************************************/
/*
* Initialize Timer Service
*/
extern void HalTimerInit ( void );
/*
* Configure channel in different modes
*/
extern uint8 HalTimerConfig ( uint8 timerId,
uint8 opMode,
uint8 channel,
uint8 channelMode,
bool intEnable,
halTimerCBack_t cback );
/*
* Start a Timer
*/
extern uint8 HalTimerStart ( uint8 timerId, uint32 timePerTick );
/*
* Stop a Timer
*/
extern uint8 HalTimerStop ( uint8 timerId );
/*
* This is used for polling, provide the tick increment
*/
extern void HalTimerTick ( void );
/*
* Enable and disable particular timer
*/
extern uint8 HalTimerInterruptEnable (uint8 timerId, uint8 channelMode, bool enable);
/***************************************************************************************************
***************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,263 @@
/**************************************************************************************************
Filename: hal_uart.h
Revised: $Date: 2009-03-09 05:27:36 -0700 (Mon, 09 Mar 2009) $
Revision: $Revision: 19340 $
Description: This file contains the interface to the UART Service.
Copyright 2005-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_UART_H
#define HAL_UART_H
#ifdef __cplusplus
extern "C"
{
#endif
/***************************************************************************************************
* INCLUDES
***************************************************************************************************/
#include "hal_board.h"
/***************************************************************************************************
* MACROS
***************************************************************************************************/
/***************************************************************************************************
* CONSTANTS
***************************************************************************************************/
/* UART Ports */
/*
Serial Port Baudrate Settings
Have to match with baudrate table
Note that when using interrupt service based UART configuration (as opposed to DMA)
higher baudrate such as 115200bps may have problem when radio is operational at the same time.
*/
#define HAL_UART_BR_9600 0x00
#define HAL_UART_BR_19200 0x01
#define HAL_UART_BR_38400 0x02
#define HAL_UART_BR_57600 0x03
#define HAL_UART_BR_115200 0x04
/* Frame Format constant */
/* Stop Bits */
#define HAL_UART_ONE_STOP_BIT 0x00
#define HAL_UART_TWO_STOP_BITS 0x01
/* Parity settings */
#define HAL_UART_NO_PARITY 0x00
#define HAL_UART_EVEN_PARITY 0x01
#define HAL_UART_ODD_PARITY 0x02
/* Character Size */
#define HAL_UART_8_BITS_PER_CHAR 0x00
#define HAL_UART_9_BITS_PER_CHAR 0x01
/* Flow control */
#define HAL_UART_FLOW_OFF 0x00
#define HAL_UART_FLOW_ON 0x01
/* Ports */
#define HAL_UART_PORT_0 0x00
#define HAL_UART_PORT_1 0x01
#define HAL_UART_PORT_MAX 0x02
/* UART Status */
#define HAL_UART_SUCCESS 0x00
#define HAL_UART_UNCONFIGURED 0x01
#define HAL_UART_NOT_SUPPORTED 0x02
#define HAL_UART_MEM_FAIL 0x03
#define HAL_UART_BAUDRATE_ERROR 0x04
/* UART Events */
#define HAL_UART_RX_FULL 0x01
#define HAL_UART_RX_ABOUT_FULL 0x02
#define HAL_UART_RX_TIMEOUT 0x04
#define HAL_UART_TX_FULL 0x08
#define HAL_UART_TX_EMPTY 0x10
/***************************************************************************************************
* TYPEDEFS
***************************************************************************************************/
typedef void (*halUARTCBack_t) (uint8 port, uint8 event);
typedef struct
{
// The head or tail is updated by the Tx or Rx ISR respectively, when not polled.
volatile uint16 bufferHead;
volatile uint16 bufferTail;
uint16 maxBufSize;
uint8 *pBuffer;
} halUARTBufControl_t;
typedef struct
{
bool configured;
uint8 baudRate;
bool flowControl;
uint16 flowControlThreshold;
uint8 idleTimeout;
halUARTBufControl_t rx;
halUARTBufControl_t tx;
bool intEnable;
uint32 rxChRvdTime;
halUARTCBack_t callBackFunc;
}halUARTCfg_t;
typedef union
{
bool paramCTS;
bool paramRTS;
bool paramDSR;
bool paramDTR;
bool paramCD;
bool paramRI;
uint16 baudRate;
bool flowControl;
bool flushControl;
}halUARTIoctl_t;
/***************************************************************************************************
* GLOBAL VARIABLES
***************************************************************************************************/
/***************************************************************************************************
* FUNCTIONS - API
***************************************************************************************************/
/*
* Initialize UART at the startup
*/
extern void HalUARTInit ( void );
/*
* Open a port based on the configuration
*/
extern uint8 HalUARTOpen ( uint8 port, halUARTCfg_t *config );
/*
* Close a port
*/
extern void HalUARTClose ( uint8 port );
/*
* Read a buffer from the UART
*/
extern uint16 HalUARTRead ( uint8 port, uint8 *pBuffer, uint16 length );
/*
* Write a buff to the uart *
*/
extern uint16 HalUARTWrite ( uint8 port, uint8 *pBuffer, uint16 length );
/*
* Write a buffer to the UART
*/
extern uint8 HalUARTIoctl ( uint8 port, uint8 cmd, halUARTIoctl_t *pIoctl );
/*
* This to support polling
*/
extern void HalUARTPoll( void );
/*
* Return the number of bytes in the Rx buffer
*/
extern uint16 Hal_UART_RxBufLen ( uint8 port );
/*
* Return the number of bytes in the Tx buffer
*/
extern uint16 Hal_UART_TxBufLen ( uint8 port );
/*
* This enable/disable flow control
*/
extern void Hal_UART_FlowControlSet ( uint8 port, bool status );
/*
* Initialize hardware for UART
*/
extern uint8 HalUART_HW_Init(uint8 port);
/*
* Abort UART when entering sleep mode
*/
extern void HalUARTSuspend(void);
/*
* Resume UART after wakeup from sleep
*/
extern void HalUARTResume(void);
/*
* Lowlevel init function for UART1
*/
void HalUART1HwInit(void);
/*
* Lowlevel send byte function for UART1
*/
void HalUART1HwTxByte(uint8 v);
/*
* Lowlevel send data function for UART1
*/
void HalUART1HwTx(uint8 *Data, int len);
/*
* Lowlevel receive byte function for UART1
*/
uint8 HalUART1HwRxByte(void);
/*
* Lowlevel receive data function for UART1
*/
uint8 *HalUART1HwRx(uint8 *data, int maxLen);
/***************************************************************************************************
***************************************************************************************************/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,91 @@
#ifndef __SHT10_h__
#define __SHT10_h__
// write your header here
#ifndef _IOCC2530_
#define _IOCC2530_
#include "ioCC2530.h"
#endif
#define IO_IN 0
#define IO_OUT 1
#define IO_DIR_PORT_PIN(port, pin, dir) \
do { \
if (dir == IO_OUT) \
P##port##DIR |= (0x01<<(pin)); \
else \
P##port##DIR &= ~(0x01<<(pin)); \
}while(0)
#define IO_Port 0
#define I2C_D P0_6
#define I2C_C P0_0
#define I2C_D_NU 6
#define I2C_C_NU 0
//#define IO_Port2 (IO_Port)
#define CFG_WRITE(x) do{IO_DIR_PORT_PIN(0,x,IO_OUT);}while(0)
#define CFG_READ(x) do{IO_DIR_PORT_PIN(0,x,IO_IN);}while(0)
#define MAKE_HIGH(x) do{x = 1;}while(0)
#define MAKE_LOW(x) do{x = 0;}while(0)
#define BIT_READ(x) x
#define DURATION1 1000
/*****************************************
******************************************/
#define SCLK_DIR_OUT CFG_WRITE(I2C_C_NU)
#define SDIO_DIR_IN CFG_READ(I2C_D_NU)
#define SDIO_DIR_OUT CFG_WRITE(I2C_D_NU)
#define SCLK_HIGH MAKE_HIGH(I2C_C)
#define SCLK_LOW MAKE_LOW(I2C_C)
#define SDIO_HIGH MAKE_HIGH(I2C_D)
#define SDIO_LOW MAKE_LOW(I2C_D)
#define READ_SDIO BIT_READ(I2C_D)
/**************************************
***************************************/
#define DELAY(DURATION) { unsigned int i = DURATION; while(i--);}
//SH10 Command
#define CMD_RESERVED 0x00 //保留
#define CMD_TEM_MES 0x03 //温度测量命令
#define CMD_HUMI_MES 0x05 //湿度测量命令
#define CMD_Read_STATUS_REG 0x07 //读状态寄存器
#define CMD_Write_STATUS_REG 0x06 //写状态寄存器
#define CMD_Soft_Reset 0x1E //软复位
#define bitselect 0x01 //选择温度与湿度的低位读
#define noACK 0
#define ACK 1
#define HUMIDITY 2
#define TEMPERATURE 1
void SHT10_Transstart(void);
unsigned char SHT10_WriteByte(unsigned char data);
unsigned char SHT10_ReadByte(unsigned char ack);
void SHT10_Connectionreset(void);
unsigned char SHT10_Softreset(void);
unsigned char SHT10_WriteStatusReg(unsigned char RegVlaue);
unsigned char SHT10_ReadStatusReg(void);
unsigned char SHT10_Measure(unsigned int *p_value, unsigned char *p_checksum, unsigned char mode);
float SHT10_Calculate(unsigned int data,unsigned char mode);
void SHT10_init(unsigned int Initial_Reg);
#endif

View File

@@ -0,0 +1,22 @@
#ifndef _UART_RXH
#define _UART_RXH
#include <ioCC2530.h>
#include <string.h>
#define uint unsigned int
#define uchar unsigned char
#define RXMAXLENGTH 20
#define FALSE 0
#define TURE 1
//定义控制灯的端口
#define led2 P1_1
//函数声明
void Delay(uint);
void initUARTrx(void);
uchar ReceiveData(void);
void ReceiverAction(void);
void Init_LED_IO(void);
#endif

View File

@@ -0,0 +1,222 @@
/***********************************************************
** FileName: IR.c
** Introductions: Sunplusapp CC2530 ZigBee Node IR Romoter Signal Send Functions
** Last Modify time: 2013.05.21
** Modify: 修改红外编码发送,优化时序,添加注释
** Author: GuoZhenjiang <zhenjiang.guo@sunplusapp.com>
***********************************************************/
#include "IR.h"
#include "OSAL.h"
#if defined(HAL_IRENC) && (HAL_IRENC == TRUE)
// 定时器1中自增量,控制每一位编码的周期
volatile uint16 T1_80usCnt = 0;
// Timer1红外编码初始化
void IRSend_T1_Init(void);
// Timer3红外编码初始化
void IRSend_T3_Init(void);
// Timer1 & Timer3 中断处理函数声明
__near_func __interrupt void IRSend_T1IntHandle(void);
__near_func __interrupt void IRSend_T3IntHandle(void);
/***********************************************************
** 函数名称: GenIR
** 实现功能: 系统时钟设置
** 入口参数: IRData: 红外编码数据首地址
** Mode: 引导码分类:1 周期9ms 2:周期13.56ms
** CodeLen: 编码位数(bit,不是Byte)
** 返回结果: 0:发送失败 1:发送成功
***********************************************************/
int GenIR(uint8 *IRData , uint8 Mode , uint8 CodeLen )
{
uint16 GuideCodeLen=0;
static IRSendSta_t IRSendSta = IRSta_Guide;
static uint8 cntByte=0, cntbit=0, bitNum;
bitNum = CodeLen; //保存位数
if(Mode == 1)
GuideCodeLen = 56;//226; 引导码长度4.5ms、4.5ms
else if(Mode == 2)
GuideCodeLen = 114; //引导码长度9ms、4.5ms
IRSend_T1_Init();
IRSend_T3_Init();
IR_SEL_IOOUT;
CLR_IOB_BIT;
IRSendSta = IRSta_Guide;
T1_80usCnt = 0;
IR_SEL_T3PWM;
while(1)
{
// 查询红外编码发送状态
switch(IRSendSta)
{
// 引导码阶段
case IRSta_Guide:
// 引导码4.5ms或9ms载波阶段
if(T1_80usCnt <= GuideCodeLen)
{
IRSendSta = IRSta_Guide;
IR_SEL_T3PWM;
}
// 引导码4.5ms低电平阶段
else if((T1_80usCnt > GuideCodeLen) && (T1_80usCnt <= GuideCodeLen+56))
{
IRSendSta = IRSta_Guide;
IR_SEL_IOOUT;
CLR_IOB_BIT;
}
// 引导码发送完毕,准备发送数据位
else
{
IRSendSta = IRSta_T3PWM;
IR_SEL_T3PWM;
T1_80usCnt = 0;
}
break;
// 数据位中的位0、位1的0.56ms的38kHz载波阶段
case IRSta_T3PWM:
if(T1_80usCnt >= 7) // 7 * 80us = 560us
{
IR_SEL_IOOUT;
CLR_IOB_BIT;
IRSendSta = IRSta_Data0;
}
break;
// 数据位中的位0、位1的低电平持续阶段
case IRSta_Data0:
//发送数据0,低电平持续 0.565ms。
if(!(IRData[cntByte] & (0x80 >> (cntbit % 8))))
{
if(T1_80usCnt >= 14)
{
IR_SEL_T3PWM;
T1_80usCnt = 0;
cntbit++;
if(0 == (cntbit % 8))
cntByte++;
}
}
//发送数据1,低电平持续 1.685ms。
else if(IRData[cntByte] & (0x80 >> (cntbit % 8)))
{
if(T1_80usCnt >= 28)
{
IR_SEL_T3PWM;
T1_80usCnt = 0;
cntbit++;
if(0 == (cntbit % 8))
cntByte++;
}
}
// 发送完毕?
if(cntbit >= bitNum)
IRSendSta = IRSta_Stop;
// 继续发送?
else
IRSendSta = IRSta_T3PWM;
break;
// 红外编码数据部分发送完毕
case IRSta_Stop:
// 一组编码发送完毕 结束位是 0.56ms 的 38K 载波
while(T1_80usCnt < 7)
;
STOP_T1_T3; // stop T1 & T3
T1_80usCnt = 0;
IR_SEL_IOOUT;
CLR_IOB_BIT;
cntbit = 0;
cntByte = 0;
return 1;
break;
default:
return 0;
break;
}
}
}
/***********************************************************
** 函数名称: IRSend_T1_Init
** 实现功能: 红外编码发送定时器1初始化
** 入口参数: None
** 返回结果: None
***********************************************************/
void IRSend_T1_Init(void)
{
T1CTL = 0x0E; // f = 32MHz / 128 = 250 000Hz, T = 4us;模模式,从0~T1CC0反复计数。
T1CCTL0 = 0x44; // Timer1通道0中断允许,比较匹配模式,比较比配时输出置位。
T1CC0L = 19; // 先写T1CC0L,再写T1CC0H,T1CNT=0时更新。 4us*20 = 80us;
T1CC0H = 0;
TIMIF |= BIT_1(6); // TIMIF.T1OVFIM Timer1溢出中断允许
IEN1 |= BIT_1(1); // IEN1.T1IE Timer1总中断允许
EA = 1; // 打开全局总中断
T1_80usCnt = 0; // 80us溢出中断自增量清零
}
/***********************************************************
** 函数名称: IRSend_T3_Init
** 实现功能: 红外编码发送定时器3初始化
** 入口参数: None
** 返回结果: None
***********************************************************/
void IRSend_T3_Init(void)
{
P1SEL |= BIT_1(3); // P1.3 us as T3 PWM Out Pin.
T3CTL = 0x02; // T3CTL.MODE[10] 模模式,从0~T3CC0反复计数
T3CTL |= BIT_1(5); // T3CTL.MODE[001] f = 32MHz / 2 = 16MHz;
T3CCTL0 |= BIT_1(2); // T3CCTL0.MODE 输出比较比配模式
T3CCTL0 |= BIT_1(4); // T3CCTL0.CMP[010] 比较匹配时,输出取反
T3CC0 = 208; // Timer3通道0输出比较匹配上限值,16MHz / 208 = 76923.076923Hz; 76923 / 2 =38k(比较匹配时取反).
T3CTL |= BIT_1(4); // T3CTL.START 启动Timer3
P2SEL |= BIT_1(5); // P2SEL.PRI2P1 当USART1和Timer3占用相同引脚,Timer3优先。
T3CCTL0 |= BIT_1(6); // T3CCTL0.IM Timer3通道0中断允许。
IEN1 |= BIT_1(3); // IEN1.T3IE Timer3总中断允许。
EA = 1; // 全局总中断允许。
}
/***********************************************************
** 函数名称: IRSendInit
** 实现功能: 红外编码发送初始化
** 入口参数: None
** 返回结果: None
***********************************************************/
void IRSendInit(void)
{
IR_SEL_IOOUT;
CLR_IOB_BIT;
}
/***********************************************************
** 函数名称: IRSend_T1IntHandle
** 实现功能: Timer1 红外编码发送中的中断处理函数
** 入口参数: None
** 返回结果: None
***********************************************************/
#pragma vector = T1_VECTOR
__interrupt void IRSend_T1IntHandle(void)
{
T1STAT &= BIT_0(5); // T1STAT.OVFIF 清除Timer1溢出中断标志
T1STAT &= BIT_0(1); // T1STAT.CH0IF 清除Timer1通道0中断标志
IRCON &= BIT_0(1); // IRCON.T1IF 清除Timer1总中断标志
T1_80usCnt++;
}
/***********************************************************
** 函数名称: IRSend_T3IntHandle
** 实现功能: Timer3 红外编码发送中的中断处理函数
** 入口参数: None
** 返回结果: None
***********************************************************/
#pragma vector = T3_VECTOR
__near_func __interrupt void IRSend_T3IntHandle(void)
{
TIMIF &= BIT_0(1); // TIMIF.T3CH0IF
}
#endif // defined(HAL_IRENC) && (HAL_IRENC == TRUE)

View File

@@ -0,0 +1,809 @@
/**************************************************************************************************
Filename: _hal_uart_dma.c
Revised: $Date: 2010-04-01 18:14:33 -0700 (Thu, 01 Apr 2010) $
Revision: $Revision: 22068 $
Description: This file contains the interface to the H/W UART driver by DMA.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_assert.h"
#include "hal_board.h"
#include "hal_defs.h"
#include "hal_dma.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if defined MT_TASK
#include "mt_uart.h"
#endif
#include "osal.h"
/*********************************************************************
* MACROS
*/
//#define HAL_UART_ASSERT(expr) HAL_ASSERT((expr))
#define HAL_UART_ASSERT(expr)
#if defined HAL_BOARD_CC2430EB || defined HAL_BOARD_CC2430DB || defined HAL_BOARD_CC2430BB
#define HAL_UART_DMA_NEW_RX_BYTE(IDX) (DMA_PAD == LO_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_GET_RX_BYTE(IDX) (HI_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_CLR_RX_BYTE(IDX) (dmaCfg.rxBuf[(IDX)] = BUILD_UINT16((DMA_PAD ^ 0xFF), 0))
#else
#define HAL_UART_DMA_NEW_RX_BYTE(IDX) (DMA_PAD == HI_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_GET_RX_BYTE(IDX) (LO_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_CLR_RX_BYTE(IDX) (dmaCfg.rxBuf[(IDX)] = BUILD_UINT16(0, (DMA_PAD ^ 0xFF)))
#endif
/*********************************************************************
* CONSTANTS
*/
// UxCSR - USART Control and Status Register.
#define CSR_MODE 0x80
#define CSR_RE 0x40
#define CSR_SLAVE 0x20
#define CSR_FE 0x10
#define CSR_ERR 0x08
#define CSR_RX_BYTE 0x04
#define CSR_TX_BYTE 0x02
#define CSR_ACTIVE 0x01
// UxUCR - USART UART Control Register.
#define UCR_FLUSH 0x80
#define UCR_FLOW 0x40
#define UCR_D9 0x20
#define UCR_BIT9 0x10
#define UCR_PARITY 0x08
#define UCR_SPB 0x04
#define UCR_STOP 0x02
#define UCR_START 0x01
#define UTX0IE 0x04
#define UTX1IE 0x08
#define P2DIR_PRIPO 0xC0
// Incompatible redefinitions result with more than one UART driver sub-module.
#undef PxOUT
#undef PxDIR
#undef PxSEL
#undef UxCSR
#undef UxUCR
#undef UxDBUF
#undef UxBAUD
#undef UxGCR
#undef URXxIE
#undef URXxIF
#undef UTXxIE
#undef UTXxIF
#undef HAL_UART_PERCFG_BIT
#undef HAL_UART_Px_RTS
#undef HAL_UART_Px_CTS
#undef HAL_UART_Px_RX_TX
#if (HAL_UART_DMA == 1)
#define PxOUT P0
#define PxIN P0
#define PxDIR P0DIR
#define PxSEL P0SEL
#define UxCSR U0CSR
#define UxUCR U0UCR
#define UxDBUF U0DBUF
#define UxBAUD U0BAUD
#define UxGCR U0GCR
#define URXxIE URX0IE
#define URXxIF URX0IF
#define UTXxIE UTX0IE
#define UTXxIF UTX0IF
#else
#define PxOUT P1
#define PxIN P1
#define PxDIR P1DIR
#define PxSEL P1SEL
#define UxCSR U1CSR
#define UxUCR U1UCR
#define UxDBUF U1DBUF
#define UxBAUD U1BAUD
#define UxGCR U1GCR
#define URXxIE URX1IE
#define URXxIF URX1IF
#define UTXxIE UTX1IE
#define UTXxIF UTX1IF
#endif
#if (HAL_UART_DMA == 1)
#define HAL_UART_PERCFG_BIT 0x01 // USART0 on P0, Alt-1; so clear this bit.
#define HAL_UART_Px_RX_TX 0x0C // Peripheral I/O Select for Rx/Tx.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#else
#define HAL_UART_PERCFG_BIT 0x02 // USART1 on P1, Alt-2; so set this bit.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#define HAL_UART_Px_RX_TX 0xC0 // Peripheral I/O Select for Rx/Tx.
#endif
// The timeout tick is at 32-kHz, so multiply msecs by 33.
#define HAL_UART_MSECS_TO_TICKS 33
#if defined MT_TASK
#define HAL_UART_DMA_TX_MAX MT_UART_DEFAULT_MAX_TX_BUFF
#define HAL_UART_DMA_RX_MAX MT_UART_DEFAULT_MAX_RX_BUFF
#define HAL_UART_DMA_HIGH MT_UART_DEFAULT_THRESHOLD
#define HAL_UART_DMA_IDLE (MT_UART_DEFAULT_IDLE_TIMEOUT * HAL_UART_MSECS_TO_TICKS)
#else
#if !defined HAL_UART_DMA_RX_MAX
#define HAL_UART_DMA_RX_MAX 256
#endif
#if !defined HAL_UART_DMA_TX_MAX
#define HAL_UART_DMA_TX_MAX HAL_UART_DMA_RX_MAX
#endif
#if !defined HAL_UART_DMA_HIGH
#define HAL_UART_DMA_HIGH (HAL_UART_DMA_RX_MAX / 2 - 16)
#endif
#if !defined HAL_UART_DMA_IDLE
#define HAL_UART_DMA_IDLE (1 * HAL_UART_MSECS_TO_TICKS)
#endif
#endif
#if !defined HAL_UART_DMA_FULL
#define HAL_UART_DMA_FULL (HAL_UART_DMA_RX_MAX - 16)
#endif
#if defined HAL_BOARD_CC2430EB || defined HAL_BOARD_CC2430DB || defined HAL_BOARD_CC2430BB
#define HAL_DMA_U0DBUF 0xDFC1
#define HAL_DMA_U1DBUF 0xDFF9
#else /* CC2530 */
#define HAL_DMA_U0DBUF 0x70C1
#define HAL_DMA_U1DBUF 0x70F9
#endif
#if (HAL_UART_DMA == 1)
#define DMATRIG_RX HAL_DMA_TRIG_URX0
#define DMATRIG_TX HAL_DMA_TRIG_UTX0
#define DMA_UDBUF HAL_DMA_U0DBUF
#define DMA_PAD U0BAUD
#else
#define DMATRIG_RX HAL_DMA_TRIG_URX1
#define DMATRIG_TX HAL_DMA_TRIG_UTX1
#define DMA_UDBUF HAL_DMA_U1DBUF
#define DMA_PAD U1BAUD
#endif
/*********************************************************************
* TYPEDEFS
*/
#if HAL_UART_DMA_RX_MAX <= 256
typedef uint8 rxIdx_t;
#else
typedef uint16 rxIdx_t;
#endif
#if HAL_UART_DMA_TX_MAX <= 256
typedef uint8 txIdx_t;
#else
typedef uint16 txIdx_t;
#endif
typedef struct
{
uint16 rxBuf[HAL_UART_DMA_RX_MAX];
rxIdx_t rxHead;
rxIdx_t rxTail;
uint8 rxTick;
uint8 rxShdw;
uint8 txBuf[2][HAL_UART_DMA_TX_MAX];
txIdx_t txIdx[2];
volatile uint8 txSel;
uint8 txMT;
uint8 txTick; // 1-character time in 32kHz ticks according to baud rate,
// to be used in calculating time lapse since DMA ISR
// to allow delay margin before start firing DMA, so that
// DMA does not overwrite UART DBUF of previous packet
volatile uint8 txShdw; // Sleep Timer LSB shadow.
volatile uint8 txShdwValid; // TX shadow value is valid
uint8 txDMAPending; // UART TX DMA is pending
halUARTCBack_t uartCB;
} uartDMACfg_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
void HalUARTIsrDMA(void);
/*********************************************************************
* LOCAL VARIABLES
*/
static uartDMACfg_t dmaCfg;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static rxIdx_t findTail(void);
// Invoked by functions in hal_uart.c when this file is included.
static void HalUARTInitDMA(void);
static void HalUARTOpenDMA(halUARTCfg_t *config);
static uint16 HalUARTReadDMA(uint8 *buf, uint16 len);
static uint16 HalUARTWriteDMA(uint8 *buf, uint16 len);
static void HalUARTPollDMA(void);
static uint16 HalUARTRxAvailDMA(void);
static void HalUARTSuspendDMA(void);
static void HalUARTResumeDMA(void);
/*****************************************************************************
* @fn findTail
*
* @brief Find the rxBuf index where the DMA RX engine is working.
*
* @param None.
*
* @return Index of tail of rxBuf.
*****************************************************************************/
static rxIdx_t findTail(void)
{
rxIdx_t idx = dmaCfg.rxHead;
do
{
if (!HAL_UART_DMA_NEW_RX_BYTE(idx))
{
break;
}
#if HAL_UART_DMA_RX_MAX == 256
idx++;
#else
if (++idx >= HAL_UART_DMA_RX_MAX)
{
idx = 0;
}
#endif
} while (idx != dmaCfg.rxHead);
return idx;
}
/******************************************************************************
* @fn HalUARTInitDMA
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTInitDMA(void)
{
halDMADesc_t *ch;
P2DIR &= ~P2DIR_PRIPO;
P2DIR |= HAL_UART_PRIPO;
#if (HAL_UART_DMA == 1)
PERCFG &= ~HAL_UART_PERCFG_BIT; // Set UART0 I/O to Alt. 1 location on P0.
#else
PERCFG |= HAL_UART_PERCFG_BIT; // Set UART1 I/O to Alt. 2 location on P1.
#endif
PxSEL |= HAL_UART_Px_RX_TX; // Enable Tx and Rx on P1.
ADCCFG &= ~HAL_UART_Px_RX_TX; // Make sure ADC doesnt use this.
UxCSR = CSR_MODE; // Mode is UART Mode.
UxUCR = UCR_FLUSH; // Flush it.
// Setup Tx by DMA.
ch = HAL_DMA_GET_DESC1234( HAL_DMA_CH_TX );
// The start address of the destination.
HAL_DMA_SET_DEST( ch, DMA_UDBUF );
// Using the length field to determine how many bytes to transfer.
HAL_DMA_SET_VLEN( ch, HAL_DMA_VLEN_USE_LEN );
// One byte is transferred each time.
HAL_DMA_SET_WORD_SIZE( ch, HAL_DMA_WORDSIZE_BYTE );
// The bytes are transferred 1-by-1 on Tx Complete trigger.
HAL_DMA_SET_TRIG_MODE( ch, HAL_DMA_TMODE_SINGLE );
HAL_DMA_SET_TRIG_SRC( ch, DMATRIG_TX );
// The source address is incremented by 1 byte after each transfer.
HAL_DMA_SET_SRC_INC( ch, HAL_DMA_SRCINC_1 );
// The destination address is constant - the Tx Data Buffer.
HAL_DMA_SET_DST_INC( ch, HAL_DMA_DSTINC_0 );
// The DMA Tx done is serviced by ISR in order to maintain full thruput.
HAL_DMA_SET_IRQ( ch, HAL_DMA_IRQMASK_ENABLE );
// Xfer all 8 bits of a byte xfer.
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS );
// DMA has highest priority for memory access.
HAL_DMA_SET_PRIORITY( ch, HAL_DMA_PRI_HIGH );
// Setup Rx by DMA.
ch = HAL_DMA_GET_DESC1234( HAL_DMA_CH_RX );
// The start address of the source.
HAL_DMA_SET_SOURCE( ch, DMA_UDBUF );
// Using the length field to determine how many bytes to transfer.
HAL_DMA_SET_VLEN( ch, HAL_DMA_VLEN_USE_LEN );
/* The trick is to cfg DMA to xfer 2 bytes for every 1 byte of Rx.
* The byte after the Rx Data Buffer is the Baud Cfg Register,
* which always has a known value. So init Rx buffer to inverse of that
* known value. DMA word xfer will flip the bytes, so every valid Rx byte
* in the Rx buffer will be preceded by a DMA_PAD char equal to the
* Baud Cfg Register value.
*/
HAL_DMA_SET_WORD_SIZE( ch, HAL_DMA_WORDSIZE_WORD );
// The bytes are transferred 1-by-1 on Rx Complete trigger.
HAL_DMA_SET_TRIG_MODE( ch, HAL_DMA_TMODE_SINGLE_REPEATED );
HAL_DMA_SET_TRIG_SRC( ch, DMATRIG_RX );
// The source address is constant - the Rx Data Buffer.
HAL_DMA_SET_SRC_INC( ch, HAL_DMA_SRCINC_0 );
// The destination address is incremented by 1 word after each transfer.
HAL_DMA_SET_DST_INC( ch, HAL_DMA_DSTINC_1 );
HAL_DMA_SET_DEST( ch, dmaCfg.rxBuf );
HAL_DMA_SET_LEN( ch, HAL_UART_DMA_RX_MAX );
// The DMA is to be polled and shall not issue an IRQ upon completion.
HAL_DMA_SET_IRQ( ch, HAL_DMA_IRQMASK_DISABLE );
// Xfer all 8 bits of a byte xfer.
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS );
// DMA has highest priority for memory access.
HAL_DMA_SET_PRIORITY( ch, HAL_DMA_PRI_HIGH );
}
/******************************************************************************
* @fn HalUARTOpenDMA
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param config - contains configuration information
*
* @return none
*****************************************************************************/
static void HalUARTOpenDMA(halUARTCfg_t *config)
{
dmaCfg.uartCB = config->callBackFunc;
// Only supporting subset of baudrate for code size - other is possible.
HAL_UART_ASSERT((config->baudRate == HAL_UART_BR_9600) ||
(config->baudRate == HAL_UART_BR_19200) ||
(config->baudRate == HAL_UART_BR_38400) ||
(config->baudRate == HAL_UART_BR_57600) ||
(config->baudRate == HAL_UART_BR_115200));
if (config->baudRate == HAL_UART_BR_57600 ||
config->baudRate == HAL_UART_BR_115200)
{
UxBAUD = 216;
}
else
{
UxBAUD = 59;
}
switch (config->baudRate)
{
case HAL_UART_BR_9600:
UxGCR = 8;
dmaCfg.txTick = 35; // (32768Hz / (9600bps / 10 bits))
// 10 bits include start and stop bits.
break;
case HAL_UART_BR_19200:
UxGCR = 9;
dmaCfg.txTick = 18;
break;
case HAL_UART_BR_38400:
UxGCR = 10;
dmaCfg.txTick = 9;
break;
case HAL_UART_BR_57600:
UxGCR = 10;
dmaCfg.txTick = 6;
break;
default:
//HAL_UART_BR_115200
UxGCR = 11;
dmaCfg.txTick = 3;
break;
}
// 8 bits/char; no parity; 1 stop bit; stop bit hi.
if (config->flowControl)
{
UxUCR = UCR_FLOW | UCR_STOP;
PxSEL |= HAL_UART_Px_CTS;
// DMA Rx is always on (self-resetting). So flow must be controlled by the S/W polling the Rx
// buffer level. Start by allowing flow.
PxOUT &= ~HAL_UART_Px_RTS;
PxDIR |= HAL_UART_Px_RTS;
}
else
{
UxUCR = UCR_STOP;
}
dmaCfg.rxBuf[0] = *(volatile uint8 *)DMA_UDBUF; // Clear the DMA Rx trigger.
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_RX);
HAL_DMA_ARM_CH(HAL_DMA_CH_RX);
osal_memset(dmaCfg.rxBuf, (DMA_PAD ^ 0xFF), HAL_UART_DMA_RX_MAX*2);
UxCSR |= CSR_RE;
// Initialize that TX DMA is not pending
dmaCfg.txDMAPending = FALSE;
dmaCfg.txShdwValid = FALSE;
}
/*****************************************************************************
* @fn HalUARTReadDMA
*
* @brief Read a buffer from the UART
*
* @param buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
static uint16 HalUARTReadDMA(uint8 *buf, uint16 len)
{
uint16 cnt;
for (cnt = 0; cnt < len; cnt++)
{
if (!HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
break;
}
*buf++ = HAL_UART_DMA_GET_RX_BYTE(dmaCfg.rxHead);
HAL_UART_DMA_CLR_RX_BYTE(dmaCfg.rxHead);
#if HAL_UART_DMA_RX_MAX == 256
(dmaCfg.rxHead)++;
#else
if (++(dmaCfg.rxHead) >= HAL_UART_DMA_RX_MAX)
{
dmaCfg.rxHead = 0;
}
#endif
}
PxOUT &= ~HAL_UART_Px_RTS; // Re-enable the flow on any read.
return cnt;
}
/******************************************************************************
* @fn HalUARTWriteDMA
*
* @brief Write a buffer to the UART.
*
* @param buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
static uint16 HalUARTWriteDMA(uint8 *buf, uint16 len)
{
uint16 cnt;
halIntState_t his;
uint8 txSel;
txIdx_t txIdx;
// Enforce all or none.
if ((len + dmaCfg.txIdx[dmaCfg.txSel]) > HAL_UART_DMA_TX_MAX)
{
return 0;
}
HAL_ENTER_CRITICAL_SECTION(his);
txSel = dmaCfg.txSel;
txIdx = dmaCfg.txIdx[txSel];
HAL_EXIT_CRITICAL_SECTION(his);
for (cnt = 0; cnt < len; cnt++)
{
dmaCfg.txBuf[txSel][txIdx++] = buf[cnt];
}
HAL_ENTER_CRITICAL_SECTION(his);
if (txSel != dmaCfg.txSel)
{
HAL_EXIT_CRITICAL_SECTION(his);
txSel = dmaCfg.txSel;
txIdx = dmaCfg.txIdx[txSel];
for (cnt = 0; cnt < len; cnt++)
{
dmaCfg.txBuf[txSel][txIdx++] = buf[cnt];
}
HAL_ENTER_CRITICAL_SECTION(his);
}
dmaCfg.txIdx[txSel] = txIdx;
if (dmaCfg.txIdx[(txSel ^ 1)] == 0)
{
// TX DMA is expected to be fired
dmaCfg.txDMAPending = TRUE;
}
HAL_EXIT_CRITICAL_SECTION(his);
return cnt;
}
/******************************************************************************
* @fn HalUARTPollDMA
*
* @brief Poll a USART module implemented by DMA.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTPollDMA(void)
{
uint16 cnt = 0;
uint8 evt = 0;
if (HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
rxIdx_t tail = findTail();
// If the DMA has transferred in more Rx bytes, reset the Rx idle timer.
if (dmaCfg.rxTail != tail)
{
dmaCfg.rxTail = tail;
// Re-sync the shadow on any 1st byte(s) received.
if (dmaCfg.rxTick == 0)
{
dmaCfg.rxShdw = ST0;
}
dmaCfg.rxTick = HAL_UART_DMA_IDLE;
}
else if (dmaCfg.rxTick)
{
// Use the LSB of the sleep timer (ST0 must be read first anyway).
uint8 decr = ST0 - dmaCfg.rxShdw;
if (dmaCfg.rxTick > decr)
{
dmaCfg.rxTick -= decr;
dmaCfg.rxShdw = ST0;
}
else
{
dmaCfg.rxTick = 0;
}
}
cnt = HalUARTRxAvailDMA();
}
else
{
dmaCfg.rxTick = 0;
}
if (cnt >= HAL_UART_DMA_FULL)
{
evt = HAL_UART_RX_FULL;
}
else if (cnt >= HAL_UART_DMA_HIGH)
{
evt = HAL_UART_RX_ABOUT_FULL;
PxOUT |= HAL_UART_Px_RTS; // Disable Rx flow.
}
else if (cnt && !dmaCfg.rxTick)
{
evt = HAL_UART_RX_TIMEOUT;
}
if (dmaCfg.txMT)
{
dmaCfg.txMT = FALSE;
evt |= HAL_UART_TX_EMPTY;
}
if (dmaCfg.txShdwValid)
{
uint8 decr = ST0;
decr -= dmaCfg.txShdw;
if (decr > dmaCfg.txTick)
{
// No protection for txShdwValid is required
// because while the shadow was valid, DMA ISR cannot be triggered
// to cause concurrent access to this variable.
dmaCfg.txShdwValid = FALSE;
}
}
if (dmaCfg.txDMAPending && !dmaCfg.txShdwValid)
{
// UART TX DMA is expected to be fired and enough time has lapsed since last DMA ISR
// to know that DBUF can be overwritten
halDMADesc_t *ch = HAL_DMA_GET_DESC1234(HAL_DMA_CH_TX);
halIntState_t intState;
// Clear the DMA pending flag
dmaCfg.txDMAPending = FALSE;
HAL_DMA_SET_SOURCE(ch, dmaCfg.txBuf[dmaCfg.txSel]);
HAL_DMA_SET_LEN(ch, dmaCfg.txIdx[dmaCfg.txSel]);
dmaCfg.txSel ^= 1;
HAL_ENTER_CRITICAL_SECTION(intState);
HAL_DMA_ARM_CH(HAL_DMA_CH_TX);
do
{
asm("NOP");
} while (!HAL_DMA_CH_ARMED(HAL_DMA_CH_TX));
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_TX);
HAL_DMA_MAN_TRIGGER(HAL_DMA_CH_TX);
HAL_EXIT_CRITICAL_SECTION(intState);
}
else
{
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
if ((dmaCfg.txIdx[dmaCfg.txSel] != 0) && !HAL_DMA_CH_ARMED(HAL_DMA_CH_TX)
&& !HAL_DMA_CHECK_IRQ(HAL_DMA_CH_TX))
{
HAL_EXIT_CRITICAL_SECTION(his);
HalUARTIsrDMA();
}
else
{
HAL_EXIT_CRITICAL_SECTION(his);
}
}
if (evt && (dmaCfg.uartCB != NULL))
{
dmaCfg.uartCB(HAL_UART_DMA-1, evt);
}
}
/**************************************************************************************************
* @fn HalUARTRxAvailDMA()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param none
*
* @return length of current Rx Buffer
**************************************************************************************************/
static uint16 HalUARTRxAvailDMA(void)
{
uint16 cnt = 0;
if (HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
uint16 idx;
for (idx = 0; idx < HAL_UART_DMA_RX_MAX; idx++)
{
if (HAL_UART_DMA_NEW_RX_BYTE(idx))
{
cnt++;
}
}
}
return cnt;
}
/******************************************************************************
* @fn HalUARTSuspendDMA
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTSuspendDMA( void )
{
PxOUT |= HAL_UART_Px_RTS; // Disable Rx flow.
UxCSR &= ~CSR_RE;
P0IEN |= HAL_UART_Px_CTS; // Enable the CTS ISR.
}
/******************************************************************************
* @fn HalUARTResumeDMA
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTResumeDMA( void )
{
P0IEN &= ~HAL_UART_Px_CTS; // Disable the CTS ISR.
UxUCR |= UCR_FLUSH;
UxCSR |= CSR_RE;
PxOUT &= ~HAL_UART_Px_RTS; // Re-enable Rx flow.
}
/******************************************************************************
* @fn HalUARTIsrDMA
*
* @brief Handle the Tx done DMA ISR.
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTIsrDMA(void);
void HalUARTIsrDMA(void)
{
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_TX);
// Indicate that the other buffer is free now.
dmaCfg.txIdx[(dmaCfg.txSel ^ 1)] = 0;
dmaCfg.txMT = TRUE;
// Set TX shadow
dmaCfg.txShdw = ST0;
dmaCfg.txShdwValid = TRUE;
// If there is more Tx data ready to go, re-start the DMA immediately on it.
if (dmaCfg.txIdx[dmaCfg.txSel])
{
// UART TX DMA is expected to be fired
dmaCfg.txDMAPending = TRUE;
}
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,587 @@
/**************************************************************************************************
Filename: _hal_uart_isr.c
Revised: $Date: 2010-03-10 20:36:55 -0800 (Wed, 10 Mar 2010) $
Revision: $Revision: 21890 $
Description: This file contains the interface to the H/W UART driver by ISR.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_assert.h"
#include "hal_board.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if defined MT_TASK
#include "MT_UART.h"
#endif
/*********************************************************************
* MACROS
*/
//#define HAL_UART_ASSERT(expr) HAL_ASSERT((expr))
#define HAL_UART_ASSERT(expr)
#define HAL_UART_ISR_RX_AVAIL() \
(isrCfg.rxTail >= isrCfg.rxHead) ? \
(isrCfg.rxTail - isrCfg.rxHead) : \
(HAL_UART_ISR_RX_MAX - isrCfg.rxHead + isrCfg.rxTail)
#define HAL_UART_ISR_TX_AVAIL() \
(isrCfg.txHead > isrCfg.txTail) ? \
(isrCfg.txHead - isrCfg.txTail - 1) : \
(HAL_UART_ISR_TX_MAX - isrCfg.txTail + isrCfg.txHead - 1)
/*********************************************************************
* CONSTANTS
*/
// UxCSR - USART Control and Status Register.
#define CSR_MODE 0x80
#define CSR_RE 0x40
#define CSR_SLAVE 0x20
#define CSR_FE 0x10
#define CSR_ERR 0x08
#define CSR_RX_BYTE 0x04
#define CSR_TX_BYTE 0x02
#define CSR_ACTIVE 0x01
// UxUCR - USART UART Control Register.
#define UCR_FLUSH 0x80
#define UCR_FLOW 0x40
#define UCR_D9 0x20
#define UCR_BIT9 0x10
#define UCR_PARITY 0x08
#define UCR_SPB 0x04
#define UCR_STOP 0x02
#define UCR_START 0x01
#define UTX0IE 0x04
#define UTX1IE 0x08
#define P2DIR_PRIPO 0xC0
// Incompatible redefinitions result with more than one UART driver sub-module.
#undef PxOUT
#undef PxDIR
#undef PxSEL
#undef UxCSR
#undef UxUCR
#undef UxDBUF
#undef UxBAUD
#undef UxGCR
#undef URXxIE
#undef URXxIF
#undef UTXxIE
#undef UTXxIF
#undef HAL_UART_PERCFG_BIT
#undef HAL_UART_Px_RTS
#undef HAL_UART_Px_CTS
#undef HAL_UART_Px_RX_TX
#if (HAL_UART_ISR == 1)
#define PxOUT P0
#define PxDIR P0DIR
#define PxSEL P0SEL
#define UxCSR U0CSR
#define UxUCR U0UCR
#define UxDBUF U0DBUF
#define UxBAUD U0BAUD
#define UxGCR U0GCR
#define URXxIE URX0IE
#define URXxIF URX0IF
#define UTXxIE UTX0IE
#define UTXxIF UTX0IF
#else
#define PxOUT P1
#define PxDIR P1DIR
#define PxSEL P1SEL
#define UxCSR U1CSR
#define UxUCR U1UCR
#define UxDBUF U1DBUF
#define UxBAUD U1BAUD
#define UxGCR U1GCR
#define URXxIE URX1IE
#define URXxIF URX1IF
#define UTXxIE UTX1IE
#define UTXxIF UTX1IF
#endif
#if (HAL_UART_ISR == 1)
#define HAL_UART_PERCFG_BIT 0x01 // USART0 on P0, Alt-1; so clear this bit.
#define HAL_UART_Px_RX_TX 0x0C // Peripheral I/O Select for Rx/Tx.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#else
#define HAL_UART_PERCFG_BIT 0x02 // USART1 on P1, Alt-2; so set this bit.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#define HAL_UART_Px_RX_TX 0xC0 // Peripheral I/O Select for Rx/Tx.
#endif
// The timeout tick is at 32-kHz, so multiply msecs by 33.
#define HAL_UART_MSECS_TO_TICKS 33
#if defined MT_TASK
#define HAL_UART_ISR_TX_MAX MT_UART_DEFAULT_MAX_TX_BUFF
#define HAL_UART_ISR_RX_MAX MT_UART_DEFAULT_MAX_RX_BUFF
#define HAL_UART_ISR_HIGH MT_UART_DEFAULT_THRESHOLD
#define HAL_UART_ISR_IDLE (MT_UART_DEFAULT_IDLE_TIMEOUT * HAL_UART_MSECS_TO_TICKS)
#else
#if !defined HAL_UART_ISR_RX_MAX
#define HAL_UART_ISR_RX_MAX 128
#endif
#if !defined HAL_UART_ISR_TX_MAX
#define HAL_UART_ISR_TX_MAX HAL_UART_ISR_RX_MAX
#endif
#if !defined HAL_UART_ISR_HIGH
#define HAL_UART_ISR_HIGH (HAL_UART_ISR_RX_MAX / 2 - 16)
#endif
#if !defined HAL_UART_ISR_IDLE
#define HAL_UART_ISR_IDLE (6 * HAL_UART_MSECS_TO_TICKS)
#endif
#endif
/*********************************************************************
* TYPEDEFS
*/
typedef struct
{
uint8 rxBuf[HAL_UART_ISR_RX_MAX];
#if HAL_UART_ISR_RX_MAX < 256
uint8 rxHead;
volatile uint8 rxTail;
#else
uint16 rxHead;
volatile uint16 rxTail;
#endif
uint8 rxTick;
uint8 rxShdw;
uint8 txBuf[HAL_UART_ISR_TX_MAX];
#if HAL_UART_ISR_TX_MAX < 256
volatile uint8 txHead;
uint8 txTail;
#else
volatile uint16 txHead;
uint16 txTail;
#endif
uint8 txMT;
halUARTCBack_t uartCB;
} uartISRCfg_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
static uartISRCfg_t isrCfg;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void HalUARTInitISR(void);
static void HalUARTOpenISR(halUARTCfg_t *config);
uint16 HalUARTReadISR(uint8 *buf, uint16 len);
uint16 HalUARTWriteISR(uint8 *buf, uint16 len);
static void HalUARTPollISR(void);
static uint16 HalUARTRxAvailISR(void);
static void HalUARTSuspendISR(void);
static void HalUARTResumeISR(void);
/******************************************************************************
* @fn HalUARTInitISR
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTInitISR(void)
{
// Set P2 priority - USART0 over USART1 if both are defined.
P2DIR &= ~P2DIR_PRIPO;
P2DIR |= HAL_UART_PRIPO;
#if (HAL_UART_ISR == 1)
PERCFG &= ~HAL_UART_PERCFG_BIT; // Set UART0 I/O location to P0.
#else
PERCFG |= HAL_UART_PERCFG_BIT; // Set UART1 I/O location to P1.
#endif
PxSEL |= HAL_UART_Px_RX_TX; // Enable Tx and Rx on P1.
ADCCFG &= ~HAL_UART_Px_RX_TX; // Make sure ADC doesnt use this.
UxCSR = CSR_MODE; // Mode is UART Mode.
UxUCR = UCR_FLUSH; // Flush it.
}
/******************************************************************************
* @fn HalUARTUnInitISR
*
* @brief UnInitialize the UART.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTUnInitISR(void)
{
UxCSR = 0;
URXxIE = 0;
URXxIF = 0;
IEN2 &= ~UTXxIE;
UTXxIF = 0;
}
/******************************************************************************
* @fn HalUARTOpenISR
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param config - contains configuration information
*
* @return none
*****************************************************************************/
static void HalUARTOpenISR(halUARTCfg_t *config)
{
isrCfg.uartCB = config->callBackFunc;
// Only supporting subset of baudrate for code size - other is possible.
HAL_UART_ASSERT((config->baudRate == HAL_UART_BR_9600) ||
(config->baudRate == HAL_UART_BR_19200) ||
(config->baudRate == HAL_UART_BR_38400) ||
(config->baudRate == HAL_UART_BR_57600) ||
(config->baudRate == HAL_UART_BR_115200));
if (config->baudRate == HAL_UART_BR_57600 ||
config->baudRate == HAL_UART_BR_115200)
{
UxBAUD = 216;
}
else
{
UxBAUD = 59;
}
switch (config->baudRate)
{
case HAL_UART_BR_9600:
UxGCR = 8;
break;
case HAL_UART_BR_19200:
UxGCR = 9;
break;
case HAL_UART_BR_38400:
case HAL_UART_BR_57600:
UxGCR = 10;
break;
default:
UxGCR = 11;
break;
}
// 8 bits/char; no parity; 1 stop bit; stop bit hi.
if (config->flowControl)
{
UxUCR = UCR_FLOW | UCR_STOP;
PxSEL |= HAL_UART_Px_RTS | HAL_UART_Px_CTS;
}
else
{
UxUCR = UCR_STOP;
}
UxCSR |= CSR_RE;
URXxIE = 1;
UTXxIF = 1; // Prime the ISR pump.
}
/*****************************************************************************
* @fn HalUARTReadISR
*
* @brief Read a buffer from the UART
*
* @param buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
uint16 HalUARTReadISR(uint8 *buf, uint16 len)
{
uint16 cnt = 0;
while ((isrCfg.rxHead != isrCfg.rxTail) && (cnt < len))
{
*buf++ = isrCfg.rxBuf[isrCfg.rxHead++];
if (isrCfg.rxHead >= HAL_UART_ISR_RX_MAX)
{
isrCfg.rxHead = 0;
}
cnt++;
}
return cnt;
}
/******************************************************************************
* @fn HalUARTWriteISR
*
* @brief Write a buffer to the UART.
*
* @param buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
uint16 HalUARTWriteISR(uint8 *buf, uint16 len)
{
uint16 cnt;
// Enforce all or none.
if (HAL_UART_ISR_TX_AVAIL() < len)
{
return 0;
}
for (cnt = 0; cnt < len; cnt++)
{
isrCfg.txBuf[isrCfg.txTail] = *buf++;
isrCfg.txMT = 0;
if (isrCfg.txTail >= HAL_UART_ISR_TX_MAX-1)
{
isrCfg.txTail = 0;
}
else
{
isrCfg.txTail++;
}
// Keep re-enabling ISR as it might be keeping up with this loop due to other ints.
IEN2 |= UTXxIE;
}
return cnt;
}
/******************************************************************************
* @fn HalUARTPollISR
*
* @brief Poll a USART module implemented by ISR.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTPollISR(void)
{
if (isrCfg.uartCB != NULL)
{
uint16 cnt = HAL_UART_ISR_RX_AVAIL();
uint8 evt = 0;
if (isrCfg.rxTick)
{
// Use the LSB of the sleep timer (ST0 must be read first anyway).
uint8 decr = ST0 - isrCfg.rxShdw;
if (isrCfg.rxTick > decr)
{
isrCfg.rxTick -= decr;
}
else
{
isrCfg.rxTick = 0;
}
}
isrCfg.rxShdw = ST0;
if (cnt >= HAL_UART_ISR_RX_MAX-1)
{
evt = HAL_UART_RX_FULL;
}
else if (cnt >= HAL_UART_ISR_HIGH)
{
evt = HAL_UART_RX_ABOUT_FULL;
}
else if (cnt && !isrCfg.rxTick)
{
evt = HAL_UART_RX_TIMEOUT;
}
if (isrCfg.txMT)
{
isrCfg.txMT = 0;
evt |= HAL_UART_TX_EMPTY;
}
if (evt)
{
isrCfg.uartCB(HAL_UART_ISR-1, evt);
}
}
}
/**************************************************************************************************
* @fn HalUARTRxAvailISR()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param none
*
* @return length of current Rx Buffer
**************************************************************************************************/
static uint16 HalUARTRxAvailISR(void)
{
return HAL_UART_ISR_RX_AVAIL();
}
/******************************************************************************
* @fn HalUARTSuspendISR
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTSuspendISR( void )
{
UxCSR &= ~CSR_RE;
}
/******************************************************************************
* @fn HalUARTResumeISR
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTResumeISR( void )
{
UxUCR |= UCR_FLUSH;
UxCSR |= CSR_RE;
}
/***************************************************************************************************
* @fn halUartRxIsr
*
* @brief UART Receive Interrupt
*
* @param None
*
* @return None
***************************************************************************************************/
#if defined HAL_SB_BOOT_CODE
static void halUartRxIsr(void);
static void halUartRxIsr(void)
#else
#if (HAL_UART_ISR == 1)
HAL_ISR_FUNCTION( halUart0RxIsr, URX0_VECTOR )
#else
HAL_ISR_FUNCTION( halUart1RxIsr, URX1_VECTOR )
#endif
#endif
{
uint8 tmp = UxDBUF;
isrCfg.rxBuf[isrCfg.rxTail] = tmp;
// Re-sync the shadow on any 1st byte received.
if (isrCfg.rxHead == isrCfg.rxTail)
{
isrCfg.rxShdw = ST0;
}
if (++isrCfg.rxTail >= HAL_UART_ISR_RX_MAX)
{
isrCfg.rxTail = 0;
}
isrCfg.rxTick = HAL_UART_ISR_IDLE;
}
/***************************************************************************************************
* @fn halUartTxIsr
*
* @brief UART Transmit Interrupt
*
* @param None
*
* @return None
***************************************************************************************************/
#if defined HAL_SB_BOOT_CODE
static void halUartTxIsr(void);
static void halUartTxIsr(void)
#else
#if (HAL_UART_ISR == 1)
HAL_ISR_FUNCTION( halUart0TxIsr, UTX0_VECTOR )
#else
HAL_ISR_FUNCTION( halUart1TxIsr, UTX1_VECTOR )
#endif
#endif
{
if (isrCfg.txHead == isrCfg.txTail)
{
IEN2 &= ~UTXxIE;
isrCfg.txMT = 1;
}
else
{
UTXxIF = 0;
UxDBUF = isrCfg.txBuf[isrCfg.txHead++];
if (isrCfg.txHead >= HAL_UART_ISR_TX_MAX)
{
isrCfg.txHead = 0;
}
}
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,240 @@
/**************************************************************************************************
Filename: hal_adc.c
Revised: $Date: 2010-03-12 16:10:36 -0800 (Fri, 12 Mar 2010) $
Revision: $Revision: 21910 $
Description: This file contains the interface to the HAL ADC.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_adc.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_ADC_EOC 0x80 /* End of Conversion bit */
#define HAL_ADC_START 0x40 /* Starts Conversion */
#define HAL_ADC_STSEL_EXT 0x00 /* External Trigger */
#define HAL_ADC_STSEL_FULL 0x10 /* Full Speed, No Trigger */
#define HAL_ADC_STSEL_T1C0 0x20 /* Timer1, Channel 0 Compare Event Trigger */
#define HAL_ADC_STSEL_ST 0x30 /* ADCCON1.ST =1 Trigger */
#define HAL_ADC_RAND_NORM 0x00 /* Normal Operation */
#define HAL_ADC_RAND_LFSR 0x04 /* Clock LFSR */
#define HAL_ADC_RAND_SEED 0x08 /* Seed Modulator */
#define HAL_ADC_RAND_STOP 0x0c /* Stop Random Generator */
#define HAL_ADC_RAND_BITS 0x0c /* Bits [3:2] */
#define HAL_ADC_DEC_064 0x00 /* Decimate by 64 : 8-bit resolution */
#define HAL_ADC_DEC_128 0x10 /* Decimate by 128 : 10-bit resolution */
#define HAL_ADC_DEC_256 0x20 /* Decimate by 256 : 12-bit resolution */
#define HAL_ADC_DEC_512 0x30 /* Decimate by 512 : 14-bit resolution */
#define HAL_ADC_DEC_BITS 0x30 /* Bits [5:4] */
#define HAL_ADC_STSEL HAL_ADC_STSEL_ST
#define HAL_ADC_RAND_GEN HAL_ADC_RAND_STOP
#define HAL_ADC_REF_VOLT HAL_ADC_REF_AVDD
#define HAL_ADC_DEC_RATE HAL_ADC_DEC_064
#define HAL_ADC_SCHN HAL_ADC_CHN_VDD3
#define HAL_ADC_ECHN HAL_ADC_CHN_GND
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
#if (HAL_ADC == TRUE)
static uint8 adcRef;
#endif
/**************************************************************************************************
* @fn HalAdcInit
*
* @brief Initialize ADC Service
*
* @param None
*
* @return None
**************************************************************************************************/
void HalAdcInit (void)
{
#if (HAL_ADC == TRUE)
adcRef = HAL_ADC_REF_VOLT;
#endif
}
/**************************************************************************************************
* @fn HalAdcRead
*
* @brief Read the ADC based on given channel and resolution
*
* @param channel - channel where ADC will be read
* @param resolution - the resolution of the value
*
* @return 16 bit value of the ADC in offset binary format.
*
* Note that the ADC is "bipolar", which means the GND (0V) level is mid-scale.
* Note2: This function assumes that ADCCON3 contains the voltage reference.
**************************************************************************************************/
uint16 HalAdcRead (uint8 channel, uint8 resolution)
{
int16 reading = 0;
#if (HAL_ADC == TRUE)
uint8 i, resbits;
uint8 adcChannel = 1;
/*
* If Analog input channel is AIN0..AIN7, make sure corresponing P0 I/O pin is enabled. The code
* does NOT disable the pin at the end of this function. I think it is better to leave the pin
* enabled because the results will be more accurate. Because of the inherent capacitance on the
* pin, it takes time for the voltage on the pin to charge up to its steady-state level. If
* HalAdcRead() has to turn on the pin for every conversion, the results may show a lower voltage
* than actuality because the pin did not have time to fully charge.
*/
if (channel < 8)
{
for (i=0; i < channel; i++)
{
adcChannel <<= 1;
}
}
/* Enable channel */
ADCCFG |= adcChannel;
/* Convert resolution to decimation rate */
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
resbits = HAL_ADC_DEC_064;
break;
case HAL_ADC_RESOLUTION_10:
resbits = HAL_ADC_DEC_128;
break;
case HAL_ADC_RESOLUTION_12:
resbits = HAL_ADC_DEC_256;
break;
case HAL_ADC_RESOLUTION_14:
default:
resbits = HAL_ADC_DEC_512;
break;
}
/* writing to this register starts the extra conversion */
ADCCON3 = channel | resbits | adcRef;
/* Wait for the conversion to be done */
while (!(ADCCON1 & HAL_ADC_EOC));
/* Disable channel after done conversion */
ADCCFG &= (adcChannel ^ 0xFF);
/* Read the result */
reading = (int16) (ADCL);
reading |= (int16) (ADCH << 8);
/* Treat small negative as 0 */
if (reading < 0)
reading = 0;
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
reading >>= 8;
break;
case HAL_ADC_RESOLUTION_10:
reading >>= 6;
break;
case HAL_ADC_RESOLUTION_12:
reading >>= 4;
break;
case HAL_ADC_RESOLUTION_14:
default:
reading >>= 2;
break;
}
#else
// unused arguments
(void) channel;
(void) resolution;
#endif
return ((uint16)reading);
}
/**************************************************************************************************
* @fn HalAdcSetReference
*
* @brief Sets the reference voltage for the ADC and initializes the service
*
* @param reference - the reference voltage to be used by the ADC
*
* @return none
*
**************************************************************************************************/
void HalAdcSetReference ( uint8 reference )
{
#if (HAL_ADC == TRUE)
adcRef = reference;
#endif
}
/*********************************************************************
* @fn HalAdcCheckVdd
*
* @brief Check for minimum Vdd specified.
*
* @param vdd - The board-specific Vdd reading to check for.
*
* @return TRUE if the Vdd measured is greater than the 'vdd' minimum parameter;
* FALSE if not.
*
*********************************************************************/
bool HalAdcCheckVdd(uint8 vdd)
{
ADCCON3 = 0x0F;
while (!(ADCCON1 & 0x80));
return (ADCH > vdd);
}
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,124 @@
/**************************************************************************************************
Filename: hal_aes.h
Revised: $Date: 2010-01-08 13:24:55 -0800 (Fri, 08 Jan 2010) $
Revision: $Revision: 21463 $
Description: Support for HW/SW AES encryption.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_AES_H_
#define HAL_AES_H_
#include "ZComDef.h"
#define STATE_BLENGTH 16 // Number of bytes in State
#define KEY_BLENGTH 16 // Number of bytes in Key
#define KEY_EXP_LENGTH 176 // Nb * (Nr+1) * 4
/* AES Engine is default to hardware AES. To turn on software AES, #define one of the followings:
* #define SOFTWARE_AES TRUE, uses software aes ( slowest setting )
* #define SW_AES_AND_KEY_EXP TRUE, enables software aes with key expansion ( improves speed at the cost of 176 bytes of data (RAM) )
*/
#if ((defined SOFTWARE_AES) && (SOFTWARE_AES == TRUE)) && ((defined SW_AES_AND_KEY_EXP) && (SW_AES_AND_KEY_EXP == TRUE))
#error "SOFTWARE_AES and SW_AES_AND_KEY_EXP cannot be both defined."
#endif
extern void HalAesInit( void );
extern void AesLoadBlock( uint8 * );
extern void AesStartBlock( uint8 *, uint8 * );
extern void AesStartShortBlock( uint8 *, uint8 * );
extern void AesLoadIV(uint8 *);
extern void AesDmaSetup( uint8 *, uint16, uint8 *, uint16 );
extern void AesLoadKey( uint8 * );
extern void (*pSspAesEncrypt)( uint8 *, uint8 * );
extern void ssp_HW_KeyInit (uint8 *);
extern void sspKeyExpansion (uint8 *, uint8 *);
extern void sspAesEncryptHW (uint8 *, uint8 *);
extern void sspAesEncryptKeyExp (uint8 *, uint8 *);
extern void sspAesEncryptBasic (uint8 *, uint8 *);
extern void sspAesEncrypt( uint8 *key, uint8 *buf );
#define AES_BUSY 0x08
#define ENCRYPT 0x00
#define DECRYPT 0x01
// Macro for setting the mode of the AES operation
#define AES_SETMODE(mode) do { ENCCS &= ~0x70; ENCCS |= mode; } while (0)
// _mode_ is one of
#define CBC 0x00
#define CFB 0x10
#define OFB 0x20
#define CTR 0x30
#define ECB 0x40
#define CBC_MAC 0x50
// Macro for starting or stopping encryption or decryption
#define AES_SET_ENCR_DECR_KEY_IV(mode) \
do { \
ENCCS = (ENCCS & ~0x07) | mode \
} while(0)
// Where _mode_ is one of
#define AES_ENCRYPT 0x00;
#define AES_DECRYPT 0x02;
#define AES_LOAD_KEY 0x04;
#define AES_LOAD_IV 0x06;
// Macro for starting the AES module for either encryption, decryption,
// key or initialisation vector loading.
#define AES_START() ENCCS |= 0x01
/* Used by DMA macros to shift 1 to create a mask for DMA registers. */
#define HAL_DMA_AES_IN 1
#define HAL_DMA_AES_OUT 2
/* AES registers */
#define HAL_AES_IN_ADDR 0x70B1
#define HAL_AES_OUT_ADDR 0x70B2
#if !defined (HAL_AES_DMA) || (HAL_AES_DMA == FALSE)
#define HAL_AES_DELAY() \
do { \
uint8 delay = 15; \
while(delay--); \
} while(0)
#endif
// End of CC2530 hardware AES engine definitions
#endif // HAL_AES_H_

View File

@@ -0,0 +1,517 @@
/**************************************************************************************************
Filename: hal_board_cfg.h
Revised: $Date: 2010-06-24 11:52:41 -0700 (Thu, 24 Jun 2010) $
Revision: $Revision: 22814 $
Description: Declarations for the CC2530EM used on the SmartRF05EB.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_BOARD_CFG_H
#define HAL_BOARD_CFG_H
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* CC2590/CC2591 support
*
* Define HAL_PA_LNA_CC2590 if CC2530+CC2590EM is used
* Define HAL_PA_LNA if CC2530+CC2591EM is used
* Note that only one of them can be defined
* ------------------------------------------------------------------------------------------------
*/
#define xHAL_PA_LNA
#define xHAL_PA_LNA_CC2590
/* ------------------------------------------------------------------------------------------------
* Board Indentifier
*
* Define the Board Identifier to HAL_BOARD_CC2530EB_REV13 for SmartRF05 EB 1.3 board
* ------------------------------------------------------------------------------------------------
*/
#if !defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_BOARD_CC2530EB_REV13)
#define HAL_BOARD_CC2530EB_REV17
#endif
/* ------------------------------------------------------------------------------------------------
* Clock Speed
* ------------------------------------------------------------------------------------------------
*/
#define HAL_CPU_CLOCK_MHZ 32
/* This flag should be defined if the SoC uses the 32MHz crystal
* as the main clock source (instead of DCO).
*/
#define HAL_CLOCK_CRYSTAL
/* 32 kHz clock source select in CLKCONCMD */
#if !defined (OSC32K_CRYSTAL_INSTALLED) || (defined (OSC32K_CRYSTAL_INSTALLED) && (OSC32K_CRYSTAL_INSTALLED == TRUE))
#define OSC_32KHZ 0x00 /* external 32 KHz xosc */
#else
#define OSC_32KHZ 0x80 /* internal 32 KHz rcosc */
#endif
#define HAL_CLOCK_STABLE() st( while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); )
/* ------------------------------------------------------------------------------------------------
* LED Configuration
* ------------------------------------------------------------------------------------------------
*/
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_NUM_LEDS 3
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_NUM_LEDS 1
#else
#error Unknown Board Indentifier
#endif
#define HAL_LED_BLINK_DELAY() st( { volatile uint32 i; for (i=0; i<0x5800; i++) { }; } )
/* 1 - Green */
#define LED1_BV BV(0)
#define LED1_SBIT P2_0
#define LED1_DDR P2DIR
#define LED1_POLARITY ACTIVE_LOW
#if defined (HAL_BOARD_CC2530EB_REV17)
/* 2 - Red */
#define LED2_BV BV(1)
#define LED2_SBIT P1_1
#define LED2_DDR P1DIR
#define LED2_POLARITY ACTIVE_LOW
/* 3 - Yellow */
#define LED3_BV BV(4)
#define LED3_SBIT P1_4
#define LED3_DDR P1DIR
#define LED3_POLARITY ACTIVE_HIGH
#endif
/* ------------------------------------------------------------------------------------------------
* Push Button Configuration
* ------------------------------------------------------------------------------------------------
*/
#define ACTIVE_LOW !
#define ACTIVE_HIGH !! /* double negation forces result to be '1' */
/* S1 */
#define PUSH1_BV BV(1)
#define PUSH1_SBIT P0_1
#if defined (HAL_BOARD_CC2530EB_REV17)
#define PUSH1_POLARITY ACTIVE_HIGH
#elif defined (HAL_BOARD_CC2530EB_REV13)
#define PUSH1_POLARITY ACTIVE_LOW
#else
#error Unknown Board Indentifier
#endif
/* Joystick Center Press */
#define PUSH2_BV BV(0)
#define PUSH2_SBIT P1_0
#define PUSH2_POLARITY ACTIVE_HIGH
/* ------------------------------------------------------------------------------------------------
* OSAL NV implemented by internal flash pages.
* ------------------------------------------------------------------------------------------------
*/
// Flash is partitioned into 8 banks of 32 KB or 16 pages.
#define HAL_FLASH_PAGE_PER_BANK 16
// Flash is constructed of 128 pages of 2 KB.
#define HAL_FLASH_PAGE_SIZE 2048
#define HAL_FLASH_WORD_SIZE 4
// CODE banks get mapped into the XDATA range 8000-FFFF.
#define HAL_FLASH_PAGE_MAP 0x8000
// The last 16 bytes of the last available page are reserved for flash lock bits.
// NV page definitions must coincide with segment declaration in project *.xcl file.
#if defined NON_BANKED
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 30
#define HAL_NV_PAGE_CNT 2
#else
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 126
#define HAL_NV_PAGE_CNT 6
#endif
// Re-defining Z_EXTADDR_LEN here so as not to include a Z-Stack .h file.
#define HAL_FLASH_IEEE_SIZE 8
#define HAL_FLASH_IEEE_PAGE (HAL_NV_PAGE_END+1)
#define HAL_FLASH_IEEE_OSET (HAL_FLASH_PAGE_SIZE - HAL_FLASH_LOCK_BITS - HAL_FLASH_IEEE_SIZE)
#define HAL_INFOP_IEEE_OSET 0xC
// add by lijian 20120821
#define HAL_FLASH_PID_SIZE 2
#define HAL_FLASH_PID_OSET 0
// end of add
#define HAL_FLASH_DEV_PRIVATE_KEY_OSET 0x7D2
#define HAL_FLASH_CA_PUBLIC_KEY_OSET 0x7BC
#define HAL_FLASH_IMPLICIT_CERT_OSET 0x78C
#define HAL_NV_PAGE_BEG (HAL_NV_PAGE_END-HAL_NV_PAGE_CNT+1)
// Used by DMA macros to shift 1 to create a mask for DMA registers.
#define HAL_NV_DMA_CH 0
#define HAL_DMA_CH_RX 3
#define HAL_DMA_CH_TX 4
#define HAL_NV_DMA_GET_DESC() HAL_DMA_GET_DESC0()
#define HAL_NV_DMA_SET_ADDR(a) HAL_DMA_SET_ADDR_DESC0((a))
/* ------------------------------------------------------------------------------------------------
* Serial Boot Loader: reserving the first 4 pages of flash and other memory in cc2530-sb.xcl.
* ------------------------------------------------------------------------------------------------
*/
#define HAL_SB_IMG_ADDR 0x2000
#define HAL_SB_CRC_ADDR 0x2090
// Size of internal flash less 4 pages for boot loader, 6 pages for NV, & 1 page for lock bits.
#define HAL_SB_IMG_SIZE (0x40000 - 0x2000 - 0x3000 - 0x0800)
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/* ----------- RF-frontend Connection Initialization ---------- */
#if defined HAL_PA_LNA || defined HAL_PA_LNA_CC2590
extern void MAC_RfFrontendSetup(void);
#define HAL_BOARD_RF_FRONTEND_SETUP() MAC_RfFrontendSetup()
#else
#define HAL_BOARD_RF_FRONTEND_SETUP()
#endif
/* ----------- Cache Prefetch control ---------- */
#define PREFETCH_ENABLE() st( FCTL = 0x08; )
#define PREFETCH_DISABLE() st( FCTL = 0x04; )
/* ----------- Board Initialization ---------- */
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_BOARD_INIT() \
{ \
uint16 i; \
\
SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \
while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \
asm("NOP"); /* chip bug workaround */ \
for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \
CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \
SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \
\
/* Turn on cache prefetch mode */ \
PREFETCH_ENABLE(); \
\
HAL_TURN_OFF_LED1(); \
LED1_DDR |= LED1_BV; \
HAL_TURN_OFF_LED2(); \
LED2_DDR |= LED2_BV; \
HAL_TURN_OFF_LED3(); \
LED3_DDR |= LED3_BV; \
\
/* configure tristates */ \
P0INP |= PUSH2_BV; \
}
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_BOARD_INIT() \
{ \
uint16 i; \
\
SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \
while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \
asm("NOP"); /* chip bug workaround */ \
for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \
CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \
SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \
\
/* Turn on cache prefetch mode */ \
PREFETCH_ENABLE(); \
\
/* set direction for GPIO outputs */ \
LED1_DDR |= LED1_BV; \
\
/* Set PA/LNA HGM control P0_7 */ \
P0DIR |= BV(7); \
\
/* configure tristates */ \
P0INP |= PUSH2_BV; \
\
/* setup RF frontend if necessary */ \
HAL_BOARD_RF_FRONTEND_SETUP(); \
}
#endif
/* ----------- Debounce ---------- */
#define HAL_DEBOUNCE(expr) { int i; for (i=0; i<500; i++) { if (!(expr)) i = 0; } }
/* ----------- Push Buttons ---------- */
#define HAL_PUSH_BUTTON1() (PUSH1_POLARITY (PUSH1_SBIT))
#define HAL_PUSH_BUTTON2() (PUSH2_POLARITY (PUSH2_SBIT))
#define HAL_PUSH_BUTTON3() (0)
#define HAL_PUSH_BUTTON4() (0)
#define HAL_PUSH_BUTTON5() (0)
#define HAL_PUSH_BUTTON6() (0)
/* ----------- LED's ---------- */
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); )
#define HAL_TURN_OFF_LED2() st( LED2_SBIT = LED2_POLARITY (0); )
#define HAL_TURN_OFF_LED3() st( LED3_SBIT = LED3_POLARITY (0); )
#define HAL_TURN_OFF_LED4() HAL_TURN_OFF_LED1()
#define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); )
#define HAL_TURN_ON_LED2() st( LED2_SBIT = LED2_POLARITY (1); )
#define HAL_TURN_ON_LED3() st( LED3_SBIT = LED3_POLARITY (1); )
#define HAL_TURN_ON_LED4() HAL_TURN_ON_LED1()
#define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} )
#define HAL_TOGGLE_LED2() st( if (LED2_SBIT) { LED2_SBIT = 0; } else { LED2_SBIT = 1;} )
#define HAL_TOGGLE_LED3() st( if (LED3_SBIT) { LED3_SBIT = 0; } else { LED3_SBIT = 1;} )
#define HAL_TOGGLE_LED4() HAL_TOGGLE_LED1()
#define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT))
#define HAL_STATE_LED2() (LED2_POLARITY (LED2_SBIT))
#define HAL_STATE_LED3() (LED3_POLARITY (LED3_SBIT))
#define HAL_STATE_LED4() HAL_STATE_LED1()
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); )
#define HAL_TURN_OFF_LED2() HAL_TURN_OFF_LED1()
#define HAL_TURN_OFF_LED3() HAL_TURN_OFF_LED1()
#define HAL_TURN_OFF_LED4() HAL_TURN_OFF_LED1()
#define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); )
#define HAL_TURN_ON_LED2() HAL_TURN_ON_LED1()
#define HAL_TURN_ON_LED3() HAL_TURN_ON_LED1()
#define HAL_TURN_ON_LED4() HAL_TURN_ON_LED1()
#define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} )
#define HAL_TOGGLE_LED2() HAL_TOGGLE_LED1()
#define HAL_TOGGLE_LED3() HAL_TOGGLE_LED1()
#define HAL_TOGGLE_LED4() HAL_TOGGLE_LED1()
#define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT))
#define HAL_STATE_LED2() HAL_STATE_LED1()
#define HAL_STATE_LED3() HAL_STATE_LED1()
#define HAL_STATE_LED4() HAL_STATE_LED1()
#endif
/* ----------- XNV ---------- */
#define XNV_SPI_BEGIN() st(P1_3 = 0;)
#define XNV_SPI_TX(x) st(U1CSR &= ~0x02; U1DBUF = (x);)
#define XNV_SPI_RX() U1DBUF
#define XNV_SPI_WAIT_RXRDY() st(while (!(U1CSR & 0x02));)
#define XNV_SPI_END() st(P1_3 = 1;)
// The TI reference design uses UART1 Alt. 2 in SPI mode.
#define XNV_SPI_INIT() \
st( \
/* Mode select UART1 SPI Mode as master. */\
U1CSR = 0; \
\
/* Setup for 115200 baud. */\
U1GCR = 11; \
U1BAUD = 216; \
\
/* Set bit order to MSB */\
U1GCR |= BV(5); \
\
/* Set UART1 I/O to alternate 2 location on P1 pins. */\
PERCFG |= 0x02; /* U1CFG */\
\
/* Select peripheral function on I/O pins but SS is left as GPIO for separate control. */\
P1SEL |= 0xE0; /* SELP1_[7:4] */\
/* P1.1,2,3: reset, LCD CS, XNV CS. */\
P1SEL &= ~0x0E; \
P1 |= 0x0E; \
P1_1 = 0; \
P1DIR |= 0x0E; \
\
/* Give UART1 priority over Timer3. */\
P2SEL &= ~0x20; /* PRI2P1 */\
\
/* When SPI config is complete, enable it. */\
U1CSR |= 0x40; \
/* Release XNV reset. */\
P1_1 = 1; \
)
/* ----------- Minimum safe bus voltage ---------- */
// Vdd/3 / Internal Reference X ENOB --> (Vdd / 3) / 1.15 X 127
#define VDD_2_0 74 // 2.0 V required to safely read/write internal flash.
#define VDD_2_7 100 // 2.7 V required for the Numonyx device.
#define VDD_MIN_RUN VDD_2_0
#define VDD_MIN_NV (VDD_2_0+4) // 5% margin over minimum to survive a page erase and compaction.
#define VDD_MIN_XNV (VDD_2_7+5) // 5% margin over minimum to survive a page erase and compaction.
/* ------------------------------------------------------------------------------------------------
* Driver Configuration
* ------------------------------------------------------------------------------------------------
*/
/* Set to TRUE enable H/W TIMER usage, FALSE disable it */
#ifndef HAL_TIMER
#define HAL_TIMER FALSE
#endif
/* Set to TRUE enable ADC usage, FALSE disable it */
#ifndef HAL_ADC
#define HAL_ADC TRUE
#endif
/* Set to TRUE enable DMA usage, FALSE disable it */
#ifndef HAL_DMA
#define HAL_DMA TRUE
#endif
/* Set to TRUE enable Flash access, FALSE disable it */
#ifndef HAL_FLASH
#define HAL_FLASH TRUE
#endif
/* Set to TRUE enable AES usage, FALSE disable it */
#ifndef HAL_AES
#define HAL_AES TRUE
#endif
#ifndef HAL_AES_DMA
#define HAL_AES_DMA TRUE
#endif
/* Set to TRUE enable LCD usage, FALSE disable it */
#ifndef HAL_LCD
#define HAL_LCD FALSE
#endif
/* Set to TRUE enable LED usage, FALSE disable it */
#ifndef HAL_LED
#define HAL_LED TRUE
#endif
#if (!defined BLINK_LEDS) && (HAL_LED == TRUE)
#define BLINK_LEDS
#endif
/* Set to TRUE enable KEY usage, FALSE disable it */
#ifndef HAL_KEY
#define HAL_KEY FALSE
#endif
/* Set to TRUE enable UART usage, FALSE disable it */
#ifndef HAL_UART
#if (defined ZAPP_P1) || (defined ZAPP_P2) || (defined ZTOOL_P1) || (defined ZTOOL_P2)
#define HAL_UART TRUE
#else
#define HAL_UART FALSE
#endif
#endif
#if HAL_UART
#ifndef HAL_UART_DMA
#if HAL_DMA
#if (defined ZAPP_P2) || (defined ZTOOL_P2)
#define HAL_UART_DMA 2
#else
#define HAL_UART_DMA 1
#endif
#else
#define HAL_UART_DMA 0
#endif
#endif
#ifndef HAL_UART_ISR
#if HAL_UART_DMA // Default preference for DMA over ISR.
#define HAL_UART_ISR 0
#elif (defined ZAPP_P2) || (defined ZTOOL_P2)
#define HAL_UART_ISR 2
#else
#define HAL_UART_ISR 1
#endif
#endif
#if (HAL_UART_DMA && (HAL_UART_DMA == HAL_UART_ISR))
#error HAL_UART_DMA & HAL_UART_ISR must be different.
#endif
// Used to set P2 priority - USART0 over USART1 if both are defined.
#if ((HAL_UART_DMA == 1) || (HAL_UART_ISR == 1))
#define HAL_UART_PRIPO 0x00
#else
#define HAL_UART_PRIPO 0x40
#endif
#else
#define HAL_UART_DMA 0
#define HAL_UART_ISR 0
#endif
/* USB is not used for CC2530 configuration */
#define HAL_UART_USB 0
/* Support for SunplusAPP WSN Box */
// add by lijian 20120821 - 语音传感器修改为2,其他情况下修改为1
#undef HAL_UART_DMA
#define HAL_UART_DMA 1
/* IR Encode & Decode configuration */
#define HAL_IRENC TRUE
#define HAL_IRDEC FALSE
#endif
/*******************************************************************************************************
*/

View File

@@ -0,0 +1,167 @@
/**************************************************************************************************
Filename: hal_dma.c
Revised: $Date: 2010-07-21 16:20:44 -0700 (Wed, 21 Jul 2010) $
Revision: $Revision: 23090 $
Description: This file contains the interface to the DMA.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_defs.h"
#include "hal_dma.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
#include "hal_irgen.h"
#endif
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
#include "hal_spi.h"
#endif
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
halDMADesc_t dmaCh0;
halDMADesc_t dmaCh1234[4];
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
/*********************************************************************
* LOCAL FUNCTIONS
*/
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
void HalDmaInit( void )
{
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
HAL_DMA_SET_ADDR_DESC1234( dmaCh1234 );
#if (HAL_UART_DMA || \
((defined HAL_SPI) && (HAL_SPI == TRUE)) || \
((defined HAL_IRGEN) && (HAL_IRGEN == TRUE)))
DMAIE = 1;
#endif
}
#if (HAL_UART_DMA || \
((defined HAL_SPI) && (HAL_SPI == TRUE)) || \
((defined HAL_IRGEN) && (HAL_IRGEN == TRUE)))
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
HAL_ISR_FUNCTION( halDmaIsr, DMA_VECTOR )
{
extern void HalUARTIsrDMA(void);
HAL_ENTER_ISR();
DMAIF = 0;
#if HAL_UART_DMA
if (HAL_DMA_CHECK_IRQ(HAL_DMA_CH_TX))
{
HalUARTIsrDMA();
}
#endif // HAL_UART_DMA
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_RX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_RX );
HalSpiRxIsr();
}
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_TX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_TX );
HalSpiTxIsr();
}
#endif // (defined HAL_SPI) && (HAL_SPI == TRUE)
#if (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
if ( HAL_IRGEN == TRUE && HAL_DMA_CHECK_IRQ( HAL_IRGEN_DMA_CH ) )
{
HAL_DMA_CLEAR_IRQ( HAL_IRGEN_DMA_CH );
HalIrGenDmaIsr();
}
#endif // (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
#endif
#endif // #if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,302 @@
/**************************************************************************************************
Filename: hal_dma.h
Revised: $Date: 2011-05-31 11:57:28 -0700 (Tue, 31 May 2011) $
Revision: $Revision: 26163 $
Description: This file contains the interface to the DMA Service.
Copyright 2007-2011 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_DMA_H
#define HAL_DMA_H
#ifdef __cplusplus
extern "C"
{
#endif
/*********************************************************************
* INCLUDES
*/
#include "hal_board.h"
#include "hal_types.h"
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
#define HAL_DMA_SET_ADDR_DESC0( a ) \
st( \
DMA0CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA0CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_SET_ADDR_DESC1234( a ) \
st( \
DMA1CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA1CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_GET_DESC0() &dmaCh0
#define HAL_DMA_GET_DESC1234( a ) (dmaCh1234+((a)-1))
#define HAL_DMA_ARM_CH( ch ) DMAARM = (0x01 << (ch))
#define HAL_DMA_CH_ARMED( ch ) (DMAARM & (0x01 << (ch)))
#define HAL_DMA_ABORT_CH( ch ) DMAARM = (0x80 | (0x01 << (ch)))
#define HAL_DMA_MAN_TRIGGER( ch ) DMAREQ = (0x01 << (ch))
#define HAL_DMA_START_CH( ch ) HAL_DMA_MAN_TRIGGER( (ch) )
#define HAL_DMA_CLEAR_IRQ( ch ) DMAIRQ = ((0x01 << (ch)) ^ 0xFF)
#define HAL_DMA_CHECK_IRQ( ch ) (DMAIRQ & (0x01 << (ch)))
// Macro for quickly setting the source address of a DMA structure.
#define HAL_DMA_SET_SOURCE( pDesc, src ) \
st( \
pDesc->srcAddrH = (uint8)( (uint16)(src) >> 8 ); \
pDesc->srcAddrL = (uint8)( (uint16)(src) & 0xFF ); \
)
// Macro for quickly setting the destination address of a DMA structure.
#define HAL_DMA_SET_DEST( pDesc, dst ) \
st( \
pDesc->dstAddrH = (uint8)( (uint16)(dst) >> 8 ); \
pDesc->dstAddrL = (uint8)( (uint16)(dst) & 0xFF ); \
)
// Macro for quickly setting the number of bytes to be transferred by the DMA,
// max length is 0x1FFF.
#define HAL_DMA_SET_LEN( pDesc, len ) \
st( \
pDesc->xferLenL = (uint8)( (uint16)(len) & 0xFF); \
pDesc->xferLenV &= ~HAL_DMA_LEN_H; \
pDesc->xferLenV |= (uint8)((uint16)(len) >> 8); \
)
#define HAL_DMA_GET_LEN( pDesc ) \
(((uint16)(pDesc->xferLenV & HAL_DMA_LEN_H) << 8) | pDesc->xferLenL)
#define HAL_DMA_SET_VLEN( pDesc, vMode ) \
st( \
pDesc->xferLenV &= ~HAL_DMA_LEN_V; \
pDesc->xferLenV |= (vMode << 5); \
)
#define HAL_DMA_SET_WORD_SIZE( pDesc, xSz ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_WORD_SIZE; \
pDesc->ctrlA |= (xSz << 7); \
)
#define HAL_DMA_SET_TRIG_MODE( pDesc, tMode ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_MODE; \
pDesc->ctrlA |= (tMode << 5); \
)
#define HAL_DMA_GET_TRIG_MODE( pDesc ) ((pDesc->ctrlA >> 5) & 0x3)
#define HAL_DMA_SET_TRIG_SRC( pDesc, tSrc ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_SRC; \
pDesc->ctrlA |= tSrc; \
)
#define HAL_DMA_SET_SRC_INC( pDesc, srcInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_SRC_INC; \
pDesc->ctrlB |= (srcInc << 6); \
)
#define HAL_DMA_SET_DST_INC( pDesc, dstInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_DST_INC; \
pDesc->ctrlB |= (dstInc << 4); \
)
#define HAL_DMA_SET_IRQ( pDesc, enable ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_IRQ_MASK; \
pDesc->ctrlB |= (enable << 3); \
)
#define HAL_DMA_SET_M8( pDesc, m8 ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_M8; \
pDesc->ctrlB |= (m8 << 2); \
)
#define HAL_DMA_SET_PRIORITY( pDesc, pri ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_PRIORITY; \
pDesc->ctrlB |= pri; \
)
/*********************************************************************
* CONSTANTS
*/
// Use LEN for transfer count
#define HAL_DMA_VLEN_USE_LEN 0x00
// Transfer the first byte + the number of bytes indicated by the first byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST 0x01
// Transfer the number of bytes indicated by the first byte (starting with the first byte)
#define HAL_DMA_VLEN_VALOFFIRST 0x02
// Transfer the first byte + the number of bytes indicated by the first byte + 1 more byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_1 0x03
// Transfer the first byte + the number of bytes indicated by the first byte + 2 more bytes
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_2 0x04
#define HAL_DMA_WORDSIZE_BYTE 0x00 /* Transfer a byte at a time. */
#define HAL_DMA_WORDSIZE_WORD 0x01 /* Transfer a 16-bit word at a time. */
#define HAL_DMA_TMODE_SINGLE 0x00 /* Transfer a single byte/word after each DMA trigger. */
#define HAL_DMA_TMODE_BLOCK 0x01 /* Transfer block of data (length len) after each DMA trigger. */
#define HAL_DMA_TMODE_SINGLE_REPEATED 0x02 /* Transfer single byte/word (after len transfers, rearm DMA). */
#define HAL_DMA_TMODE_BLOCK_REPEATED 0x03 /* Transfer block of data (after len transfers, rearm DMA). */
#define HAL_DMA_TRIG_NONE 0 /* No trigger, setting DMAREQ.DMAREQx bit starts transfer. */
#define HAL_DMA_TRIG_PREV 1 /* DMA channel is triggered by completion of previous channel. */
#define HAL_DMA_TRIG_T1_CH0 2 /* Timer 1, compare, channel 0. */
#define HAL_DMA_TRIG_T1_CH1 3 /* Timer 1, compare, channel 1. */
#define HAL_DMA_TRIG_T1_CH2 4 /* Timer 1, compare, channel 2. */
#define HAL_DMA_TRIG_T2_COMP 5 /* Timer 2, compare. */
#define HAL_DMA_TRIG_T2_OVFL 6 /* Timer 2, overflow. */
#define HAL_DMA_TRIG_T3_CH0 7 /* Timer 3, compare, channel 0. */
#define HAL_DMA_TRIG_T3_CH1 8 /* Timer 3, compare, channel 1. */
#define HAL_DMA_TRIG_T4_CH0 9 /* Timer 4, compare, channel 0. */
#define HAL_DMA_TRIG_T4_CH1 10 /* Timer 4, compare, channel 1. */
#define HAL_DMA_TRIG_ST 11 /* Sleep Timer compare. */
#define HAL_DMA_TRIG_IOC_0 12 /* Port 0 I/O pin input transition. */
#define HAL_DMA_TRIG_IOC_1 13 /* Port 1 I/O pin input transition. */
#define HAL_DMA_TRIG_URX0 14 /* USART0 RX complete. */
#define HAL_DMA_TRIG_UTX0 15 /* USART0 TX complete. */
#define HAL_DMA_TRIG_URX1 16 /* USART1 RX complete. */
#define HAL_DMA_TRIG_UTX1 17 /* USART1 TX complete. */
#define HAL_DMA_TRIG_FLASH 18 /* Flash data write complete. */
#define HAL_DMA_TRIG_RADIO 19 /* RF packet byte received/transmit. */
#define HAL_DMA_TRIG_ADC_CHALL 20 /* ADC end of a conversion in a sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH0 21 /* ADC end of conversion channel 0 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH1 22 /* ADC end of conversion channel 1 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH2 23 /* ADC end of conversion channel 2 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH3 24 /* ADC end of conversion channel 3 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH4 25 /* ADC end of conversion channel 4 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH5 26 /* ADC end of conversion channel 5 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH6 27 /* ADC end of conversion channel 6 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH7 28 /* ADC end of conversion channel 7 in sequence, sample ready. */
#define HAL_DMA_TRIG_ENC_DW 29 /* AES encryption processor requests download input data. */
#define HAL_DMA_TRIG_ENC_UP 30 /* AES encryption processor requests upload output data. */
#define HAL_DMA_SRCINC_0 0x00 /* Increment source pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_1 0x01 /* Increment source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_2 0x02 /* Increment source pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_M1 0x03 /* Decrement source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_0 0x00 /* Increment destination pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_1 0x01 /* Increment destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_2 0x02 /* Increment destination pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_M1 0x03 /* Decrement destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_IRQMASK_DISABLE 0x00 /* Disable interrupt generation. */
#define HAL_DMA_IRQMASK_ENABLE 0x01 /* Enable interrupt generation upon DMA channel done. */
#define HAL_DMA_M8_USE_8_BITS 0x00 /* Use all 8 bits for transfer count. */
#define HAL_DMA_M8_USE_7_BITS 0x01 /* Use 7 LSB for transfer count. */
#define HAL_DMA_PRI_LOW 0x00 /* Low, CPU has priority. */
#define HAL_DMA_PRI_GUARANTEED 0x01 /* Guaranteed, DMA at least every second try. */
#define HAL_DMA_PRI_HIGH 0x02 /* High, DMA has priority. */
#define HAL_DMA_PRI_ABSOLUTE 0x03 /* Highest, DMA has priority. Reserved for DMA port access.. */
#define HAL_DMA_MAX_ARM_CLOCKS 45 // Maximum number of clocks required if arming all 5 at once.
/*********************************************************************
* TYPEDEFS
*/
// Bit fields of the 'lenModeH'
#define HAL_DMA_LEN_V 0xE0
#define HAL_DMA_LEN_H 0x1F
// Bit fields of the 'ctrlA'
#define HAL_DMA_WORD_SIZE 0x80
#define HAL_DMA_TRIG_MODE 0x60
#define HAL_DMA_TRIG_SRC 0x1F
// Bit fields of the 'ctrlB'
#define HAL_DMA_SRC_INC 0xC0
#define HAL_DMA_DST_INC 0x30
#define HAL_DMA_IRQ_MASK 0x08
#define HAL_DMA_M8 0x04
#define HAL_DMA_PRIORITY 0x03
typedef struct {
uint8 srcAddrH;
uint8 srcAddrL;
uint8 dstAddrH;
uint8 dstAddrL;
uint8 xferLenV;
uint8 xferLenL;
uint8 ctrlA;
uint8 ctrlB;
} halDMADesc_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
extern halDMADesc_t dmaCh0;
extern halDMADesc_t dmaCh1234[4];
/*********************************************************************
* FUNCTIONS - API
*/
void HalDmaInit( void );
#endif // #if (defined HAL_DMA) && (HAL_DMA == TRUE)
#ifdef __cplusplus
}
#endif
#endif // #ifndef HAL_DMA_H
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,171 @@
/**************************************************************************************************
Filename: hal_flash.c
Revised: $Date: 2010-10-07 02:19:52 -0700 (Thu, 07 Oct 2010) $
Revision: $Revision: 24049 $
Description: This file contains the interface to the H/W Flash driver.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* @fn HalFlashRead
*
* @brief This function reads 'cnt' bytes from the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number.
* @param offset - A valid offset into the page.
* @param buf - A valid buffer space at least as big as the 'cnt' parameter.
* @param cnt - A valid number of bytes to read.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashRead(uint8 pg, uint16 offset, uint8 *buf, uint16 cnt)
{
// Calculate the offset into the containing flash bank as it gets mapped into XDATA.
uint8 *pData = (uint8 *)(offset + HAL_FLASH_PAGE_MAP) +
((pg % HAL_FLASH_PAGE_PER_BANK) * HAL_FLASH_PAGE_SIZE);
uint8 memctr = MEMCTR; // Save to restore.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
halIntState_t is;
#endif
pg /= HAL_FLASH_PAGE_PER_BANK; // Calculate the flash bank from the flash page.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_ENTER_CRITICAL_SECTION(is);
#endif
// Calculate and map the containing flash bank into XDATA.
MEMCTR = (MEMCTR & 0xF8) | pg;
while (cnt--)
{
*buf++ = *pData++;
}
MEMCTR = memctr;
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_EXIT_CRITICAL_SECTION(is);
#endif
}
/**************************************************************************************************
* @fn HalFlashWrite
*
* @brief This function writes 'cnt' bytes to the internal flash.
*
* input parameters
*
* @param addr - Valid HAL flash write address: actual addr / 4 and quad-aligned.
* @param buf - Valid buffer space at least as big as 'cnt' X 4.
* @param cnt - Number of 4-byte blocks to write.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashWrite(uint16 addr, uint8 *buf, uint16 cnt)
{
#if (defined HAL_DMA) && (HAL_DMA == TRUE)
halDMADesc_t *ch = HAL_NV_DMA_GET_DESC();
HAL_DMA_SET_SOURCE(ch, buf);
HAL_DMA_SET_DEST(ch, &FWDATA);
HAL_DMA_SET_VLEN(ch, HAL_DMA_VLEN_USE_LEN);
HAL_DMA_SET_LEN(ch, (cnt * HAL_FLASH_WORD_SIZE));
HAL_DMA_SET_WORD_SIZE(ch, HAL_DMA_WORDSIZE_BYTE);
HAL_DMA_SET_TRIG_MODE(ch, HAL_DMA_TMODE_SINGLE);
HAL_DMA_SET_TRIG_SRC(ch, HAL_DMA_TRIG_FLASH);
HAL_DMA_SET_SRC_INC(ch, HAL_DMA_SRCINC_1);
HAL_DMA_SET_DST_INC(ch, HAL_DMA_DSTINC_0);
// The DMA is to be polled and shall not issue an IRQ upon completion.
HAL_DMA_SET_IRQ(ch, HAL_DMA_IRQMASK_DISABLE);
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS);
HAL_DMA_SET_PRIORITY(ch, HAL_DMA_PRI_HIGH);
HAL_DMA_CLEAR_IRQ(HAL_NV_DMA_CH);
HAL_DMA_ARM_CH(HAL_NV_DMA_CH);
FADDRL = (uint8)addr;
FADDRH = (uint8)(addr >> 8);
FCTL |= 0x02; // Trigger the DMA writes.
while (FCTL & 0x80); // Wait until writing is done.
#endif
}
/**************************************************************************************************
* @fn HalFlashErase
*
* @brief This function erases the specified page of the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number to erase.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashErase(uint8 pg)
{
FADDRH = pg * (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE / 256);
FCTL |= 0x01;
}
/**************************************************************************************************
*/

View File

@@ -0,0 +1,258 @@
#include "hal_io.h"
#include "OSAL.h"
#include <string.h>
static struct {
uint8 ioIntTskId;
uint8 intInUse[MAX_IOGROUP + 1];
uint8 endPointMap[MAX_IOPORT + 1];
void *endPointArgMap[MAX_IOPORT + 1];
} ioIntResMap;
void HalIOInit(uint8 taskId)
{
memset(&ioIntResMap, 0, sizeof(ioIntResMap));
ioIntResMap.ioIntTskId = taskId;
}
/***********************************************************
** 函数名称: HalIOSetInput
** 实现功能: 设置端口为普通输入IO
** 入口参数: group:Port;
** bit:Bit;
** pull:(Pull_None:无上下拉; Pull_Up:上拉; Pull_Down:下拉;);
** 返回结果: IOInt_None
** 注意事项: CC2530的通用IO上下拉电阻是对整个端口的设置
** 不能实现将同一端口的不同位配置为上下拉不同
***********************************************************/
void HalIOSetInput(uint8 group, uint8 bit, PullSet_t pull)
{
switch(group)
{
case 0:
//设置为通用输入IO
CLRBIT(P0DIR, bit);
CLRBIT(P0SEL, bit);
//设置内部上下拉电阻状态
if(Pull_None == pull)
SETBIT(P0INP, bit); //P0INP[7-0]:(0:上下拉有效; 1:无效;)
else if(Pull_Up == pull)
{
CLRBIT(P0INP, bit); //P0INP[7-0]:(0:上下拉有效; 1:无效;)
CLRBIT(P2INP, 5); //P2INP[5 ]:(0:Port0 上拉; 1:Port0 下拉;)
}
else if(Pull_Down == pull)
{
CLRBIT(P0INP, bit); //P0INP[7-0]:(0:上下拉有效; 1:无效;)
SETBIT(P2INP, 5); //P2INP[5 ]:(0:Port0 上拉; 1:Port0 下拉;)
}
break;
case 1:
//设置为通用输入IO
CLRBIT(P1DIR, bit);
CLRBIT(P1SEL, bit);
//设置内部上下拉电阻状态
if(Pull_None == pull)
SETBIT(P1INP, bit); //P1INP[7-2]:(0:上下拉有效; 1:无效;) P[1-0] 写无效读为0.
else if(Pull_Up == pull)
{
CLRBIT(P1INP, bit); //P1INP[7-2]:(0:上下拉有效; 1:无效;) P[1-0] 写无效读为0.
CLRBIT(P2INP, 6); //P2INP[6 ]:(0:Port1 上拉; 1:Port1 下拉;)
}
else if(Pull_Down == pull)
{
CLRBIT(P1INP, bit); //P1INP[7-2]:(0:上下拉有效; 1:无效;) P[1-0] 写无效读为0.
SETBIT(P2INP, 6); //P2INP[6 ]:(0:Port1 上拉; 1:Port1 下拉;)
}
break;
case 2:
//设置为通用输入IO
CLRBIT(P2DIR, bit);
CLRBIT(P2SEL, bit);
//设置内部上下拉电阻状态
if(Pull_None == pull)
SETBIT(P2INP, bit); //P2INP[4-0]:(0:上下拉有效; 1:无效;)
else if(Pull_Up == pull)
{
CLRBIT(P2INP, bit); //P2INP[4-0]:(0:上下拉有效; 1:无效;)
CLRBIT(P2INP, 7); //P2INP[7 ]:(0:Port2 上拉; 1:Port2 下拉;)
}
else if(Pull_Down == pull)
{
CLRBIT(P2INP, bit); //P2INP[4-0]:(0:上下拉有效; 1:无效;)
SETBIT(P2INP, 7); //P2INP[7 ]:(0:Port2 上拉; 1:Port2 下拉;)
}
break;
default:
break;
}
}
void HalIOSetOutput(uint8 group, uint8 bit)
{
switch(group)
{
case 0: P0DIR |= (1 << bit); P0SEL &= ~(1 << bit); break;
case 1: P1DIR |= (1 << bit); P1SEL &= ~(1 << bit); break;
case 2: P2DIR |= (1 << bit); P2SEL &= ~(1 << bit); break;
}
}
uint8 HalIOGetLevel(uint8 group, uint8 bit)
{
switch(group)
{
case 0: return !!(P0 & (1 << bit));
case 1: return !!(P1 & (1 << bit));
case 2: return !!(P2 & (1 << bit));
}
return 0;
}
void HalIOSetLevel(uint8 group, uint8 bit, uint8 value)
{
switch(group)
{
case 0:
if(value)
SETBIT(P0, bit);
else
CLRBIT(P0, bit);
break;
case 1:
if(value)
SETBIT(P1, bit);
else
CLRBIT(P1, bit);
break;
case 2:
if(value)
SETBIT(P2, bit);
else
CLRBIT(P2, bit);
break;
}
}
/***********************************************************
** 函数名称: IOIntteruptSet
** 实现功能: 设置端口中断触发方式
** 入口参数: group:Port;
** bit:Bit;
** trigger:(IOInt_Rising:上升沿触发; IOInt_Falling:下降沿触发;)
** 返回结果: IOInt_None
** 注意事项: CC2530的通用IO中断触发方式是对整个端口的设置
** 只有P1口的高四位和第四位触发方式可以设置为不同
** P0端口和P2端口的所有端口触发方式以最后一次设置为准。
***********************************************************/
void HalIOIntSet(uint8 endPoint, uint8 group, uint8 bit, IntSel_t trigger, void *arg)
{
if(HAL_IOPORT(group, bit) > MAX_IOPORT)
return;
if(trigger == IOInt_None)
{
CLRBIT(ioIntResMap.intInUse[group], bit);
}
else
{
SETBIT(ioIntResMap.intInUse[group], bit);
ioIntResMap.endPointMap[HAL_IOPORT(group, bit)] = endPoint;
ioIntResMap.endPointArgMap[HAL_IOPORT(group, bit)] = arg;
}
switch(group)
{
case 0:
if(trigger == IOInt_None)
CLRBIT(P0IEN, bit);
else
{
SETBIT(P0IEN, bit);
if(trigger == IOInt_Rising)
CLRBIT(PICTL, 0);
else
SETBIT(PICTL, 0);
}
P0IFG = 0x00; //清除P0相应位中断标志
P0IF = 0; //清除P0端口总中断标志
//SETBIT(IEN1, 5); //P0总中断允许
CLRBIT(IEN1, 5); //P0总中断禁止
break;
case 1:
if(trigger == IOInt_None)
CLRBIT(P1IEN, bit);
else
{
uint8 ctlBit = (bit <= 3) ? 1 : 2;
SETBIT(P1IEN, bit);
if(trigger == IOInt_Rising)
CLRBIT(PICTL, ctlBit);
else
SETBIT(PICTL, ctlBit);
}
P1IFG = 0X00; //清除P0相应位中断标志
P1IF = 0; //清除P0端口总中断标志
//SETBIT(IEN2, 4); //P1总中断允许
CLRBIT(IEN2, 4); //P1总中断禁止
break;
case 2:
if(trigger == IOInt_None)
CLRBIT(P2IEN, bit);
else
{
SETBIT(P2IEN, bit);
if(trigger == IOInt_Rising)
CLRBIT(PICTL, 3);
else
SETBIT(PICTL, 3);
}
P2IFG = 0X00; //清除P0相应位中断标志
P2IF = 0; //清除P0端口总中断标志
//SETBIT(IEN2, 1); //P2总中断允许
CLRBIT(IEN2, 1); //P2总中断禁止
break;
default :
break;
}
}
void HalIOPortPoll()
{
OSALIOIntData_t* IOIntData;
uint8 idx;
uint8 flag = ioIntResMap.intInUse[0] & P0IFG;
for(idx = 0; flag && (idx < 8); idx++)
{
if(BV(idx) & flag)
{
IOIntData = (OSALIOIntData_t *)osal_msg_allocate(sizeof(OSALIOIntData_t));
IOIntData->hdr.event = IOPORT_INT_EVENT;
IOIntData->endPoint = ioIntResMap.endPointMap[HAL_IOPORT(0, idx)];
IOIntData->arg = ioIntResMap.endPointArgMap[HAL_IOPORT(0, idx)];
osal_msg_send(ioIntResMap.ioIntTskId, (uint8*)(IOIntData));
}
}
flag = ioIntResMap.intInUse[1] & P1IFG;
for(idx = 0; flag && (idx < 8); idx++)
{
if(BV(idx) & flag)
{
IOIntData = (OSALIOIntData_t *)osal_msg_allocate(sizeof(OSALIOIntData_t));
IOIntData->hdr.event = IOPORT_INT_EVENT;
IOIntData->endPoint = ioIntResMap.endPointMap[HAL_IOPORT(1, idx)];
IOIntData->arg = ioIntResMap.endPointArgMap[HAL_IOPORT(1, idx)];
osal_msg_send(ioIntResMap.ioIntTskId, (uint8*)(IOIntData));
}
}
flag = ioIntResMap.intInUse[2] & P2IFG;
for(idx = 0; flag && (idx < 5); idx++)
{
if(BV(idx) & flag)
{
IOIntData = (OSALIOIntData_t *)osal_msg_allocate(sizeof(OSALIOIntData_t));
IOIntData->hdr.event = IOPORT_INT_EVENT;
IOIntData->endPoint = ioIntResMap.endPointMap[HAL_IOPORT(2, idx)];
IOIntData->arg = ioIntResMap.endPointArgMap[HAL_IOPORT(2, idx)];
osal_msg_send(ioIntResMap.ioIntTskId, (uint8*)(IOIntData));
}
}
// 中断事件处理完毕,清除硬件中断标志位。
P0IFG = 0;
P1IFG = 0;
P2IFG = 0;
}

View File

@@ -0,0 +1,235 @@
/***********************************************************
** FileName: IRDecode.c
** Introductions: IR Remote decode for MCU of CC2530
** Last Modify time: 2013.05.03
** Update: 基本解码测试
** Author: GuoZhenjiang<zhenjiang.guo@sunplusapp.com>
** Modify:
** 2013.05.03 lijian Change File Name to hal_irdec.c
***********************************************************/
#include <hal_board.h>
#include "hal_irdec.h"
#include <string.h>
#if defined(HAL_IRDEC) && (HAL_IRDEC == TRUE)
static struct {
uint8 IRIntTskId;
uint8 IRIntEp;
OSALIRDecData_t IRCodeTab;
} IRDecodeRes;
volatile uint8 IROverTimeAdd_En=FALSE, IROverTimeOvf_flg=FALSE;
volatile uint16 IROverTimeAdd_cnt=0;
volatile IRDecodeSta_t IRDeodeSta = WaitForGuideTrig1;
static uint8 cnt_Byte, cnt_bit; // 用于控制解码过程的基本变量
/***********************************************************
** 函数名称: IRDecodeT1Init
** 实现功能: 中断法进行红外解码初始化工作
** 入口参数: None
** 返回结果: None
***********************************************************/
void IRDecodeT1Init(uint8 taskid, uint8 ep)
{
// 保存任务号和端点号
IRDecodeRes.IRIntTskId = taskid;
IRDecodeRes.IRIntEp = ep;
// 初始化Timer1
P1SEL |= 0x04; // 配置P1.2为Timer1的外设功能引脚
P1DIR &= ~0x04; // 输入捕获引脚必须设置为输入
PERCFG |= 0x40; // Timer1占用第2引脚位置(通道0为P1.2)
P2SEL |= 0x04; // 当USART0和Timer1分配了相同引脚Timer1优先
// 定时器1初始化
T1CTL = (uint8)Tdiv_32 | (uint8)Tmod_stop; // 1MHz,暂停运行
CLR_T1CNT; // 清零定时器1
// Timer1通道0上升沿输入捕获设置
T1CCTL0 = 0x01; // 上升沿捕获,通道0输入捕获中断未使能,查询中断标志即可
T1CCTL0 |= 0x40; // T1CCTL0.IM 定时器1通道0中断开关
T1STAT = 0;
IEN1 |= 0x02; // IEN1.T1IE 定时器1中断总开关
EA = 1; // IEN0.EA 全局总中断开关
// 初始化Time4
P2SEL |= 0x10; // 定时器4优先级高于定时器1
T4CTL |= 0xEC; // 128分频,清空计数值,允许溢出中断,自由运行
T4CTL |= 0x10; // 启动定时器
IEN1 |= 0x10; // 打开定时器4总中断
}
/***********************************************************
** 函数名称: Timer1_ISR
** 实现功能: Timer1 中断处理函数,利用Timer1通道0输入捕获功能实现红外解码
** 入口参数: None
** 返回结果: None
***********************************************************/
HAL_ISR_FUNC_DECLARATION(Timer1_ISR, T1_VECTOR);
HAL_ISR_FUNCTION(Timer1_ISR, T1_VECTOR)
{
#define CLR_T1CH0_IF T1STAT &= 0xFE
#define CLR_T1CH1_IF T1STAT &= 0xFD
#define CLR_T1OVF_IF T1STAT &= 0xDF
#define CLR_T1IF IRCON &= 0xFD
static uint8 IRdata[15]; // 用于存储解析的红外数据
static uint16 tCapture = 0; // 用于存储判断每个捕获周期
// 红外解码中捕获到定时器1通道0上升沿
if(T1STAT & 0x01)
{
switch(IRDeodeSta)
{
case WaitForGuideTrig1:
IRDeodeSta = WaitForGuideTrig2;
CLR_T1CNT; // 清零定时器1
T1CTL = (uint8)Tdiv_32 | (uint8)Tmod_free; // 1MHz,自由计数模式
break;
case WaitForGuideTrig2:
tCapture = T1CC0L; // 获取当前一个周期值
tCapture |= (uint16)T1CC0H << 8;
CLR_T1CNT; // 清零定时器1
T1CTL = (uint8)Tdiv_32 | (uint8)Tmod_free; // 1MHz,自由计数模式
// 如果是引导码4.5ms引导码或者9ms引导码
if(((tCapture > T_IR_GUIDE9_MIN) && (tCapture < T_IR_GUIDE9_MAX)) || ((tCapture > T_IR_GUIDE4_MIN) && (tCapture < T_IR_GUIDE4_MAX)))
{
IRDeodeSta = Decoding;
// 准备解码工作
cnt_bit = 0;
cnt_Byte = 0;
}
else
IRDeodeSta = WaitForGuideTrig1;
IROverTimeAdd_cnt = 0;
break;
case Decoding:
tCapture = T1CC0L; // 获取当前一个周期值
tCapture |= (uint16)T1CC0H << 8;
CLR_T1CNT; // 清零定时器1
T1CTL = (uint8)Tdiv_32 | (uint8)Tmod_free; // 1MHz,自由计数模式
// 接收到位0?
if((tCapture > T_IR_0_MIN) && (tCapture < T_IR_0_MAX))
{
IRDeodeSta = Decoding;
IROverTimeAdd_cnt = 0;
IRdata[cnt_Byte] &= ~(0x80 >> cnt_bit); // 保存当前位0
cnt_bit++;
if(cnt_bit >= 8) // 接收完毕一个字节
{
IRDecodeRes.IRCodeTab.irCode[cnt_Byte] = IRdata[cnt_Byte];
cnt_bit=0;
cnt_Byte++;
if(cnt_Byte >= 15) // 超出最大接收队列长度
{
IRDeodeSta = Decode_BufOverflow;
goto OneIRpkgGot;
}
}
}
// 接收到位1?
else if((tCapture > T_IR_1_MIN) && (tCapture < T_IR_1_MAX))
{
IRDeodeSta = Decoding;
IROverTimeAdd_cnt = 0;
IRdata[cnt_Byte] |= 0x80 >> cnt_bit; // 保存当前位0
cnt_bit++;
if(cnt_bit >= 8) // 接收完毕一个字节
{
IRDecodeRes.IRCodeTab.irCode[cnt_Byte] = IRdata[cnt_Byte];
cnt_bit=0;
cnt_Byte++;
if(cnt_Byte >= 15) // 超出最大接收队列长度
{
IRDeodeSta = Decode_BufOverflow;
goto OneIRpkgGot;
}
}
}
// 没有超时,不是位0,不是位1,出错???
else
{
IRDeodeSta = Decode_OverUnknow;
goto OneIRpkgGot;
}
break;
default :
IRDeodeSta = WaitForGuideTrig1;
break;
}
OneIRpkgGot:
{
switch(IRDeodeSta) // 一次红外解码结束
{
// 处理 接收队列溢出导致解码结束
case Decode_BufOverflow:
// 处理 未知原因导致解码结束
case Decode_OverUnknow:
IROverTimeAdd_cnt = 0;
IRDecodeRes.IRCodeTab.irLen = cnt_Byte;
cnt_bit = 0;
cnt_Byte = 0;
OSALIRDecIntData_t* T1Ch0IntData;
T1Ch0IntData = (OSALIRDecIntData_t *)osal_msg_allocate(sizeof(OSALIRDecIntData_t));
T1Ch0IntData->hdr.event = IRDEC_INT_EVENT;
T1Ch0IntData->endPoint = IRDecodeRes.IRIntEp;
T1Ch0IntData->data = &IRDecodeRes.IRCodeTab;
osal_msg_send(IRDecodeRes.IRIntTskId, (uint8*)(T1Ch0IntData));
IRDeodeSta = WaitForGuideTrig1;
break;
default :
break;
}
}
CLR_T1CH0_IF; // 清除通道0输入捕获中断标志
}
CLR_T1IF; // 清除T1IF
}
/***********************************************************
** 函数名称: Timer4_ISR
** 实现功能: Timer4 中断处理函数,利用Timer1通道0输入捕获功能实现红外解码
** 入口参数: None
** 返回结果: None
***********************************************************/
HAL_ISR_FUNC_DECLARATION(Timer4_ISR, T4_VECTOR);
HAL_ISR_FUNCTION(Timer4_ISR, T4_VECTOR)
{
// (32MHz / 128) T = 4us; f = 250000Hz;
switch(IRDeodeSta)
{
// 等待第二次触发,检测引导码是否超时
case WaitForGuideTrig2:
IROverTimeAdd_cnt++;
if(IROverTimeAdd_cnt >= 16) // 约16ms内没有清零
{
IROverTimeAdd_cnt = 0;
IRDeodeSta = WaitForGuideTrig1;
}
break;
// 位0 位1 解码中,检测是否解码超时
case Decoding:
IROverTimeAdd_cnt++;
if(IROverTimeAdd_cnt >= 5) // 4ms内没有清零
{
IROverTimeAdd_cnt = 0;
IRDecodeRes.IRCodeTab.irLen = cnt_Byte;
cnt_bit = 0;
cnt_Byte = 0;
OSALIRDecIntData_t* T4OvfIntData;
T4OvfIntData = (OSALIRDecIntData_t *)osal_msg_allocate(sizeof(OSALIRDecIntData_t));
T4OvfIntData->hdr.event = IRDEC_INT_EVENT;
T4OvfIntData->endPoint = IRDecodeRes.IRIntEp;
T4OvfIntData->data = &IRDecodeRes.IRCodeTab;
osal_msg_send(IRDecodeRes.IRIntTskId, (uint8*)(T4OvfIntData));
IRDeodeSta = WaitForGuideTrig1;
}
break;
default :
IROverTimeAdd_cnt = 0;
break;
}
T4OVFIF = 0; // 清除定时器4溢出中断标志
T4IF = 0; // 清除定时器4总中断标志
}
#endif //#if defined(HAL_IRDEC) && (HAL_IRDEC == TRUE)

View File

@@ -0,0 +1,553 @@
/**************************************************************************************************
Filename: hal_key.c
Revised: $Date: 2010-09-15 19:02:45 -0700 (Wed, 15 Sep 2010) $
Revision: $Revision: 23815 $
Description: This file contains the interface to the HAL KEY Service.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
NOTE: If polling is used, the hal_driver task schedules the KeyRead()
to occur every 100ms. This should be long enough to naturally
debounce the keys. The KeyRead() function remembers the key
state of the previous poll and will only return a non-zero
value if the key state changes.
NOTE: If interrupts are used, the KeyRead() function is scheduled
25ms after the interrupt occurs by the ISR. This delay is used
for key debouncing. The ISR disables any further Key interrupt
until KeyRead() is executed. KeyRead() will re-enable Key
interrupts after executing. Unlike polling, when interrupts
are enabled, the previous key state is not remembered. This
means that KeyRead() will return the current state of the keys
(not a change in state of the keys).
NOTE: If interrupts are used, the KeyRead() fucntion is scheduled by
the ISR. Therefore, the joystick movements will only be detected
during a pushbutton interrupt caused by S1 or the center joystick
pushbutton.
NOTE: When a switch like S1 is pushed, the S1 signal goes from a normally
high state to a low state. This transition is typically clean. The
duration of the low state is around 200ms. When the signal returns
to the high state, there is a high likelihood of signal bounce, which
causes a unwanted interrupts. Normally, we would set the interrupt
edge to falling edge to generate an interrupt when S1 is pushed, but
because of the signal bounce, it is better to set the edge to rising
edge to generate an interrupt when S1 is released. The debounce logic
can then filter out the signal bounce. The result is that we typically
get only 1 interrupt per button push. This mechanism is not totally
foolproof because occasionally, signal bound occurs during the falling
edge as well. A similar mechanism is used to handle the joystick
pushbutton on the DB. For the EB, we do not have independent control
of the interrupt edge for the S1 and center joystick pushbutton. As
a result, only one or the other pushbuttons work reasonably well with
interrupts. The default is the make the S1 switch on the EB work more
reliably.
*********************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_board.h"
#include "hal_drivers.h"
#include "hal_adc.h"
#include "hal_key.h"
#include "osal.h"
#if (defined HAL_KEY) && (HAL_KEY == TRUE)
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_KEY_RISING_EDGE 0
#define HAL_KEY_FALLING_EDGE 1
#define HAL_KEY_DEBOUNCE_VALUE 25
/* CPU port interrupt */
#define HAL_KEY_CPU_PORT_0_IF P0IF
#define HAL_KEY_CPU_PORT_2_IF P2IF
/* SW_6 is at P0.1 */
#define HAL_KEY_SW_6_PORT P0
#define HAL_KEY_SW_6_BIT BV(1)
#define HAL_KEY_SW_6_SEL P0SEL
#define HAL_KEY_SW_6_DIR P0DIR
/* edge interrupt */
#define HAL_KEY_SW_6_EDGEBIT BV(0)
#define HAL_KEY_SW_6_EDGE HAL_KEY_FALLING_EDGE
/* SW_6 interrupts */
#define HAL_KEY_SW_6_IEN IEN1 /* CPU interrupt mask register */
#define HAL_KEY_SW_6_IENBIT BV(5) /* Mask bit for all of Port_0 */
#define HAL_KEY_SW_6_ICTL P0IEN /* Port Interrupt Control register */
#define HAL_KEY_SW_6_ICTLBIT BV(1) /* P0IEN - P0.1 enable/disable bit */
#define HAL_KEY_SW_6_PXIFG P0IFG /* Interrupt flag at source */
/* Joy stick move at P2.0 */
#define HAL_KEY_JOY_MOVE_PORT P2
#define HAL_KEY_JOY_MOVE_BIT BV(0)
#define HAL_KEY_JOY_MOVE_SEL P2SEL
#define HAL_KEY_JOY_MOVE_DIR P2DIR
/* edge interrupt */
#define HAL_KEY_JOY_MOVE_EDGEBIT BV(3)
#define HAL_KEY_JOY_MOVE_EDGE HAL_KEY_FALLING_EDGE
/* Joy move interrupts */
#define HAL_KEY_JOY_MOVE_IEN IEN2 /* CPU interrupt mask register */
#define HAL_KEY_JOY_MOVE_IENBIT BV(1) /* Mask bit for all of Port_2 */
#define HAL_KEY_JOY_MOVE_ICTL P2IEN /* Port Interrupt Control register */
#define HAL_KEY_JOY_MOVE_ICTLBIT BV(0) /* P2IENL - P2.0<->P2.3 enable/disable bit */
#define HAL_KEY_JOY_MOVE_PXIFG P2IFG /* Interrupt flag at source */
#define HAL_KEY_JOY_CHN HAL_ADC_CHANNEL_6
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
static uint8 halKeySavedKeys; /* used to store previous key state in polling mode */
static halKeyCBack_t pHalKeyProcessFunction;
static uint8 HalKeyConfigured;
bool Hal_KeyIntEnable; /* interrupt enable/disable flag */
/**************************************************************************************************
* FUNCTIONS - Local
**************************************************************************************************/
void halProcessKeyInterrupt(void);
uint8 halGetJoyKeyInput(void);
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/**************************************************************************************************
* @fn HalKeyInit
*
* @brief Initilize Key Service
*
* @param none
*
* @return None
**************************************************************************************************/
void HalKeyInit( void )
{
/* Initialize previous key to 0 */
halKeySavedKeys = 0;
HAL_KEY_SW_6_SEL &= ~(HAL_KEY_SW_6_BIT); /* Set pin function to GPIO */
HAL_KEY_SW_6_DIR &= ~(HAL_KEY_SW_6_BIT); /* Set pin direction to Input */
HAL_KEY_JOY_MOVE_SEL &= ~(HAL_KEY_JOY_MOVE_BIT); /* Set pin function to GPIO */
HAL_KEY_JOY_MOVE_DIR &= ~(HAL_KEY_JOY_MOVE_BIT); /* Set pin direction to Input */
/* Initialize callback function */
pHalKeyProcessFunction = NULL;
/* Start with key is not configured */
HalKeyConfigured = FALSE;
}
/**************************************************************************************************
* @fn HalKeyConfig
*
* @brief Configure the Key serivce
*
* @param interruptEnable - TRUE/FALSE, enable/disable interrupt
* cback - pointer to the CallBack function
*
* @return None
**************************************************************************************************/
void HalKeyConfig (bool interruptEnable, halKeyCBack_t cback)
{
/* Enable/Disable Interrupt or */
Hal_KeyIntEnable = interruptEnable;
/* Register the callback fucntion */
pHalKeyProcessFunction = cback;
/* Determine if interrupt is enable or not */
if (Hal_KeyIntEnable)
{
/* Rising/Falling edge configuratinn */
PICTL &= ~(HAL_KEY_SW_6_EDGEBIT); /* Clear the edge bit */
/* For falling edge, the bit must be set. */
#if (HAL_KEY_SW_6_EDGE == HAL_KEY_FALLING_EDGE)
PICTL |= HAL_KEY_SW_6_EDGEBIT;
#endif
/* Interrupt configuration:
* - Enable interrupt generation at the port
* - Enable CPU interrupt
* - Clear any pending interrupt
*/
HAL_KEY_SW_6_ICTL |= HAL_KEY_SW_6_ICTLBIT;
HAL_KEY_SW_6_IEN |= HAL_KEY_SW_6_IENBIT;
HAL_KEY_SW_6_PXIFG = ~(HAL_KEY_SW_6_BIT);
/* Rising/Falling edge configuratinn */
HAL_KEY_JOY_MOVE_ICTL &= ~(HAL_KEY_JOY_MOVE_EDGEBIT); /* Clear the edge bit */
/* For falling edge, the bit must be set. */
#if (HAL_KEY_JOY_MOVE_EDGE == HAL_KEY_FALLING_EDGE)
HAL_KEY_JOY_MOVE_ICTL |= HAL_KEY_JOY_MOVE_EDGEBIT;
#endif
/* Interrupt configuration:
* - Enable interrupt generation at the port
* - Enable CPU interrupt
* - Clear any pending interrupt
*/
HAL_KEY_JOY_MOVE_ICTL |= HAL_KEY_JOY_MOVE_ICTLBIT;
HAL_KEY_JOY_MOVE_IEN |= HAL_KEY_JOY_MOVE_IENBIT;
HAL_KEY_JOY_MOVE_PXIFG = ~(HAL_KEY_JOY_MOVE_BIT);
/* Do this only after the hal_key is configured - to work with sleep stuff */
if (HalKeyConfigured == TRUE)
{
osal_stop_timerEx(Hal_TaskID, HAL_KEY_EVENT); /* Cancel polling if active */
}
}
else /* Interrupts NOT enabled */
{
HAL_KEY_SW_6_ICTL &= ~(HAL_KEY_SW_6_ICTLBIT); /* don't generate interrupt */
HAL_KEY_SW_6_IEN &= ~(HAL_KEY_SW_6_IENBIT); /* Clear interrupt enable bit */
osal_set_event(Hal_TaskID, HAL_KEY_EVENT);
}
/* Key now is configured */
HalKeyConfigured = TRUE;
}
/**************************************************************************************************
* @fn HalKeyRead
*
* @brief Read the current value of a key
*
* @param None
*
* @return keys - current keys status
**************************************************************************************************/
uint8 HalKeyRead ( void )
{
uint8 keys = 0;
if (HAL_PUSH_BUTTON1())
{
keys |= HAL_KEY_SW_6;
}
if ((HAL_KEY_JOY_MOVE_PORT & HAL_KEY_JOY_MOVE_BIT)) /* Key is active low */
{
keys |= halGetJoyKeyInput();
}
return keys;
}
/**************************************************************************************************
* @fn HalKeyPoll
*
* @brief Called by hal_driver to poll the keys
*
* @param None
*
* @return None
**************************************************************************************************/
void HalKeyPoll (void)
{
uint8 keys = 0;
if ((HAL_KEY_JOY_MOVE_PORT & HAL_KEY_JOY_MOVE_BIT)) /* Key is active HIGH */
{
keys = halGetJoyKeyInput();
}
/* If interrupts are not enabled, previous key status and current key status
* are compared to find out if a key has changed status.
*/
if (!Hal_KeyIntEnable)
{
if (keys == halKeySavedKeys)
{
/* Exit - since no keys have changed */
return;
}
/* Store the current keys for comparation next time */
halKeySavedKeys = keys;
}
else
{
/* Key interrupt handled here */
}
if (HAL_PUSH_BUTTON1())
{
keys |= HAL_KEY_SW_6;
}
/* Invoke Callback if new keys were depressed */
if (keys && (pHalKeyProcessFunction))
{
(pHalKeyProcessFunction) (keys, HAL_KEY_STATE_NORMAL);
}
}
/**************************************************************************************************
* @fn halGetJoyKeyInput
*
* @brief Map the ADC value to its corresponding key.
*
* @param None
*
* @return keys - current joy key status
**************************************************************************************************/
uint8 halGetJoyKeyInput(void)
{
/* The joystick control is encoded as an analog voltage.
* Read the JOY_LEVEL analog value and map it to joy movement.
*/
uint8 adc;
uint8 ksave0 = 0;
uint8 ksave1;
/* Keep on reading the ADC until two consecutive key decisions are the same. */
do
{
ksave1 = ksave0; /* save previouse key reading */
adc = HalAdcRead (HAL_KEY_JOY_CHN, HAL_ADC_RESOLUTION_8);
if ((adc >= 2) && (adc <= 38))
{
ksave0 |= HAL_KEY_UP;
}
else if ((adc >= 74) && (adc <= 88))
{
ksave0 |= HAL_KEY_RIGHT;
}
else if ((adc >= 60) && (adc <= 73))
{
ksave0 |= HAL_KEY_LEFT;
}
else if ((adc >= 39) && (adc <= 59))
{
ksave0 |= HAL_KEY_DOWN;
}
else if ((adc >= 89) && (adc <= 100))
{
ksave0 |= HAL_KEY_CENTER;
}
} while (ksave0 != ksave1);
return ksave0;
}
/**************************************************************************************************
* @fn halProcessKeyInterrupt
*
* @brief Checks to see if it's a valid key interrupt, saves interrupt driven key states for
* processing by HalKeyRead(), and debounces keys by scheduling HalKeyRead() 25ms later.
*
* @param
*
* @return
**************************************************************************************************/
void halProcessKeyInterrupt (void)
{
bool valid=FALSE;
if (HAL_KEY_SW_6_PXIFG & HAL_KEY_SW_6_BIT) /* Interrupt Flag has been set */
{
HAL_KEY_SW_6_PXIFG = ~(HAL_KEY_SW_6_BIT); /* Clear Interrupt Flag */
valid = TRUE;
}
if (HAL_KEY_JOY_MOVE_PXIFG & HAL_KEY_JOY_MOVE_BIT) /* Interrupt Flag has been set */
{
HAL_KEY_JOY_MOVE_PXIFG = ~(HAL_KEY_JOY_MOVE_BIT); /* Clear Interrupt Flag */
valid = TRUE;
}
if (valid)
{
osal_start_timerEx (Hal_TaskID, HAL_KEY_EVENT, HAL_KEY_DEBOUNCE_VALUE);
}
}
/**************************************************************************************************
* @fn HalKeyEnterSleep
*
* @brief - Get called to enter sleep mode
*
* @param
*
* @return
**************************************************************************************************/
void HalKeyEnterSleep ( void )
{
}
/**************************************************************************************************
* @fn HalKeyExitSleep
*
* @brief - Get called when sleep is over
*
* @param
*
* @return - return saved keys
**************************************************************************************************/
uint8 HalKeyExitSleep ( void )
{
/* Wake up and read keys */
return ( HalKeyRead () );
}
/***************************************************************************************************
* INTERRUPT SERVICE ROUTINE
***************************************************************************************************/
/**************************************************************************************************
* @fn halKeyPort0Isr
*
* @brief Port0 ISR
*
* @param
*
* @return
**************************************************************************************************/
HAL_ISR_FUNCTION( halKeyPort0Isr, P0INT_VECTOR )
{
HAL_ENTER_ISR();
if (HAL_KEY_SW_6_PXIFG & HAL_KEY_SW_6_BIT)
{
halProcessKeyInterrupt();
}
/*
Clear the CPU interrupt flag for Port_0
PxIFG has to be cleared before PxIF
*/
HAL_KEY_SW_6_PXIFG = 0;
HAL_KEY_CPU_PORT_0_IF = 0;
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
/**************************************************************************************************
* @fn halKeyPort2Isr
*
* @brief Port2 ISR
*
* @param
*
* @return
**************************************************************************************************/
HAL_ISR_FUNCTION( halKeyPort2Isr, P2INT_VECTOR )
{
HAL_ENTER_ISR();
if (HAL_KEY_JOY_MOVE_PXIFG & HAL_KEY_JOY_MOVE_BIT)
{
halProcessKeyInterrupt();
}
/*
Clear the CPU interrupt flag for Port_2
PxIFG has to be cleared before PxIF
Notes: P2_1 and P2_2 are debug lines.
*/
HAL_KEY_JOY_MOVE_PXIFG = 0;
HAL_KEY_CPU_PORT_2_IF = 0;
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
#else
void HalKeyInit(void){}
void HalKeyConfig(bool interruptEnable, halKeyCBack_t cback){}
uint8 HalKeyRead(void){ return 0;}
void HalKeyPoll(void){}
#endif /* HAL_KEY */
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,763 @@
/**************************************************************************************************
Filename: hal_lcd.c
Revised: $Date: 2010-06-21 17:31:27 -0700 (Mon, 21 Jun 2010) $
Revision: $Revision: 22794 $
Description: This file contains the interface to the HAL LCD Service.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_types.h"
#include "hal_lcd.h"
#include "OSAL.h"
#include "OnBoard.h"
#include "hal_assert.h"
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#include "DebugTrace.h"
#endif
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/*
LCD pins
//control
P0.0 - LCD_MODE
P1.1 - LCD_FLASH_RESET
P1.2 - LCD_CS
//spi
P1.5 - CLK
P1.6 - MOSI
P1.7 - MISO
*/
/* LCD Control lines */
#define HAL_LCD_MODE_PORT 0
#define HAL_LCD_MODE_PIN 0
#define HAL_LCD_RESET_PORT 1
#define HAL_LCD_RESET_PIN 1
#define HAL_LCD_CS_PORT 1
#define HAL_LCD_CS_PIN 2
/* LCD SPI lines */
#define HAL_LCD_CLK_PORT 1
#define HAL_LCD_CLK_PIN 5
#define HAL_LCD_MOSI_PORT 1
#define HAL_LCD_MOSI_PIN 6
#define HAL_LCD_MISO_PORT 1
#define HAL_LCD_MISO_PIN 7
/* SPI settings */
#define HAL_SPI_CLOCK_POL_LO 0x00
#define HAL_SPI_CLOCK_PHA_0 0x00
#define HAL_SPI_TRANSFER_MSB_FIRST 0x20
/* LCD lines */
#define LCD_MAX_LINE_COUNT 3
#define LCD_MAX_LINE_LENGTH 16
#define LCD_MAX_BUF 25
/* Defines for HW LCD */
/* Set power save mode */
#define OSC_OFF 0x00
#define OSC_ON 0x01
#define POWER_SAVE_OFF 0x00
#define POWER_SAVE_ON 0x02
#define SET_POWER_SAVE_MODE(options) HalLcd_HW_Control(0x0C | (options))
/* Function Set */
#define CGROM 0x00
#define CGRAM 0x01
#define COM_FORWARD 0x00
#define COM_BACKWARD 0x02
#define TWO_LINE 0x00
#define THREE_LINE 0x04
#define FUNCTION_SET(options) HalLcd_HW_Control(0x10 | (options))
/* Set Display Start Line */
#define LINE1 0x00
#define LINE2 0x01
#define LINE3 0x02
#define LINE4 0x03
#define SET_DISPLAY_START_LINE(line) HalLcd_HW_Control(0x18 | (line))
/* Bias control */
#define BIAS_1_5 0x00
#define BIAS_1_4 0x01
#define SET_BIAS_CTRL(bias) HalLcd_HW_Control(0x1C | (bias))
/* Power control */
#define VOLTAGE_DIVIDER_OFF 0x00
#define VOLTAGE_DIVIDER_ON 0x01
#define CONVERTER_AND_REG_OFF 0x00
#define CONVERTER_AND_REG_ON 0x04
#define SET_POWER_CTRL(options) HalLcd_HW_Control(0x20 | (options))
// Set display control
#define DISPLAY_CTRL_ON 0x01
#define DISPLAY_CTRL_OFF 0x00
#define DISPLAY_CTRL_BLINK_ON 0x02
#define DISPLAY_CTRL_BLINK_OFF 0x00
#define DISPLAY_CTRL_CURSOR_ON 0x04
#define DISPLAY_CTRL_CURSOR_OFF 0x00
#define SET_DISPLAY_CTRL(options) HalLcd_HW_Control(0x28 | (options))
/* Set DD/ CGRAM address */
#define SET_DDRAM_ADDR(charIndex) HalLcd_HW_Control(0x80 | (charIndex))
#define SET_GCRAM_CHAR(specIndex) HalLcd_HW_Control(0xC0 | (specIndex))
/* Set ICONRAM address */
#define CONTRAST_CTRL_REGISTER 0x10
#define SET_ICONRAM_ADDR(addr) HalLcd_HW_Control(0x40 | (addr))
/* Set double height */
#define LINE_1_AND_2 0x01
#define LINE_2_AND_3 0x02
#define NORMAL_DISPLAY 0x00
#define SET_DOUBLE_HEIGHT(options) HalLcd_HW_Control(0x08 | (options))
/**************************************************************************************************
* MACROS
**************************************************************************************************/
#define HAL_IO_SET(port, pin, val) HAL_IO_SET_PREP(port, pin, val)
#define HAL_IO_SET_PREP(port, pin, val) st( P##port##_##pin## = val; )
#define HAL_CONFIG_IO_OUTPUT(port, pin, val) HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val)
#define HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val) st( P##port##SEL &= ~BV(pin); \
P##port##_##pin## = val; \
P##port##DIR |= BV(pin); )
#define HAL_CONFIG_IO_PERIPHERAL(port, pin) HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin)
#define HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin) st( P##port##SEL |= BV(pin); )
/* SPI interface control */
#define LCD_SPI_BEGIN() HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 0); /* chip select */
#define LCD_SPI_END() \
{ \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1); /* chip select */ \
}
/* clear the received and transmit byte status, write tx data to buffer, wait till transmit done */
#define LCD_SPI_TX(x) { U1CSR &= ~(BV(2) | BV(1)); U1DBUF = x; while( !(U1CSR & BV(1)) ); }
#define LCD_SPI_WAIT_RXRDY() { while(!(U1CSR & BV(1))); }
/* Control macros */
#define LCD_DO_WRITE() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
#define LCD_DO_CONTROL() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 0);
#define LCD_ACTIVATE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 0);
#define LCD_RELEASE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* LOCAL VARIABLES
**************************************************************************************************/
static uint8 *Lcd_Line1;
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
void HalLcd_HW_Init(void);
void HalLcd_HW_WaitUs(uint16 i);
void HalLcd_HW_Clear(void);
void HalLcd_HW_ClearAllSpecChars(void);
void HalLcd_HW_Control(uint8 cmd);
void HalLcd_HW_Write(uint8 data);
void HalLcd_HW_SetContrast(uint8 value);
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text);
void HalLcd_HW_WriteLine(uint8 line, const char *pText);
#endif //LCD
/**************************************************************************************************
* @fn HalLcdInit
*
* @brief Initilize LCD Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
**************************************************************************************************/
void HalLcdInit(void)
{
#if (HAL_LCD == TRUE)
Lcd_Line1 = NULL;
HalLcd_HW_Init();
#endif
}
/*************************************************************************************************
* LCD EMULATION FUNCTIONS
*
* Some evaluation boards are equipped with Liquid Crystal Displays
* (LCD) which may be used to display diagnostic information. These
* functions provide LCD emulation, sending the diagnostic strings
* to Z-Tool via the RS232 serial port. These functions are enabled
* when the "LCD_SUPPORTED" compiler flag is placed in the makefile.
*
* Most applications update both lines (1 and 2) of the LCD whenever
* text is posted to the device. This emulator assumes that line 1 is
* updated first (saved locally) and the formatting and send operation
* is triggered by receipt of line 2. Nothing will be transmitted if
* only line 1 is updated.
*
*************************************************************************************************/
/**************************************************************************************************
* @fn HalLcdWriteString
*
* @brief Write a string to the LCD
*
* @param str - pointer to the string that will be displayed
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteString ( char *str, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 strLen = 0;
uint8 totalLen = 0;
uint8 *buf;
uint8 tmpLen;
if ( Lcd_Line1 == NULL )
{
Lcd_Line1 = osal_mem_alloc( HAL_LCD_MAX_CHARS+1 );
HalLcdWriteString( "TexasInstruments", 1 );
}
strLen = (uint8)osal_strlen( (char*)str );
/* Check boundries */
if ( strLen > HAL_LCD_MAX_CHARS )
strLen = HAL_LCD_MAX_CHARS;
if ( option == HAL_LCD_LINE_1 )
{
/* Line 1 gets saved for later */
osal_memcpy( Lcd_Line1, str, strLen );
Lcd_Line1[strLen] = '\0';
}
else
{
/* Line 2 triggers action */
tmpLen = (uint8)osal_strlen( (char*)Lcd_Line1 );
totalLen = tmpLen + 1 + strLen + 1;
buf = osal_mem_alloc( totalLen );
if ( buf != NULL )
{
/* Concatenate strings */
osal_memcpy( buf, Lcd_Line1, tmpLen );
buf[tmpLen++] = ' ';
osal_memcpy( &buf[tmpLen], str, strLen );
buf[tmpLen+strLen] = '\0';
/* Send it out */
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#if defined(SERIAL_DEBUG_SUPPORTED)
debug_str( (uint8*)buf );
#endif //LCD_SUPPORTED
#endif //ZTOOL_P1
/* Free mem */
osal_mem_free( buf );
}
}
/* Display the string */
HalLcd_HW_WriteLine (option, str);
#endif //HAL_LCD
}
/**************************************************************************************************
* @fn HalLcdWriteValue
*
* @brief Write a value to the LCD
*
* @param value - value that will be displayed
* radix - 8, 10, 16
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteValue ( uint32 value, const uint8 radix, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 buf[LCD_MAX_BUF];
_ltoa( value, &buf[0], radix );
HalLcdWriteString( (char*)buf, option );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteScreen
*
* @brief Write a value to the LCD
*
* @param line1 - string that will be displayed on line 1
* line2 - string that will be displayed on line 2
*
* @return None
**************************************************************************************************/
void HalLcdWriteScreen( char *line1, char *line2 )
{
#if (HAL_LCD == TRUE)
HalLcdWriteString( line1, 1 );
HalLcdWriteString( line2, 2 );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value - value
* format - redix
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValue( char *title, uint16 value, uint8 format, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
osal_memcpy( buf, title, tmpLen );
buf[tmpLen] = ' ';
err = (uint32)(value);
_ltoa( err, &buf[tmpLen+1], format );
HalLcdWriteString( (char*)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value1 - value #1
* format1 - redix of value #1
* value2 - value #2
* format2 - redix of value #2
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValueValue( char *title, uint16 value1, uint8 format1,
uint16 value2, uint8 format2, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
if ( tmpLen )
{
osal_memcpy( buf, title, tmpLen );
buf[tmpLen++] = ' ';
}
err = (uint32)(value1);
_ltoa( err, &buf[tmpLen], format1 );
tmpLen = (uint8)osal_strlen( (char*)buf );
buf[tmpLen++] = ',';
buf[tmpLen++] = ' ';
err = (uint32)(value2);
_ltoa( err, &buf[tmpLen], format2 );
HalLcdWriteString( (char *)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdDisplayPercentBar
*
* @brief Display percentage bar on the LCD
*
* @param title -
* value -
*
* @return None
**************************************************************************************************/
void HalLcdDisplayPercentBar( char *title, uint8 value )
{
#if (HAL_LCD == TRUE)
uint8 percent;
uint8 leftOver;
uint8 buf[17];
uint32 err;
uint8 x;
/* Write the title: */
HalLcdWriteString( title, HAL_LCD_LINE_1 );
if ( value > 100 )
value = 100;
/* convert to blocks */
percent = (uint8)(value / 10);
leftOver = (uint8)(value % 10);
/* Make window */
osal_memcpy( buf, "[ ] ", 15 );
for ( x = 0; x < percent; x ++ )
{
buf[1+x] = '>';
}
if ( leftOver >= 5 )
buf[1+x] = '+';
err = (uint32)value;
_ltoa( err, (uint8*)&buf[13], 10 );
HalLcdWriteString( (char*)buf, HAL_LCD_LINE_2 );
#endif
}
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* HARDWARE LCD
**************************************************************************************************/
/**************************************************************************************************
* @fn halLcd_ConfigIO
*
* @brief Configure IO lines needed for LCD control.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigIO(void)
{
/* GPIO configuration */
HAL_CONFIG_IO_OUTPUT(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1);
}
/**************************************************************************************************
* @fn halLcd_ConfigSPI
*
* @brief Configure SPI lines needed for talking to LCD.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigSPI(void)
{
/* UART/SPI Peripheral configuration */
uint8 baud_exponent;
uint8 baud_mantissa;
/* Set SPI on UART 1 alternative 2 */
PERCFG |= 0x02;
/* Configure clk, master out and master in lines */
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_CLK_PORT, HAL_LCD_CLK_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MOSI_PORT, HAL_LCD_MOSI_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MISO_PORT, HAL_LCD_MISO_PIN);
/* Set SPI speed to 1 MHz (the values assume system clk of 32MHz)
* Confirm on board that this results in 1MHz spi clk.
*/
baud_exponent = 15;
baud_mantissa = 0;
/* Configure SPI */
U1UCR = 0x80; /* Flush and goto IDLE state. 8-N-1. */
U1CSR = 0x00; /* SPI mode, master. */
U1GCR = HAL_SPI_TRANSFER_MSB_FIRST | HAL_SPI_CLOCK_PHA_0 | HAL_SPI_CLOCK_POL_LO | baud_exponent;
U1BAUD = baud_mantissa;
}
/**************************************************************************************************
* @fn HalLcd_HW_Init
*
* @brief Initilize HW LCD Driver.
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Init(void)
{
/* Initialize LCD IO lines */
halLcd_ConfigIO();
/* Initialize SPI */
halLcd_ConfigSPI();
/* Perform reset */
LCD_ACTIVATE_RESET();
HalLcd_HW_WaitUs(15000); // 15 ms
LCD_RELEASE_RESET();
HalLcd_HW_WaitUs(15); // 15 us
/* Perform the initialization sequence */
FUNCTION_SET(CGRAM | COM_FORWARD | THREE_LINE);
/* Set contrast */
HalLcd_HW_SetContrast(15);
/* Set power */
SET_POWER_SAVE_MODE(OSC_OFF | POWER_SAVE_ON);
SET_POWER_CTRL(VOLTAGE_DIVIDER_ON | CONVERTER_AND_REG_ON);
SET_BIAS_CTRL(BIAS_1_5);
HalLcd_HW_WaitUs(21000);// 21 ms
/* Clear the display */
HalLcd_HW_Clear();
HalLcd_HW_ClearAllSpecChars();
SET_DISPLAY_CTRL(DISPLAY_CTRL_ON | DISPLAY_CTRL_BLINK_OFF | DISPLAY_CTRL_CURSOR_OFF);
}
/**************************************************************************************************
* @fn HalLcd_HW_Control
*
* @brief Write 1 command to the LCD
*
* @param uint8 cmd - command to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Control(uint8 cmd)
{
LCD_SPI_BEGIN();
LCD_DO_CONTROL();
LCD_SPI_TX(cmd);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_Write
*
* @brief Write 1 byte to the LCD
*
* @param uint8 data - data to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Write(uint8 data)
{
LCD_SPI_BEGIN();
LCD_DO_WRITE();
LCD_SPI_TX(data);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_SetContrast
*
* @brief Set display contrast
*
* @param uint8 value - contrast value
*
* @return none
**************************************************************************************************/
void HalLcd_HW_SetContrast(uint8 value)
{
SET_ICONRAM_ADDR(CONTRAST_CTRL_REGISTER);
HalLcd_HW_Write(value);
}
/**************************************************************************************************
* @fn HalLcd_HW_Clear
*
* @brief Clear the HW LCD
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Clear(void)
{
uint8 n;
SET_DDRAM_ADDR(0x00);
for (n = 0; n < (LCD_MAX_LINE_COUNT * LCD_MAX_LINE_LENGTH); n++)
{
HalLcd_HW_Write(' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_ClearAllSpecChars
*
* @brief Clear all special chars
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_ClearAllSpecChars(void)
{
uint8 n = 0;
SET_GCRAM_CHAR(0);
for (n = 0; n < (8 * 8); n++)
{
HalLcd_HW_Write(0x00);
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WriteChar
*
* @brief Write one char to the display
*
* @param uint8 line - line number that the char will be displayed
* uint8 col - colum where the char will be displayed
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text)
{
if (col < LCD_MAX_LINE_LENGTH)
{
SET_DDRAM_ADDR((line - 1) * LCD_MAX_LINE_LENGTH + col);
HalLcd_HW_Write(text);
}
else
{
return;
}
}
/**************************************************************************************************
* @fn halLcdWriteLine
*
* @brief Write one line on display
*
* @param uint8 line - display line
* char *pText - text buffer to write
*
* @return none
**************************************************************************************************/
void HalLcd_HW_WriteLine(uint8 line, const char *pText)
{
uint8 count;
uint8 totalLength = (uint8)osal_strlen( (char *)pText );
/* Write the content first */
for (count=0; count<totalLength; count++)
{
HalLcd_HW_WriteChar(line, count, (*(pText++)));
}
/* Write blank spaces to rest of the line */
for(count=totalLength; count<LCD_MAX_LINE_LENGTH;count++)
{
HalLcd_HW_WriteChar(line, count, ' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WaitUs
*
* @brief wait for x us. @ 32MHz MCU clock it takes 32 "nop"s for 1 us delay.
*
* @param x us. range[0-65536]
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WaitUs(uint16 microSecs)
{
while(microSecs--)
{
/* 32 NOPs == 1 usecs */
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop");
}
}
#endif
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,517 @@
/**************************************************************************************************
Filename: hal_led.c
Revised: $Date: 2011-04-15 10:47:58 -0700 (Fri, 15 Apr 2011) $
Revision: $Revision: 25723 $
Description: This file contains the interface to the HAL LED Service.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/***************************************************************************************************
* INCLUDES
***************************************************************************************************/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_drivers.h"
#include "hal_led.h"
#include "osal.h"
#include "hal_board.h"
/***************************************************************************************************
* CONSTANTS
***************************************************************************************************/
/***************************************************************************************************
* MACROS
***************************************************************************************************/
/***************************************************************************************************
* TYPEDEFS
***************************************************************************************************/
/* LED control structure */
typedef struct {
uint8 mode; /* Operation mode */
uint8 todo; /* Blink cycles left */
uint8 onPct; /* On cycle percentage */
uint16 time; /* On/off cycle time (msec) */
uint32 next; /* Time for next change */
} HalLedControl_t;
typedef struct
{
HalLedControl_t HalLedControlTable[HAL_LED_DEFAULT_MAX_LEDS];
uint8 sleepActive;
} HalLedStatus_t;
/***************************************************************************************************
* GLOBAL VARIABLES
***************************************************************************************************/
static uint8 HalLedState; // LED state at last set/clr/blink update
#if HAL_LED == TRUE
static uint8 HalSleepLedState; // LED state at last set/clr/blink update
static uint8 preBlinkState; // Original State before going to blink mode
// bit 0, 1, 2, 3 represent led 0, 1, 2, 3
#endif
#ifdef BLINK_LEDS
static HalLedStatus_t HalLedStatusControl;
#endif
/***************************************************************************************************
* LOCAL FUNCTION
***************************************************************************************************/
#if (HAL_LED == TRUE)
void HalLedUpdate (void);
void HalLedOnOff (uint8 leds, uint8 mode);
#endif /* HAL_LED */
/***************************************************************************************************
* FUNCTIONS - API
***************************************************************************************************/
/***************************************************************************************************
* @fn HalLedInit
*
* @brief Initialize LED Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
***************************************************************************************************/
void HalLedInit (void)
{
#if (HAL_LED == TRUE)
/* Initialize all LEDs to OFF */
HalLedSet (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Initialize sleepActive to FALSE */
HalLedStatusControl.sleepActive = FALSE;
#endif
}
/***************************************************************************************************
* @fn HalLedSet
*
* @brief Tun ON/OFF/TOGGLE given LEDs
*
* @param led - bit mask value of leds to be turned ON/OFF/TOGGLE
* mode - BLINK, FLASH, TOGGLE, ON, OFF
* @return None
***************************************************************************************************/
uint8 HalLedSet (uint8 leds, uint8 mode)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
switch (mode)
{
case HAL_LED_MODE_BLINK:
/* Default blink, 1 time, D% duty cycle */
HalLedBlink (leds, 1, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_FLASH:
/* Default flash, N times, D% duty cycle */
HalLedBlink (leds, HAL_LED_DEFAULT_FLASH_COUNT, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_ON:
case HAL_LED_MODE_OFF:
case HAL_LED_MODE_TOGGLE:
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
if (mode != HAL_LED_MODE_TOGGLE)
{
sts->mode = mode; /* ON or OFF */
}
else
{
sts->mode ^= HAL_LED_MODE_ON; /* Toggle */
}
HalLedOnOff (led, sts->mode);
leds ^= led;
}
led <<= 1;
sts++;
}
break;
default:
break;
}
#elif (HAL_LED == TRUE)
LedOnOff(leds, mode);
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) mode;
#endif /* BLINK_LEDS && HAL_LED */
return ( HalLedState );
}
/***************************************************************************************************
* @fn HalLedBlink
*
* @brief Blink the leds
*
* @param leds - bit mask value of leds to be blinked
* numBlinks - number of blinks
* percent - the percentage in each period where the led
* will be on
* period - length of each cycle in milliseconds
*
* @return None
***************************************************************************************************/
void HalLedBlink (uint8 leds, uint8 numBlinks, uint8 percent, uint16 period)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
if (leds && percent && period)
{
if (percent < 100)
{
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
/* Store the current state of the led before going to blinking if not already blinking */
if(sts->mode < HAL_LED_MODE_BLINK )
preBlinkState |= (led & HalLedState);
sts->mode = HAL_LED_MODE_OFF; /* Stop previous blink */
sts->time = period; /* Time for one on/off cycle */
sts->onPct = percent; /* % of cycle LED is on */
sts->todo = numBlinks; /* Number of blink cycles */
if (!numBlinks) sts->mode |= HAL_LED_MODE_FLASH; /* Continuous */
sts->next = osal_GetSystemClock(); /* Start now */
sts->mode |= HAL_LED_MODE_BLINK; /* Enable blinking */
leds ^= led;
}
led <<= 1;
sts++;
}
osal_set_event (Hal_TaskID, HAL_LED_BLINK_EVENT);
}
else
{
HalLedSet (leds, HAL_LED_MODE_ON); /* >= 100%, turn on */
}
}
else
{
HalLedSet (leds, HAL_LED_MODE_OFF); /* No on time, turn off */
}
#elif (HAL_LED == TRUE)
percent = (leds & HalLedState) ? HAL_LED_MODE_OFF : HAL_LED_MODE_ON;
HalLedOnOff (leds, percent); /* Toggle */
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) numBlinks;
(void) percent;
(void) period;
#endif /* BLINK_LEDS && HAL_LED */
}
#if (HAL_LED == TRUE)
/***************************************************************************************************
* @fn HalLedUpdate
*
* @brief Update leds to work with blink
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedUpdate (void)
{
uint8 led;
uint8 pct;
uint8 leds;
HalLedControl_t *sts;
uint32 time;
uint16 next;
uint16 wait;
next = 0;
led = HAL_LED_1;
leds = HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
/* Check if sleep is active or not */
if (!HalLedStatusControl.sleepActive)
{
while (leds)
{
if (leds & led)
{
if (sts->mode & HAL_LED_MODE_BLINK)
{
time = osal_GetSystemClock();
if (time >= sts->next)
{
if (sts->mode & HAL_LED_MODE_ON)
{
pct = 100 - sts->onPct; /* Percentage of cycle for off */
sts->mode &= ~HAL_LED_MODE_ON; /* Say it's not on */
HalLedOnOff (led, HAL_LED_MODE_OFF); /* Turn it off */
if (!(sts->mode & HAL_LED_MODE_FLASH))
{
sts->todo--; /* Not continuous, reduce count */
if (!sts->todo)
{
sts->mode ^= HAL_LED_MODE_BLINK; /* No more blinks */
}
}
}
else
{
pct = sts->onPct; /* Percentage of cycle for on */
sts->mode |= HAL_LED_MODE_ON; /* Say it's on */
HalLedOnOff (led, HAL_LED_MODE_ON); /* Turn it on */
}
if (sts->mode & HAL_LED_MODE_BLINK)
{
wait = (((uint32)pct * (uint32)sts->time) / 100);
sts->next = time + wait;
}
else
{
/* no more blink, no more wait */
wait = 0;
/* After blinking, set the LED back to the state before it blinks */
HalLedSet (led, ((preBlinkState & led)!=0)?HAL_LED_MODE_ON:HAL_LED_MODE_OFF);
/* Clear the saved bit */
preBlinkState &= (led ^ 0xFF);
}
}
else
{
wait = sts->next - time; /* Time left */
}
if (!next || ( wait && (wait < next) ))
{
next = wait;
}
}
leds ^= led;
}
led <<= 1;
sts++;
}
if (next)
{
osal_start_timerEx(Hal_TaskID, HAL_LED_BLINK_EVENT, next); /* Schedule event */
}
}
}
/***************************************************************************************************
* @fn HalLedOnOff
*
* @brief Turns specified LED ON or OFF
*
* @param leds - LED bit mask
* mode - LED_ON,LED_OFF,
*
* @return none
***************************************************************************************************/
void HalLedOnOff (uint8 leds, uint8 mode)
{
if (leds & HAL_LED_1)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
}
if (leds & HAL_LED_2)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED2();
}
else
{
HAL_TURN_OFF_LED2();
}
}
#if 0
if (leds & HAL_LED_3)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED3();
}
else
{
HAL_TURN_OFF_LED3();
}
}
if (leds & HAL_LED_4)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED4();
}
else
{
HAL_TURN_OFF_LED4();
}
}
#endif
/* Remember current state */
if (mode)
{
HalLedState |= leds;
}
else
{
HalLedState &= (leds ^ 0xFF);
}
}
#endif /* HAL_LED */
/***************************************************************************************************
* @fn HalGetLedState
*
* @brief Dim LED2 - Dim (set level) of LED2
*
* @param none
*
* @return led state
***************************************************************************************************/
uint8 HalLedGetState ()
{
#if (HAL_LED == TRUE)
return HalLedState;
#else
return 0;
#endif
}
/***************************************************************************************************
* @fn HalLedEnterSleep
*
* @brief Store current LEDs state before sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedEnterSleep( void )
{
#ifdef BLINK_LEDS
/* Sleep ON */
HalLedStatusControl.sleepActive = TRUE;
#endif /* BLINK_LEDS */
#if (HAL_LED == TRUE)
/* Save the state of each led */
HalSleepLedState = 0;
HalSleepLedState |= HAL_STATE_LED1();
HalSleepLedState |= HAL_STATE_LED2() << 1;
HalSleepLedState |= HAL_STATE_LED3() << 2;
HalSleepLedState |= HAL_STATE_LED4() << 3;
/* TURN OFF all LEDs to save power */
HalLedOnOff (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
}
/***************************************************************************************************
* @fn HalLedExitSleep
*
* @brief Restore current LEDs state after sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedExitSleep( void )
{
#if (HAL_LED == TRUE)
/* Load back the saved state */
HalLedOnOff(HalSleepLedState, HAL_LED_MODE_ON);
/* Restart - This takes care BLINKING LEDS */
HalLedUpdate();
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Sleep OFF */
HalLedStatusControl.sleepActive = FALSE;
#endif /* BLINK_LEDS */
}
/***************************************************************************************************
***************************************************************************************************/

View File

@@ -0,0 +1,62 @@
/**************************************************************************************************
Filename: hal_mac_cfg.h
Revised: $Date: 2010-04-12 09:38:02 -0700 (Mon, 12 Apr 2010) $
Revision: $Revision: 22158 $
Description: Describe the purpose and contents of the file.
Copyright 2007-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_MAC_CFG_H
#define HAL_MAC_CFG_H
/*
* Board Configuration File for low-level MAC
* --------------------------------------------
* Manufacturer : Texas Instruments
* Part Number : CC2530EB
* Processor : Texas Instruments CC2530
*
*/
/* ------------------------------------------------------------------------------------------------
* Board Specific Configuration
* ------------------------------------------------------------------------------------------------
*/
#define HAL_MAC_RSSI_OFFSET -73 /* no units */
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,190 @@
/**************************************************************************************************
Filename: hal_mcu.h
Revised: $Date: 2010-07-21 16:20:44 -0700 (Wed, 21 Jul 2010) $
Revision: $Revision: 23090 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef _HAL_MCU_H
#define _HAL_MCU_H
/*
* Target : Texas Instruments CC2530 (8051 core)
*
*/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_defs.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* Target Defines
* ------------------------------------------------------------------------------------------------
*/
#define HAL_MCU_CC2530
/* ------------------------------------------------------------------------------------------------
* Compiler Abstraction
* ------------------------------------------------------------------------------------------------
*/
/* ---------------------- IAR Compiler ---------------------- */
#ifdef __IAR_SYSTEMS_ICC__
#include <ioCC2530.h>
#define HAL_COMPILER_IAR
#define HAL_MCU_LITTLE_ENDIAN() __LITTLE_ENDIAN__
#define _PRAGMA(x) _Pragma(#x)
#define HAL_ISR_FUNC_DECLARATION(f,v) _PRAGMA(vector=v) __near_func __interrupt void f(void)
#define HAL_ISR_FUNC_PROTOTYPE(f,v) _PRAGMA(vector=v) __near_func __interrupt void f(void)
#define HAL_ISR_FUNCTION(f,v) HAL_ISR_FUNC_PROTOTYPE(f,v); HAL_ISR_FUNC_DECLARATION(f,v)
/* ---------------------- Keil Compiler ---------------------- */
#elif defined __KEIL__
#include <CC2530.h>
#define HAL_COMPILER_KEIL
#define HAL_MCU_LITTLE_ENDIAN() 0
#define HAL_ISR_FUNC_DECLARATION(f,v) void f(void) interrupt v
#define HAL_ISR_FUNC_PROTOTYPE(f,v) void f(void)
#define HAL_ISR_FUNCTION(f,v) HAL_ISR_FUNC_PROTOTYPE(f,v); HAL_ISR_FUNC_DECLARATION(f,v)
/* ------------------ Unrecognized Compiler ------------------ */
#else
#error "ERROR: Unknown compiler."
#endif
/* ------------------------------------------------------------------------------------------------
* Interrupt Macros
* ------------------------------------------------------------------------------------------------
*/
#define HAL_ENABLE_INTERRUPTS() st( EA = 1; )
#define HAL_DISABLE_INTERRUPTS() st( EA = 0; )
#define HAL_INTERRUPTS_ARE_ENABLED() (EA)
typedef unsigned char halIntState_t;
#define HAL_ENTER_CRITICAL_SECTION(x) st( x = EA; HAL_DISABLE_INTERRUPTS(); )
#define HAL_EXIT_CRITICAL_SECTION(x) st( EA = x; )
#define HAL_CRITICAL_STATEMENT(x) st( halIntState_t _s; HAL_ENTER_CRITICAL_SECTION(_s); x; HAL_EXIT_CRITICAL_SECTION(_s); )
#ifdef __IAR_SYSTEMS_ICC__
/* IAR library uses XCH instruction with EA. It may cause the higher priority interrupt to be
* locked out, therefore, may increase interrupt latency. It may also create a lockup condition.
* This workaround should only be used with 8051 using IAR compiler. When IAR fixes this by
* removing XCH usage in its library, compile the following macros to null to disable them.
*/
#define HAL_ENTER_ISR() { halIntState_t _isrIntState = EA; HAL_ENABLE_INTERRUPTS();
#define HAL_EXIT_ISR() EA = _isrIntState; }
#else
#define HAL_ENTER_ISR()
#define HAL_EXIT_ISR()
#endif /* __IAR_SYSTEMS_ICC__ */
/* ------------------------------------------------------------------------------------------------
* Reset Macro
* ------------------------------------------------------------------------------------------------
*/
#define WD_EN BV(3)
#define WD_MODE BV(2)
#define WD_INT_1900_USEC (BV(0) | BV(1))
#define WD_RESET1 (0xA0 | WD_EN | WD_INT_1900_USEC)
#define WD_RESET2 (0x50 | WD_EN | WD_INT_1900_USEC)
#define WD_KICK() st( WDCTL = (0xA0 | WDCTL & 0x0F); WDCTL = (0x50 | WDCTL & 0x0F); )
/* disable interrupts, set watchdog timer, wait for reset */
#define HAL_SYSTEM_RESET() st( HAL_DISABLE_INTERRUPTS(); WDCTL = WD_RESET1; WDCTL = WD_RESET2; for(;;); )
/* ------------------------------------------------------------------------------------------------
* CC2530 rev numbers
* ------------------------------------------------------------------------------------------------
*/
#define REV_A 0x00 /* workaround turned off */
#define REV_B 0x11 /* PG1.1 */
#define REV_C 0x20 /* PG2.0 */
#define REV_D 0x21 /* PG2.1 */
/* ------------------------------------------------------------------------------------------------
* CC2530 sleep common code
* ------------------------------------------------------------------------------------------------
*/
/* PCON bit definitions */
#define PCON_IDLE BV(0) /* Writing 1 to force CC2530 to enter sleep mode */
/* SLEEPCMD bit definitions */
#define OSC_PD BV(2) /* Idle Osc: powered down=1 */
#define PMODE (BV(1) | BV(0)) /* Power mode bits */
/* SLEEPSTA bit definitions */
#define XOSC_STB BV(6) /* XOSC: powered, stable=1 */
#define HFRC_STB BV(5) /* HFRCOSC: powered, stable=1 */
/* SLEEPCMD and SLEEPSTA bit definitions */
#define OSC_PD BV(2) /* 0: Both oscillators powered up and stable
* 1: oscillators not stable */
/* CLKCONCMD bit definitions */
#define OSC BV(6)
#define TICKSPD(x) (x << 3)
#define CLKSPD(x) (x << 0)
#define CLKCONCMD_32MHZ (0)
#define CLKCONCMD_16MHZ (CLKSPD(1) | TICKSPD(1) | OSC)
/* STLOAD */
#define LDRDY BV(0) /* Load Ready. This bit is 0 while the sleep timer
* loads the 24-bit compare value and 1 when the sleep
* timer is ready to start loading a newcompare value. */
#ifdef POWER_SAVING
extern volatile __data uint8 halSleepPconValue;
/* Any ISR that is used to wake up the chip shall call this macro. This prevents the race condition
* when the PCON IDLE bit is set after such a critical ISR fires during the prep for sleep.
*/
#define CLEAR_SLEEP_MODE() st( halSleepPconValue = 0; )
#define ALLOW_SLEEP_MODE() st( halSleepPconValue = PCON_IDLE; )
#else
#define CLEAR_SLEEP_MODE()
#define ALLOW_SLEEP_MODE()
#endif
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,577 @@
/**************************************************************************************************
Filename: _hal_oad.c
Revised: $Date: 2010-07-08 18:39:25 -0700 (Thu, 08 Jul 2010) $
Revision: $Revision: 22957 $
Description: This module contains optionally-compiled Boot Code to support OAD.
The rest of the functionality is the H/W specific drivers to read/write
the flash/NV containing the ACTIVE and the DOWNLOADED images.
Notes: This version targets the Texas Instruments CC253x family of processors.
Copyright 2008-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "comdef.h"
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_oad.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
#if HAL_OAD_BOOT_CODE
halDMADesc_t dmaCh0;
#endif
/* ------------------------------------------------------------------------------------------------
* Local Functions
* ------------------------------------------------------------------------------------------------
*/
static uint16 runPoly(uint16 crc, uint8 val);
#if HAL_OAD_XNV_IS_SPI
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len);
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len);
#endif
#if HAL_OAD_BOOT_CODE
static void vddWait(uint8 vdd);
static void dl2rc(void);
static uint16 crcCalc(void);
/**************************************************************************************************
* @fn main
*
* @brief ISR for the reset vector.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
#pragma location="NEAR_CODE"
void main(void)
{
HAL_BOARD_INIT();
vddWait(VDD_MIN_RUN);
#if HAL_OAD_XNV_IS_SPI
XNV_SPI_INIT();
#endif
/* This is in place of calling HalDmaInit() which would require init of the other 4 DMA
* descriptors in addition to just Channel 0.
*/
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
while (1)
{
uint16 crc[2];
HalFlashRead(HAL_OAD_CRC_ADDR / HAL_FLASH_PAGE_SIZE,
HAL_OAD_CRC_ADDR % HAL_FLASH_PAGE_SIZE,
(uint8 *)crc, sizeof(crc));
if (crc[0] == crc[1])
{
break;
}
else if ((crc[0] != 0) && (crc[0] == crcCalc()))
{
crc[1] = crc[0];
HalFlashWrite((HAL_OAD_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)crc, 1);
}
else
{
dl2rc();
}
}
// Simulate a reset for the Application code by an absolute jump to location 0x0800.
asm("LJMP 0x800\n");
}
/*********************************************************************
* @fn vddWait
*
* @brief Loop waiting for 256 reads of the Vdd over the requested limit.
*
* @param vdd - Vdd level to wait for.
*
* @return None.
*********************************************************************/
static void vddWait(uint8 vdd)
{
uint8 cnt = 16;
do {
do {
ADCCON3 = 0x0F;
while (!(ADCCON1 & 0x80));
} while (ADCH < vdd);
} while (--cnt);
}
/*********************************************************************
* @fn dl2rc
*
* @brief Copy the DL image to the RC image location.
*
* NOTE: Assumes that DL image ends on a flash word boundary.
*
* @param None.
*
* @return None.
*********************************************************************/
static void dl2rc(void)
{
preamble_t preamble;
uint32 oset;
uint16 addr = HAL_OAD_RC_START / HAL_FLASH_WORD_SIZE;
uint8 buf[4];
vddWait(VDD_MIN_OAD);
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_DL);
for (oset = 0; oset < preamble.len; oset += HAL_FLASH_WORD_SIZE)
{
HalOADRead(oset, buf, HAL_FLASH_WORD_SIZE, HAL_OAD_DL);
if ((addr % (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE)) == 0)
{
HalFlashErase(addr / (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE));
}
HalFlashWrite(addr++, buf, 1);
}
}
/*********************************************************************
* @fn crcCalc
*
* @brief Run the CRC16 Polynomial calculation over the RC image.
*
* @param None.
*
* @return The CRC16 calculated.
*/
static uint16 crcCalc(void)
{
preamble_t preamble;
uint32 oset;
uint16 crc = 0;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
if (preamble.len > HAL_OAD_DL_SIZE)
{
return 0;
}
// Run the CRC calculation over the active body of code.
for (oset = 0; oset < preamble.len; oset++)
{
if (oset == HAL_OAD_CRC_OSET)
{
oset += 3;
}
else
{
uint8 buf;
HalOADRead(oset, &buf, 1, HAL_OAD_RC);
crc = runPoly(crc, buf);
}
}
// IAR note explains that poly must be run with value zero for each byte of crc.
crc = runPoly(crc, 0);
crc = runPoly(crc, 0);
return crc;
}
#endif
/*********************************************************************
* @fn runPoly
*
* @brief Run the CRC16 Polynomial calculation over the byte parameter.
*
* @param crc - Running CRC calculated so far.
* @param val - Value on which to run the CRC16.
*
* @return crc - Updated for the run.
*/
static uint16 runPoly(uint16 crc, uint8 val)
{
const uint16 poly = 0x1021;
uint8 cnt;
for (cnt = 0; cnt < 8; cnt++, val <<= 1)
{
uint8 msb = (crc & 0x8000) ? 1 : 0;
crc <<= 1;
if (val & 0x80) crc |= 0x0001;
if (msb) crc ^= poly;
}
return crc;
}
/*********************************************************************
* @fn HalOADChkDL
*
* @brief Run the CRC16 Polynomial calculation over the DL image.
*
* @param dlImagePreambleOffset - Offset into the monolithic DL image to read the preamble.
*
* @return SUCCESS or FAILURE.
*********************************************************************/
uint8 HalOADChkDL(uint8 dlImagePreambleOffset)
{
preamble_t preamble;
uint32 oset;
uint16 crc = 0, crc2;
HalOADRead(dlImagePreambleOffset, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_DL);
// Run the CRC calculation over the downloaded image.
for (oset = 0; oset < preamble.len; oset++)
{
if ((oset < HAL_OAD_CRC_OSET) || (oset >= HAL_OAD_CRC_OSET+4))
{
uint8 buf;
HalOADRead(oset, &buf, 1, HAL_OAD_DL);
crc = runPoly(crc, buf);
}
}
// IAR note explains that poly must be run with value zero for each byte of crc.
crc = runPoly(crc, 0);
crc = runPoly(crc, 0);
HalOADRead(HAL_OAD_CRC_OSET, (uint8 *)&crc2, sizeof(crc2), HAL_OAD_DL);
return (crc2 == crc) ? SUCCESS : FAILURE;
}
/*********************************************************************
* @fn HalOADInvRC
*
* @brief Invalidate the active image so that the boot code will instantiate the DL image on the
* next reset.
*
* @param None.
*
* @return None.
*********************************************************************/
void HalOADInvRC(void)
{
uint16 crc[2] = {0,0xFFFF};
HalFlashWrite((HAL_OAD_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)crc, 1);
}
/*********************************************************************
* @fn HalOADRead
*
* @brief Read from the storage medium according to image type.
*
* @param oset - Offset into the monolithic image.
* @param pBuf - Pointer to the buffer in which to copy the bytes read.
* @param len - Number of bytes to read.
* @param type - Which image: HAL_OAD_RC or HAL_OAD_DL.
*
* @return None.
*********************************************************************/
void HalOADRead(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OAD_RC != type)
{
#if HAL_OAD_XNV_IS_INT
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
//oset += HAL_OAD_RC_START + preamble.len;
oset += HAL_OAD_RC_START + HAL_OAD_DL_OSET;
#elif HAL_OAD_XNV_IS_SPI
oset += HAL_OAD_DL_OSET;
HalSPIRead(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OAD_RC_START;
}
HalFlashRead(oset / HAL_FLASH_PAGE_SIZE, oset % HAL_FLASH_PAGE_SIZE, pBuf, len);
}
/*********************************************************************
* @fn HalOADWrite
*
* @brief Write to the storage medium according to the image type.
*
* NOTE: Destructive write on page boundary! When writing to the first flash word
* of a page boundary, the page is erased without saving/restoring the bytes not written.
* Writes anywhere else on a page assume that the location written to has been erased.
*
* @param oset - Offset into the monolithic image, aligned to HAL_FLASH_WORD_SIZE.
* @param pBuf - Pointer to the buffer in from which to write.
* @param len - Number of bytes to write. If not an even multiple of HAL_FLASH_WORD_SIZE,
* remainder bytes are overwritten with garbage.
* @param type - Which image: HAL_OAD_RC or HAL_OAD_DL.
*
* @return None.
*********************************************************************/
void HalOADWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OAD_RC != type)
{
#if HAL_OAD_XNV_IS_INT
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
//oset += HAL_OAD_RC_START + preamble.len;
oset += HAL_OAD_RC_START + HAL_OAD_DL_OSET;
#elif HAL_OAD_XNV_IS_SPI
oset += HAL_OAD_DL_OSET;
HalSPIWrite(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OAD_RC_START;
}
if ((oset % HAL_FLASH_PAGE_SIZE) == 0)
{
HalFlashErase(oset / HAL_FLASH_PAGE_SIZE);
}
HalFlashWrite(oset / HAL_FLASH_WORD_SIZE, pBuf, len / HAL_FLASH_WORD_SIZE);
}
#if HAL_OAD_XNV_IS_INT
/*********************************************************************
* @fn HalOADAvail
*
* @brief Determine the space available for downloading an image.
*
* @param None.
*
* @return Number of bytes available for storing an OAD image.
*********************************************************************/
uint32 HalOADAvail(void)
{
/*
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
return HAL_OAD_DL_MAX - preamble.len;
*/
return HAL_OAD_DL_MAX - HAL_OAD_DL_OSET;
}
#elif HAL_OAD_XNV_IS_SPI
/*********************************************************************
* CONSTANTS
*/
#define XNV_STAT_CMD 0x05
#define XNV_WREN_CMD 0x06
#define XNV_WRPG_CMD 0x0A
#define XNV_READ_CMD 0x0B
#define XNV_STAT_WIP 0x01
/*********************************************************************
* @fn xnvSPIWrite
*
* @brief SPI write sequence for code size savings.
*
* @param ch - The byte to write to the SPI.
*
* @return None.
*********************************************************************/
static void xnvSPIWrite(uint8 ch);
static void xnvSPIWrite(uint8 ch)
{
XNV_SPI_TX(ch);
XNV_SPI_WAIT_RXRDY();
}
/*********************************************************************
* @fn HalOADAvail
*
* @brief Determine the space available for downloading an image.
*
* @param None.
*
* @return Number of bytes available for storing an OAD image.
*********************************************************************/
uint32 HalOADAvail(void)
{
return HAL_OAD_DL_MAX - HAL_OAD_DL_OSET;
}
/*********************************************************************
* @fn HalSPIRead
*
* @brief Read from the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to the buffer in which to copy the bytes read from external NV.
* @param len - Number of bytes to read from external NV.
*
* @return None.
*********************************************************************/
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len)
{
#if !HAL_OAD_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
XNV_SPI_BEGIN();
do {
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_READ_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
xnvSPIWrite(0);
while (len--)
{
xnvSPIWrite(0);
*pBuf++ = XNV_SPI_RX();
}
XNV_SPI_END();
#if !HAL_OAD_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
/*********************************************************************
* @fn HalSPIWrite
*
* @brief Write to the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to the buffer in from which to write bytes to external NV.
* @param len - Number of bytes to write to external NV.
*
* @return None.
*********************************************************************/
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len)
{
uint8 cnt;
#if !HAL_OAD_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
while (len)
{
XNV_SPI_BEGIN();
do {
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WREN_CMD);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WRPG_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
// Can only write within any one page boundary, so prepare for next page write if bytes remain.
cnt = 0 - (uint8)addr;
if (cnt)
{
addr += cnt;
}
else
{
addr += 256;
}
do
{
xnvSPIWrite(*pBuf++);
cnt--;
len--;
} while (len && cnt);
XNV_SPI_END();
}
#if !HAL_OAD_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
#else
#error Invalid Xtra-NV for OAD.
#endif
/**************************************************************************************************
*/

View File

@@ -0,0 +1,130 @@
/**************************************************************************************************
Filename: hal_oad.h
Revised: $Date:$
Revision: $Revision:$
Description: This module defines optionally-compiled Boot Code parameters for the CC2x3x.
Copyright 2008-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_OAD_H
#define HAL_OAD_H
/*********************************************************************
* INCLUDES
*/
#include "hal_board_cfg.h"
#include "hal_types.h"
/*********************************************************************
* MACROS
*/
#if !defined HAL_OAD_BOOT_CODE
#define HAL_OAD_BOOT_CODE FALSE
#endif
// MSP430 needs to explicitly pack OAD data structures - 8051 is automatic with byte alignment.
#define PACK_1
/*********************************************************************
* CONSTANTS
*/
// Placement controlled by oad.xcl.
#define HAL_OAD_RC_START 0x0800
#define HAL_OAD_CRC_ADDR 0x0888
#define HAL_OAD_CRC_OSET (HAL_OAD_CRC_ADDR - HAL_OAD_RC_START)
/* Note that corresponding changes must be made to oad.xcl when changing the source of Xtra-NV.
* When using internal flash for XNV, (HAL_OAD_BOOT_PG_CNT + HAL_NV_PAGE_CNT) must be even.
*/
#define HAL_OAD_XNV_IS_INT FALSE
#define HAL_OAD_XNV_IS_SPI !HAL_OAD_XNV_IS_INT
/* The oad/oad-boot.xcl files only need 1 page of boot code (located on the first flash page),
* but the Lock Bits Page is lost with OAD since it is not programmable.
* So discard it here by faking that boot needs 2 pages.
*/
#define HAL_OAD_BOOT_PG_CNT 2
/* To reduce the binary image size due to padding un-used code space, reduce HAL_OAD_DL_SIZE
* to the minimum required for your Application and make the corresponding changes to oad_app.xcl.
* This size must be an even multiple of HAL_FLASH_PAGE_SIZE.
*/
#if HAL_OAD_XNV_IS_SPI && !defined HAL_BOARD_CC2530EB_REV13
#define HAL_OAD_DL_MAX 0x40000
#define HAL_OAD_DL_SIZE (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OAD_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OAD_DL_OSET 0x0 // Configurable offset into an external NV.
#else
#define HAL_OAD_DL_MAX (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OAD_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OAD_DL_SIZE (HAL_OAD_DL_MAX / 2)
#define HAL_OAD_DL_OSET (HAL_OAD_DL_MAX / 2)
#endif
// To run OAD with the legacy ZOAD.exe PC tool, place the preamble in this legacy location.
#define PREAMBLE_OFFSET 0x8C
#if HAL_OAD_XNV_IS_INT
#define VDD_MIN_OAD VDD_MIN_NV
#else
#define VDD_MIN_OAD VDD_MIN_XNV
#endif
/*********************************************************************
* TYPEDEFS
*/
typedef enum {
HAL_OAD_RC, /* Run code / active image. */
HAL_OAD_DL /* Downloaded code to be activated later. */
} image_t;
typedef struct {
uint8 magic[2];
uint32 len;
uint16 vers;
uint16 manu;
uint16 prod;
} preamble_t;
/*********************************************************************
* FUNCTIONS
*/
uint8 HalOADChkDL(uint8 dlImagePreambleOffset);
void HalOADInvRC(void);
uint32 HalOADAvail(void);
void HalOADRead(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
void HalOADWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
#endif

View File

@@ -0,0 +1,532 @@
/******************************************************************************
Filename: hal_ota.c
Revised: $Date: 2010-11-18 08:22:50 -0800 (Thu, 18 Nov 2010) $
Revision: $Revision: 24438 $
Description: This module contains optionally-compiled Boot Code to support
OTA. The rest of the functionality is the H/W specific drivers
to read/write the flash/NV containing the ACTIVE and the
DOWNLOADED images.
Notes: Targets the Texas Instruments CC253x family of processors.
Copyright 2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
******************************************************************************/
/******************************************************************************
* INCLUDES
*/
#include "comdef.h"
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_ota.h"
#include "hal_types.h"
#include "ota_common.h"
/******************************************************************************
* CONSTANTS
*/
#if HAL_OTA_XNV_IS_SPI
#define XNV_STAT_CMD 0x05
#define XNV_WREN_CMD 0x06
#define XNV_WRPG_CMD 0x0A
#define XNV_READ_CMD 0x0B
#define XNV_STAT_WIP 0x01
#endif
/******************************************************************************
* TYPEDEFS
*/
typedef struct
{
uint16 crc[2];
uint32 programSize;
} OTA_CrcControl_t;
/******************************************************************************
* LOCAL VARIABLES
*/
OTA_CrcControl_t OTA_crcControl;
#if HAL_OTA_BOOT_CODE
halDMADesc_t dmaCh0;
#endif
/******************************************************************************
* LOCAL FUNCTIONS
*/
static uint16 runPoly(uint16 crc, uint8 val);
#if HAL_OTA_XNV_IS_SPI
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len);
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len);
static void xnvSPIWrite(uint8 ch);
#endif
#if HAL_OTA_BOOT_CODE
static void dl2rc(void);
static uint16 crcCalc(void);
/******************************************************************************
* @fn main
*
* @brief ISR for the reset vector.
*
* @param None.
*
* @return None.
*/
#pragma location="NEAR_CODE"
void main(void)
{
HAL_BOARD_INIT();
#if HAL_OTA_XNV_IS_SPI
XNV_SPI_INIT();
#endif
/* This is in place of calling HalDmaInit() which would require init of the
* other 4 DMA descriptors in addition to just Channel 0.
*/
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
while (1)
{
HalFlashRead(HAL_OTA_CRC_ADDR / HAL_FLASH_PAGE_SIZE,
HAL_OTA_CRC_ADDR % HAL_FLASH_PAGE_SIZE,
(uint8 *)&OTA_crcControl, sizeof(OTA_crcControl));
if (OTA_crcControl.crc[0] == OTA_crcControl.crc[1])
{
break;
}
else if ((OTA_crcControl.crc[0] != 0) && (OTA_crcControl.crc[0] == crcCalc()))
{
OTA_crcControl.crc[1] = OTA_crcControl.crc[0];
HalFlashWrite((HAL_OTA_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)OTA_crcControl.crc, 1);
}
else
{
dl2rc();
}
}
// Simulate a reset for the Application code by an absolute jump to location 0x0800.
asm("LJMP 0x800\n");
}
/******************************************************************************
* @fn dl2rc
*
* @brief Copy the DL image to the RC image location.
*
* NOTE: Assumes that DL image ends on a flash word boundary.
*
* @param None.
*
* @return None.
*/
static void dl2rc(void)
{
uint32 oset;
OTA_SubElementHdr_t subElement;
OTA_ImageHeader_t header;
uint16 addr = HAL_OTA_RC_START / HAL_FLASH_WORD_SIZE;
uint8 buf[4];
// Determine the length and starting point of the upgrade image
HalOTARead(0, (uint8 *)&header, sizeof(OTA_ImageHeader_t), HAL_OTA_DL);
HalOTARead(header.headerLength, (uint8*)&subElement, OTA_SUB_ELEMENT_HDR_LEN, HAL_OTA_DL);
for (oset = 0; oset < subElement.length; oset += HAL_FLASH_WORD_SIZE)
{
HalOTARead(oset + header.headerLength + OTA_SUB_ELEMENT_HDR_LEN, buf, HAL_FLASH_WORD_SIZE, HAL_OTA_DL);
if ((addr % (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE)) == 0)
{
HalFlashErase(addr / (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE));
}
HalFlashWrite(addr++, buf, 1);
}
}
/******************************************************************************
* @fn crcCalc
*
* @brief Run the CRC16 Polynomial calculation over the RC image.
*
* @param None.
*
* @return The CRC16 calculated.
*/
static uint16 crcCalc()
{
uint32 oset;
uint16 crc = 0;
// Run the CRC calculation over the active body of code.
for (oset = 0; oset < OTA_crcControl.programSize; oset++)
{
if ((oset < HAL_OTA_CRC_OSET) || (oset >= HAL_OTA_CRC_OSET + 4))
{
uint8 buf;
HalOTARead(oset, &buf, 1, HAL_OTA_RC);
crc = runPoly(crc, buf);
}
}
return crc;
}
#endif //HAL_OTA_BOOT_CODE
/******************************************************************************
* @fn runPoly
*
* @brief Run the CRC16 Polynomial calculation over the byte parameter.
*
* @param crc - Running CRC calculated so far.
* @param val - Value on which to run the CRC16.
*
* @return crc - Updated for the run.
*/
static uint16 runPoly(uint16 crc, uint8 val)
{
const uint16 poly = 0x1021;
uint8 cnt;
for (cnt = 0; cnt < 8; cnt++, val <<= 1)
{
uint8 msb = (crc & 0x8000) ? 1 : 0;
crc <<= 1;
if (val & 0x80) crc |= 0x0001;
if (msb) crc ^= poly;
}
return crc;
}
/******************************************************************************
* @fn HalOTAChkDL
*
* @brief Run the CRC16 Polynomial calculation over the DL image.
*
* @param None
*
* @return SUCCESS or FAILURE.
*/
uint8 HalOTAChkDL(uint8 dlImagePreambleOffset)
{
(void)dlImagePreambleOffset; // Intentionally unreferenced parameter
uint32 oset;
uint16 crc = 0;
OTA_CrcControl_t crcControl;
OTA_ImageHeader_t header;
uint32 programStart;
#if HAL_OTA_XNV_IS_SPI
XNV_SPI_INIT();
#endif
// Read the OTA File Header
HalOTARead(0, (uint8 *)&header, sizeof(OTA_ImageHeader_t), HAL_OTA_DL);
// Calculate the update image start address
programStart = header.headerLength + OTA_SUB_ELEMENT_HDR_LEN;
// Get the CRC Control structure
HalOTARead(programStart + HAL_OTA_CRC_OSET, (uint8 *)&crcControl, sizeof(crcControl), HAL_OTA_DL);
if ((crcControl.programSize > HAL_OTA_DL_MAX) || (crcControl.programSize == 0))
{
return FAILURE;
}
// Run the CRC calculation over the downloaded image.
for (oset = 0; oset < crcControl.programSize; oset++)
{
if ((oset < HAL_OTA_CRC_OSET) || (oset >= HAL_OTA_CRC_OSET+4))
{
uint8 buf;
HalOTARead(oset + programStart, &buf, 1, HAL_OTA_DL);
crc = runPoly(crc, buf);
}
}
return (crcControl.crc[0] == crc) ? SUCCESS : FAILURE;
}
/******************************************************************************
* @fn HalOTAInvRC
*
* @brief Invalidate the active image so that the boot code will instantiate
* the DL image on the next reset.
*
* @param None.
*
* @return None.
*/
void HalOTAInvRC(void)
{
uint16 crc[2] = {0,0xFFFF};
HalFlashWrite((HAL_OTA_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)crc, 1);
}
/******************************************************************************
* @fn HalOTARead
*
* @brief Read from the storage medium according to image type.
*
* @param oset - Offset into the monolithic image.
* @param pBuf - Pointer to the buffer in which to copy the bytes read.
* @param len - Number of bytes to read.
* @param type - Which image: HAL_OTA_RC or HAL_OTA_DL.
*
* @return None.
*/
void HalOTARead(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OTA_RC != type)
{
#if HAL_OTA_XNV_IS_INT
preamble_t preamble;
HalOTARead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OTA_RC);
oset += HAL_OTA_RC_START + HAL_OTA_DL_OSET;
#elif HAL_OTA_XNV_IS_SPI
oset += HAL_OTA_DL_OSET;
HalSPIRead(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OTA_RC_START;
}
HalFlashRead(oset / HAL_FLASH_PAGE_SIZE, oset % HAL_FLASH_PAGE_SIZE, pBuf, len);
}
/******************************************************************************
* @fn HalOTAWrite
*
* @brief Write to the storage medium according to the image type.
*
* NOTE: Destructive write on page boundary! When writing to the first flash word
* of a page boundary, the page is erased without saving/restoring the bytes not written.
* Writes anywhere else on a page assume that the location written to has been erased.
*
* @param oset - Offset into the monolithic image, aligned to HAL_FLASH_WORD_SIZE.
* @param pBuf - Pointer to the buffer in from which to write.
* @param len - Number of bytes to write. If not an even multiple of HAL_FLASH_WORD_SIZE,
* remainder bytes are overwritten with garbage.
* @param type - Which image: HAL_OTA_RC or HAL_OTA_DL.
*
* @return None.
*/
void HalOTAWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OTA_RC != type)
{
#if HAL_OTA_XNV_IS_INT
oset += HAL_OTA_RC_START + HAL_OTA_DL_OSET;
#elif HAL_OTA_XNV_IS_SPI
oset += HAL_OTA_DL_OSET;
HalSPIWrite(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OTA_RC_START;
}
if ((oset % HAL_FLASH_PAGE_SIZE) == 0)
{
HalFlashErase(oset / HAL_FLASH_PAGE_SIZE);
}
HalFlashWrite(oset / HAL_FLASH_WORD_SIZE, pBuf, len / HAL_FLASH_WORD_SIZE);
}
/******************************************************************************
* @fn HalOTAAvail
*
* @brief Determine the space available for downloading an image.
*
* @param None.
*
* @return Number of bytes available for storing an OTA image.
*/
uint32 HalOTAAvail(void)
{
return HAL_OTA_DL_MAX - HAL_OTA_DL_OSET;
}
#if HAL_OTA_XNV_IS_SPI
/******************************************************************************
* @fn xnvSPIWrite
*
* @brief SPI write sequence for code size savings.
*
* @param ch - The byte to write to the SPI.
*
* @return None.
*/
static void xnvSPIWrite(uint8 ch)
{
XNV_SPI_TX(ch);
XNV_SPI_WAIT_RXRDY();
}
/******************************************************************************
* @fn HalSPIRead
*
* @brief Read from the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to buffer to copy the bytes read from external NV.
* @param len - Number of bytes to read from external NV.
*
* @return None.
*****************************************************************************/
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len)
{
#if !HAL_OTA_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
XNV_SPI_BEGIN();
do
{
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_READ_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
xnvSPIWrite(0);
while (len--)
{
xnvSPIWrite(0);
*pBuf++ = XNV_SPI_RX();
}
XNV_SPI_END();
#if !HAL_OTA_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
/******************************************************************************
* @fn HalSPIWrite
*
* @brief Write to the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to the buffer in from which to write bytes to external NV.
* @param len - Number of bytes to write to external NV.
*
* @return None.
*****************************************************************************/
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len)
{
uint8 cnt;
#if !HAL_OTA_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
while (len)
{
XNV_SPI_BEGIN();
do
{
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WREN_CMD);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WRPG_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
// Can only write within any one page boundary, so prepare for next page write if bytes remain.
cnt = 0 - (uint8)addr;
if (cnt)
{
addr += cnt;
}
else
{
addr += 256;
}
do
{
xnvSPIWrite(*pBuf++);
cnt--;
len--;
} while (len && cnt);
XNV_SPI_END();
}
#if !HAL_OTA_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
#elif !HAL_OTA_XNV_IS_INT
#error Invalid Xtra-NV for OTA.
#endif
/******************************************************************************
*/

View File

@@ -0,0 +1,128 @@
/******************************************************************************
Filename: hal_ota.h
Revised: $Date: 2010-11-18 08:22:50 -0800 (Thu, 18 Nov 2010) $
Revision: $Revision: 24438 $
Description: This module defines optionally-compiled Boot Code parameters
for the CC253x.
Copyright 2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
******************************************************************************/
#ifndef HAL_OTA_H
#define HAL_OTA_H
/******************************************************************************
* INCLUDES
*/
#include "hal_board_cfg.h"
#include "hal_types.h"
/******************************************************************************
* MACROS
*/
#if !defined HAL_OTA_BOOT_CODE
#define HAL_OTA_BOOT_CODE FALSE
#endif
// MSP430 needs to explicitly pack OTA data structures - 8051 is automatic with byte alignment.
#define PACK_1
/******************************************************************************
* CONSTANTS
*/
// Placement controlled by ota.xcl.
#define HAL_OTA_RC_START 0x0800
#define HAL_OTA_CRC_ADDR 0x0888
#define HAL_OTA_CRC_OSET (HAL_OTA_CRC_ADDR - HAL_OTA_RC_START)
/* Note that corresponding changes must be made to ota.xcl when changing the source of Xtra-NV.
* When using internal flash for XNV, (HAL_OTA_BOOT_PG_CNT + HAL_NV_PAGE_CNT) must be even.
*/
#define HAL_OTA_XNV_IS_INT FALSE
#define HAL_OTA_XNV_IS_SPI !HAL_OTA_XNV_IS_INT
/* The ota/ota-boot.xcl files only need 1 page of boot code (located on the first flash page),
* but the Lock Bits Page is lost with OTA since it is not programmable.
* So discard it here by faking that boot needs 2 pages.
*/
#define HAL_OTA_BOOT_PG_CNT 2
/* To reduce the binary image size due to padding un-used code space, reduce HAL_OTA_DL_SIZE
* to the minimum required for your Application and make the corresponding changes to ota_app.xcl.
* This size must be an even multiple of HAL_FLASH_PAGE_SIZE.
*/
#if HAL_OTA_XNV_IS_SPI && !defined HAL_BOARD_CC2530EB_REV13
#define HAL_OTA_DL_MAX 0x40000
#define HAL_OTA_DL_SIZE (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OTA_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OTA_DL_OSET 0x0 // Configurable offset into an external NV.
#else
#define HAL_OTA_DL_MAX (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OTA_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OTA_DL_SIZE (HAL_OTA_DL_MAX / 2)
#define HAL_OTA_DL_OSET (HAL_OTA_DL_MAX / 2)
#endif
#define PREAMBLE_OFFSET 0x8C
/*********************************************************************
* TYPEDEFS
*/
typedef enum {
HAL_OTA_RC, /* Run code / active image. */
HAL_OTA_DL /* Downloaded code to be activated later. */
} image_t;
typedef struct {
uint16 crc;
uint16 crc_shadow;
} otaCrc_t;
typedef struct {
uint32 programLength;
uint16 manufacturerId;
uint16 imageType;
uint32 imageVersion;
} preamble_t;
/*********************************************************************
* FUNCTIONS
*/
uint8 HalOTAChkDL(uint8 dlImagePreambleOffset);
void HalOTAInvRC(void);
uint32 HalOTAAvail(void);
void HalOTARead(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
void HalOTAWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
#endif

View File

@@ -0,0 +1,520 @@
/**************************************************************************************************
Filename: hal_sleep.c
Revised: $Date: 2011-04-04 09:40:22 -0700 (Mon, 04 Apr 2011) $
Revision: $Revision: 25578 $
Description: This module contains the HAL power management procedures for the CC2530.
Copyright 2006-2011 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_types.h"
#include "hal_mcu.h"
#include "hal_board.h"
#include "hal_sleep.h"
#include "hal_led.h"
#include "hal_key.h"
#include "mac_api.h"
#include "OSAL.h"
#include "OSAL_Timers.h"
#include "OSAL_Tasks.h"
#include "OSAL_PwrMgr.h"
#include "OnBoard.h"
#include "hal_drivers.h"
#include "hal_assert.h"
#include "mac_mcu.h"
#ifndef ZG_BUILD_ENDDEVICE_TYPE
# define ZG_BUILD_ENDDEVICE_TYPE FALSE
#endif
#if ZG_BUILD_ENDDEVICE_TYPE && defined (NWK_AUTO_POLL)
#include "nwk_globals.h"
#include "ZGlobals.h"
#endif
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/* POWER CONSERVATION DEFINITIONS
* Sleep mode H/W definitions (enabled with POWER_SAVING compile option)
*/
#define CC2530_PM0 0 /* PM0, Clock oscillators on, voltage regulator on */
#define CC2530_PM1 1 /* PM1, 32.768 kHz oscillators on, voltage regulator on */
#define CC2530_PM2 2 /* PM2, 32.768 kHz oscillators on, voltage regulator off */
#define CC2530_PM3 3 /* PM3, All clock oscillators off, voltage regulator off */
/* HAL power management mode is set according to the power management state. The default
* setting is HAL_SLEEP_OFF. The actual value is tailored to different HW platform. Both
* HAL_SLEEP_TIMER and HAL_SLEEP_DEEP selections will:
* 1. turn off the system clock, and
* 2. halt the MCU.
* HAL_SLEEP_TIMER can be woken up by sleep timer interrupt, I/O interrupt and reset.
* HAL_SLEEP_DEEP can be woken up by I/O interrupt and reset.
*/
#define HAL_SLEEP_OFF CC2530_PM0
#define HAL_SLEEP_TIMER CC2530_PM2
#define HAL_SLEEP_DEEP CC2530_PM3
/* MAX_SLEEP_TIME calculation:
* Sleep timer maximum duration = 0xFFFF7F / 32768 Hz = 511.996 seconds
* Round it to 510 seconds or 510000 ms
*/
#define MAX_SLEEP_TIME 510000 /* maximum time to sleep allowed by ST */
/* minimum time to sleep, this macro is to:
* 1. avoid thrashing in-and-out of sleep with short OSAL timer (~2ms)
* 2. define minimum safe sleep period
*/
#if !defined (PM_MIN_SLEEP_TIME)
#define PM_MIN_SLEEP_TIME 14 /* default to minimum safe sleep time minimum CAP */
#endif
/* The PCON instruction must be 4-byte aligned. The following code may cause excessive power
* consumption if not aligned. See linker file ".xcl" for actual placement.
*/
#pragma location = "SLEEP_CODE"
void halSetSleepMode(void);
/* This value is used to adjust the sleep timer compare value such that the sleep timer
* compare takes into account the amount of processing time spent in function halSleep().
* The first value is determined by measuring the number of sleep timer ticks it from
* the beginning of the function to entering sleep mode or more precisely, when
* MAC_PwrNextTimeout() is called. The second value is determined by measuring the number
* of sleep timer ticks from exit of sleep mode to the call to MAC_PwrOnReq() where the
* MAC timer is restarted.
*/
#define HAL_SLEEP_ADJ_TICKS (11 + 12)
#ifndef HAL_SLEEP_DEBUG_POWER_MODE
/* set CC2530 power mode; always use PM2 */
#define HAL_SLEEP_PREP_POWER_MODE(mode) st( SLEEPCMD &= ~PMODE; /* clear mode bits */ \
SLEEPCMD |= mode; /* set mode bits */ \
while (!(STLOAD & LDRDY)); \
halSleepPconValue = PCON_IDLE; \
)
#define HAL_SLEEP_SET_POWER_MODE() halSetSleepMode()
#else
/* Debug: don't set power mode, just block until sleep timer interrupt */
#define HAL_SLEEP_PREP_POWER_MODE(mode) /* nothing */
#define HAL_SLEEP_SET_POWER_MODE() st( while(halSleepInt == FALSE); \
halSleepInt = FALSE; \
HAL_DISABLE_INTERRUPTS(); \
)
#endif
/* sleep and external interrupt port masks */
#define STIE_BV BV(5)
#define P0IE_BV BV(5)
#define P1IE_BV BV(4)
#define P2IE_BV BV(1)
/* sleep timer interrupt control */
#define HAL_SLEEP_TIMER_ENABLE_INT() st(IEN0 |= STIE_BV;) /* enable sleep timer interrupt */
#define HAL_SLEEP_TIMER_DISABLE_INT() st(IEN0 &= ~STIE_BV;) /* disable sleep timer interrupt */
#define HAL_SLEEP_TIMER_CLEAR_INT() st(STIF = 0;) /* clear sleep interrupt flag */
/* backup interrupt enable registers before sleep */
#define HAL_SLEEP_IE_BACKUP_AND_DISABLE(ien0, ien1, ien2) st(ien0 = IEN0; /* backup IEN0 register */ \
ien1 = IEN1; /* backup IEN1 register */ \
ien2 = IEN2; /* backup IEN2 register */ \
IEN0 &= STIE_BV; /* disable IEN0 except STIE */ \
IEN1 &= P0IE_BV; /* disable IEN1 except P0IE */ \
IEN2 &= (P1IE_BV|P2IE_BV);) /* disable IEN2 except P1IE, P2IE */
/* restore interrupt enable registers before sleep */
#define HAL_SLEEP_IE_RESTORE(ien0, ien1, ien2) st(IEN0 = ien0; /* restore IEN0 register */ \
IEN1 = ien1; /* restore IEN1 register */ \
IEN2 = ien2;) /* restore IEN2 register */
/* convert msec to 320 usec units with round */
#define HAL_SLEEP_MS_TO_320US(ms) (((((uint32) (ms)) * 100) + 31) / 32)
/* for optimized indexing of uint32's */
#if HAL_MCU_LITTLE_ENDIAN()
#define UINT32_NDX0 0
#define UINT32_NDX1 1
#define UINT32_NDX2 2
#define UINT32_NDX3 3
#else
#define UINT32_NDX0 3
#define UINT32_NDX1 2
#define UINT32_NDX2 1
#define UINT32_NDX3 0
#endif
/* ------------------------------------------------------------------------------------------------
* Global Variables
* ------------------------------------------------------------------------------------------------
*/
/* PCON register value to program when setting power mode */
volatile __data uint8 halSleepPconValue = PCON_IDLE;
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
/* HAL power management mode is set according to the power management state.
*/
static uint8 halPwrMgtMode = HAL_SLEEP_OFF;
#ifdef HAL_SLEEP_DEBUG_POWER_MODE
static bool halSleepInt = FALSE;
#endif
/* ------------------------------------------------------------------------------------------------
* Function Prototypes
* ------------------------------------------------------------------------------------------------
*/
void halSleepSetTimer(uint32 timeout);
/**************************************************************************************************
* @fn halSleep
*
* @brief This function put the CC2530 to sleep. The PCON instruction must be 4-byte aligned.
* The following code may cause excessive power consumption if not aligned. See linker
* file ".xcl" for actual placement.
*
* input parameters
*
* @param None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSetSleepMode(void)
{
PCON = halSleepPconValue;
HAL_DISABLE_INTERRUPTS();
}
/**************************************************************************************************
* @fn halSleep
*
* @brief This function is called from the OSAL task loop using and existing OSAL
* interface. It sets the low power mode of the MAC and the CC2530.
*
* input parameters
*
* @param osal_timeout - Next OSAL timer timeout.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSleep( uint16 osal_timeout )
{
uint32 timeout;
uint32 macTimeout = 0;
/* get next OSAL timer expiration converted to 320 usec units */
timeout = HAL_SLEEP_MS_TO_320US(osal_timeout);
if (timeout == 0)
{
timeout = MAC_PwrNextTimeout();
}
else
{
/* get next MAC timer expiration */
macTimeout = MAC_PwrNextTimeout();
/* get lesser of two timeouts */
if ((macTimeout != 0) && (macTimeout < timeout))
{
timeout = macTimeout;
}
}
/* HAL_SLEEP_PM2 is entered only if the timeout is zero and
* the device is a stimulated device.
*/
halPwrMgtMode = (timeout == 0) ? HAL_SLEEP_DEEP : HAL_SLEEP_TIMER;
/* DEEP sleep can only be entered when zgPollRate == 0.
* This is to eliminate any possibility of entering PM3 between
* two network timers.
*/
#if ZG_BUILD_ENDDEVICE_TYPE && defined (NWK_AUTO_POLL)
if ((timeout > HAL_SLEEP_MS_TO_320US(PM_MIN_SLEEP_TIME)) ||
(timeout == 0 && zgPollRate == 0))
#else
if ((timeout > HAL_SLEEP_MS_TO_320US(PM_MIN_SLEEP_TIME)) ||
(timeout == 0))
#endif
{
halIntState_t ien0, ien1, ien2;
HAL_ASSERT(HAL_INTERRUPTS_ARE_ENABLED());
HAL_DISABLE_INTERRUPTS();
/* always use "deep sleep" to turn off radio VREG on CC2530 */
if (halSleepPconValue != 0 && MAC_PwrOffReq(MAC_PWR_SLEEP_DEEP) == MAC_SUCCESS)
{
/* The PCON value is not zero. There is no interrupt overriding the
* sleep decision. Also, the radio granted the sleep request.
*/
#if ((defined HAL_KEY) && (HAL_KEY == TRUE))
/* get peripherals ready for sleep */
HalKeyEnterSleep();
#endif
#ifdef HAL_SLEEP_DEBUG_LED
HAL_TURN_OFF_LED3();
#else
/* use this to turn LEDs off during sleep */
HalLedEnterSleep();
#endif
/* enable sleep timer interrupt */
if (timeout != 0)
{
if (timeout > HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME ))
{
timeout -= HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME );
halSleepSetTimer(HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME ));
}
else
{
/* set sleep timer */
halSleepSetTimer(timeout);
}
/* set up sleep timer interrupt */
HAL_SLEEP_TIMER_CLEAR_INT();
HAL_SLEEP_TIMER_ENABLE_INT();
}
#ifdef HAL_SLEEP_DEBUG_LED
if (halPwrMgtMode == CC2530_PM1)
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
#endif
/* Prep CC2530 power mode */
HAL_SLEEP_PREP_POWER_MODE(halPwrMgtMode);
/* save interrupt enable registers and disable all interrupts */
HAL_SLEEP_IE_BACKUP_AND_DISABLE(ien0, ien1, ien2);
HAL_ENABLE_INTERRUPTS();
/* set CC2530 power mode, interrupt is disabled after this function
* Note that an ISR (that could wake up from power mode) which runs
* between the previous instruction enabling interrupts and before
* power mode is set would switch the halSleepPconValue so that
* power mode shall not be entered in such a case.
*/
HAL_SLEEP_SET_POWER_MODE();
/* the interrupt is disabled - see halSetSleepMode() */
/* restore interrupt enable registers */
HAL_SLEEP_IE_RESTORE(ien0, ien1, ien2);
/* disable sleep timer interrupt */
HAL_SLEEP_TIMER_DISABLE_INT();
#ifdef HAL_SLEEP_DEBUG_LED
HAL_TURN_ON_LED3();
#else
/* use this to turn LEDs back on after sleep */
HalLedExitSleep();
#endif
#if ((defined HAL_KEY) && (HAL_KEY == TRUE))
/* handle peripherals */
(void)HalKeyExitSleep();
#endif
/* power on the MAC; blocks until completion */
MAC_PwrOnReq();
HAL_ENABLE_INTERRUPTS();
/* For CC2530, T2 interrupt wont be generated when the current count is greater than
* the comparator. The interrupt is only generated when the current count is equal to
* the comparator. When the CC2530 is waking up from sleep, there is a small window
* that the count may be grater than the comparator, therefore, missing the interrupt.
* This workaround will call the T2 ISR when the current T2 count is greater than the
* comparator. The problem only occurs when POWER_SAVING is turned on, i.e. the 32KHz
* drives the chip in sleep and SYNC start is used.
*/
macMcuTimer2OverflowWorkaround();
}
else
{
/* An interrupt may have changed the sleep decision. Do not sleep at all. Turn on
* the interrupt, exit normally, and the next sleep will be allowed.
*/
HAL_ENABLE_INTERRUPTS();
}
}
}
/**************************************************************************************************
* @fn halSleepSetTimer
*
* @brief This function sets the CC2530 sleep timer compare value. First it reads and
* stores the value of the sleep timer; this value is used later to update OSAL
* timers. Then the timeout value is converted from 320 usec units to 32 kHz
* period units and the compare value is set to the timeout.
*
* input parameters
*
* @param timeout - Timeout value in 320 usec units. The sleep timer compare is set to
* this value.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSleepSetTimer(uint32 timeout)
{
uint32 ticks;
/* read the sleep timer; ST0 must be read first */
((uint8 *) &ticks)[UINT32_NDX0] = ST0;
((uint8 *) &ticks)[UINT32_NDX1] = ST1;
((uint8 *) &ticks)[UINT32_NDX2] = ST2;
((uint8 *) &ticks)[UINT32_NDX3] = 0;
/* Compute sleep timer compare value. The ratio of 32 kHz ticks to 320 usec ticks
* is 32768/3125 = 10.48576. This is nearly 671/64 = 10.484375.
*/
ticks += (timeout * 671) / 64;
/* subtract the processing time spent in function halSleep() */
ticks -= HAL_SLEEP_ADJ_TICKS;
/* set sleep timer compare; ST0 must be written last */
ST2 = ((uint8 *) &ticks)[UINT32_NDX2];
ST1 = ((uint8 *) &ticks)[UINT32_NDX1];
ST0 = ((uint8 *) &ticks)[UINT32_NDX0];
}
/**************************************************************************************************
* @fn TimerElapsed
*
* @brief Determine the number of OSAL timer ticks elapsed during sleep.
* Deprecated for CC2530 and CC2430 SoC.
*
* input parameters
*
* @param None.
*
* output parameters
*
* None.
*
* @return Number of timer ticks elapsed during sleep.
**************************************************************************************************
*/
uint32 TimerElapsed( void )
{
/* Stubs */
return (0);
}
/**************************************************************************************************
* @fn halRestoreSleepLevel
*
* @brief Restore the deepest timer sleep level.
*
* input parameters
*
* @param None
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halRestoreSleepLevel( void )
{
/* Stubs */
}
/**************************************************************************************************
* @fn halSleepTimerIsr
*
* @brief Sleep timer ISR.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
HAL_ISR_FUNCTION(halSleepTimerIsr, ST_VECTOR)
{
HAL_ENTER_ISR();
HAL_SLEEP_TIMER_CLEAR_INT();
#ifdef HAL_SLEEP_DEBUG_POWER_MODE
halSleepInt = TRUE;
#endif
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}

View File

@@ -0,0 +1,103 @@
/**************************************************************************************************
Filename: hal_startup.c
Revised: $Date: 2010-01-28 16:31:53 -0800 (Thu, 28 Jan 2010) $
Revision: $Revision: 21613 $
Description: Contains code that needs to run before main()
Copyright 2008 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
*************************************************************************************************/
#include "hal_board.h"
#include "hal_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#pragma language=extended
//
// Locate low_level_init in the CSTART module
//
#pragma location="CSTART"
//
// If the code model is banked, low_level_init must be declared
// __near_func elsa a ?BRET is performed
//
#if (__CODE_MODEL__ == 2)
__near_func __root char
#else
__root char
#endif
__low_level_init(void);
/**************************************************************************************************
* @fn __low_level_init
*
* @brief The function __low_level_init is called by the start-up code before doing
* the normal initialization of data segments. If the return value is zero,
* initialization is not performed.
*
* @param None
*
* @return 0 - don't intialize data segments / 1 - do initialization
**************************************************************************************************/
#if (__CODE_MODEL__ == 2)
__near_func __root char
#else
__root char
#endif
__low_level_init(void)
{
/*==================================*/
/* Initialize hardware. */
/*==================================*/
// Map flash bank #1 into XDATA for access to "ROM mapped as data".
MEMCTR = (MEMCTR & 0xF8) | 0x01;
/*==================================*/
/* Choose if segment initialization */
/* should be done or not. */
/* Return: 0 to omit seg_init */
/* 1 to run seg_init */
/*==================================*/
return 1;
}
#pragma language=default
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,45 @@
/**************************************************************************************************
Filename: hal_timer.c
Revised: $Date: 2010-05-28 15:26:34 -0700 (Fri, 28 May 2010) $
Revision: $Revision: 22676 $
Description: This file contains the interface to the Timer Service.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
NOTE: Z-Stack and TIMAC no longer use CC2530 Timer 1, Timer 3, and
Timer 4. The supporting timer driver module is removed and left
for the users to implement their own application timer
functions.
*********************************************************************/

View File

@@ -0,0 +1,103 @@
/**************************************************************************************************
Filename: hal_types.h
Revised: $Date: 2008-03-20 17:17:05 -0700 (Thu, 20 Mar 2008) $
Revision: $Revision: 16618 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef _HAL_TYPES_H
#define _HAL_TYPES_H
/* Texas Instruments CC2530 */
/* ------------------------------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------------------------------
*/
typedef signed char int8;
typedef unsigned char uint8;
typedef signed short int16;
typedef unsigned short uint16;
typedef signed long int32;
typedef unsigned long uint32;
typedef unsigned char bool;
typedef uint8 halDataAlign_t;
/* ------------------------------------------------------------------------------------------------
* Memory Attributes
* ------------------------------------------------------------------------------------------------
*/
/* ----------- IAR Compiler ----------- */
#ifdef __IAR_SYSTEMS_ICC__
#define CODE __code
#define XDATA __xdata
/* ----------- GNU Compiler ----------- */
#elif defined __KEIL__
#define CODE code
#define XDATA xdata
/* ----------- Unrecognized Compiler ----------- */
#else
#error "ERROR: Unknown compiler."
#endif
/* ------------------------------------------------------------------------------------------------
* Standard Defines
* ------------------------------------------------------------------------------------------------
*/
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef NULL
#define NULL 0
#endif
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,382 @@
/**************************************************************************************************
Filename: _hal_uart.c
Revised: $Date: 2009-06-12 09:16:43 -0700 (Fri, 12 Jun 2009) $
Revision: $Revision: 20142 $
Description: This file contains the interface to the H/W UART driver.
Copyright 2006-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_board_cfg.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_uart.h"
/*********************************************************************
* MACROS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
/*********************************************************************
* LOCAL FUNCTIONS
*/
#if HAL_UART_DMA
#include "_hal_uart_dma.c"
#endif
#if HAL_UART_ISR
#include "_hal_uart_isr.c"
#endif
#if HAL_UART_USB
#include "_hal_uart_usb.c"
#endif
/******************************************************************************
* @fn HalUARTInit
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTInit(void)
{
#if HAL_UART_DMA
HalUARTInitDMA();
#endif
#if HAL_UART_ISR
HalUARTInitISR();
#endif
#if HAL_UART_USB
HalUARTInitUSB();
#endif
}
/******************************************************************************
* @fn HalUARTOpen
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param port - UART port
* config - contains configuration information
*
* @return Status of the function call
*****************************************************************************/
uint8 HalUARTOpen(uint8 port, halUARTCfg_t *config)
{
(void)port;
(void)config;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) HalUARTOpenDMA(config);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) HalUARTOpenDMA(config);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) HalUARTOpenISR(config);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) HalUARTOpenISR(config);
#endif
#if (HAL_UART_USB)
HalUARTOpenUSB(config);
#endif
return HAL_UART_SUCCESS;
}
/*****************************************************************************
* @fn HalUARTRead
*
* @brief Read a buffer from the UART
*
* @param port - USART module designation
* buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
uint16 HalUARTRead(uint8 port, uint8 *buf, uint16 len)
{
(void)port;
(void)buf;
(void)len;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTReadDMA(buf, len);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTReadDMA(buf, len);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTReadISR(buf, len);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTReadISR(buf, len);
#endif
#if HAL_UART_USB
return HalUARTRx(buf, len);
#else
return 0;
#endif
}
/******************************************************************************
* @fn HalUARTWrite
*
* @brief Write a buffer to the UART.
*
* @param port - UART port
* buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
uint16 HalUARTWrite(uint8 port, uint8 *buf, uint16 len)
{
(void)port;
(void)buf;
(void)len;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTWriteDMA(buf, len);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTWriteDMA(buf, len);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTWriteISR(buf, len);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTWriteISR(buf, len);
#endif
#if HAL_UART_USB
HalUARTTx(buf, len);
return len;
#else
return 0;
#endif
}
/******************************************************************************
* @fn HalUARTSuspend
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
void HalUARTSuspend( void )
{
#if HAL_UART_DMA
HalUARTSuspendDMA();
#endif
#if HAL_UART_ISR
HalUARTSuspendISR();
#endif
}
/******************************************************************************
* @fn HalUARTResume
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
void HalUARTResume( void )
{
#if HAL_UART_DMA
HalUARTResumeDMA();
#endif
#if HAL_UART_ISR
HalUARTResumeISR();
#endif
}
/***************************************************************************************************
* @fn HalUARTPoll
*
* @brief Poll the UART.
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTPoll(void)
{
#if HAL_UART_DMA
HalUARTPollDMA();
#endif
#if HAL_UART_ISR
HalUARTPollISR();
#endif
#if HAL_UART_USB
HalUARTPollUSB();
#endif
}
/**************************************************************************************************
* @fn Hal_UART_RxBufLen()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param port - UART port
*
* @return length of current Rx Buffer
**************************************************************************************************/
uint16 Hal_UART_RxBufLen( uint8 port )
{
(void)port;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTRxAvailDMA();
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTRxAvailDMA();
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTRxAvailISR();
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTRxAvailISR();
#endif
#if HAL_UART_USB
return HalUARTRxAvailUSB();
#else
return 0;
#endif
}
/******************************************************************************
******************************************************************************/
/****************************************************************
*函数功能 初始化串口1
*入口参数 :无
*返 回 值 :无
*说 明 57600-8-n-1
****************************************************************/
void HalUART1HwInit(void)
{
CLKCONCMD &= ~0x40; //晶振
while(!(SLEEPSTA & 0x40)); //等待晶振稳定
CLKCONCMD &= ~0x47; //TICHSPD128分频CLKSPD不分频
SLEEPCMD |= 0x04; //关闭不用的RC振荡器
PERCFG |= 0x02; //位置1 P0口
P1SEL |= 0xF0; //P0用作串口
P2DIR |= 0X80; //P0优先作为串口1
U1CSR |= 0x80; //UART方式
//*********************************************************
// CC2530 UART1 BAUD设置
//*********************************************************
//设置博特率为 9600
U1GCR |= 8; //baud_e
U1BAUD |= 59; //波特率设为 9600
//设置博特率为 38400
//U1GCR |= 10; //baud_e
//U1BAUD |= 59; //波特率设为 38400
//设置博特率为 115200
//U1GCR |= 11; //baud_e
//U1BAUD |= 216; //波特率设为 115200
UTX1IF = 0;
U1CSR |= 0X40; //允许接收
IEN0 |= 0x88; //开总中断,接收中断
}
void HalUART1HwTxByte(uint8 v)
{
U1DBUF = v;
while(UTX1IF == 0);
UTX1IF = 0;
}
void HalUART1HwTx(uint8 *Data, int len)
{
while(len-- > 0)
{
U1DBUF = *Data++;
while(UTX1IF == 0);
UTX1IF = 0;
}
}
uint8 HalUART1HwRxByte(void)
{
uint8 c;
uint8 status;
status = U1CSR;
U1CSR |= 0x40;
while (!URX1IF);
c = U1DBUF;
URX1IF = 0;
U1CSR = status;
return c;
}
uint8 *HalUART1HwRx(uint8 *data, int maxLen)
{
uint8 *ret = data;
while(maxLen-- > 0)
*data++ = HalUART1HwRxByte();
return ret;
}

View File

@@ -0,0 +1,261 @@
#include "sht10.h"
/***********************************************
**Function Name: SHT10_Transstart
**Description: 发送开始时序
**
** generates a transmission start
** _____ ________
** DATA: |_______|
** ___ ___
** SCK : ___| |___| |______
**Input Parameters: 无
**Output Parameters: 无
************************************************/
void SHT10_Transstart(void)
{
SDIO_DIR_OUT;
SCLK_DIR_OUT;
SCLK_LOW;
SDIO_HIGH;
DELAY(DURATION1);
DELAY(DURATION1);
SCLK_HIGH;
DELAY(DURATION1);
SDIO_LOW;
DELAY(DURATION1);
SCLK_LOW;
DELAY(DURATION1);
SCLK_HIGH;
DELAY(DURATION1);
SDIO_HIGH;
DELAY(DURATION1);
SCLK_LOW;
}
/**********************************************************************************************************
**Function Name: SHT10_WriteByte
**Description: 写时序
**Input Parameters: 无
**Output Parameters: 无
**************************************************************************************/
unsigned char SHT10_WriteByte(unsigned char data)
{
unsigned char i;
SDIO_DIR_OUT;
SCLK_DIR_OUT;
for(i=0x80;i>0;i=(i>>1)) //shift bit for masking
{
if(i&data)
SDIO_HIGH; //masking value with i , write to SENSI-BUS
else
SDIO_LOW;
DELAY(DURATION1); //pulswith approx. 5 us
SCLK_HIGH; //clk for SENSI-BUS
DELAY(DURATION1); //pulswith approx. 5 us
SCLK_LOW;
DELAY(DURATION1); //pulswith approx. 5 us
}
SDIO_HIGH; //release DATA-line
//pulswith approx. 5 us
SDIO_DIR_IN; //Change SDA to be input
DELAY(DURATION1);
SCLK_HIGH; //clk for SENSI-BUS
if(READ_SDIO)
{
return 1; //error=1 in case of no acknowledge
}
DELAY(DURATION1); //pulswith approx. 5 us
SCLK_LOW;
return 0;
}
/**********************************************************************************************************
**Function Name: SHT10_ReadByte
**Description: 读时序
**Input Parameters: ack--->reads a byte form the Sensibus and gives an acknowledge in case of "ack=1"
**Output Parameters: 无
**********************************************************************************************************/
unsigned char SHT10_ReadByte(unsigned char ack)
{
unsigned char i,val=0;
SDIO_DIR_OUT;
SDIO_HIGH; //release DATA-line
SDIO_DIR_IN;
for(i=0x80;i>0;i=(i>>1)) //shift bit for masking
{
SCLK_HIGH; //clk for SENSI-BUS
DELAY(DURATION1);
if(READ_SDIO)
val=(val|i); //read bit
SCLK_LOW;
DELAY(DURATION1);
}
SDIO_DIR_OUT;
if(ack) //in case of "ack==1" pull down DATA-Line
SDIO_LOW;
else
SDIO_HIGH;
SCLK_HIGH; //clk #9 for ack
DELAY(DURATION1); //pulswith approx. 5 us
SCLK_LOW;
DELAY(DURATION1);
SDIO_HIGH; //release DATA-line
DELAY(DURATION1);
SDIO_DIR_IN;
return val;
}
/**********************************************************************************************************
**Function Name: SHT10_Connectionreset
**Description: 通讯复位时序
** communication reset: DATA-line=1 and at least 9 SCK cycles followed by transstart
** _____________________________________________________ ________
** DATA: |_______|
** _ _ _ _ _ _ _ _ _ ___ ___
** SCK : __| |__| |__| |__| |__| |__| |__| |__| |__| |______| |___| |______
**Input Parameters: 无
**Output Parameters: 无
**********************************************************************************************************/
void SHT10_Connectionreset(void)
{
unsigned char ClkCnt;
SDIO_DIR_OUT;
SCLK_DIR_OUT;
SDIO_HIGH;
SCLK_LOW; //Initial state
DELAY(DURATION1);
for(ClkCnt=0;ClkCnt<9;ClkCnt++) //9 SCK cycles
{
SCLK_HIGH;
DELAY(DURATION1);
SCLK_LOW;
DELAY(DURATION1);
}
SHT10_Transstart(); //transmission start
}
/**********************************************************************************************************
**Function Name: SHT10_Softreset
**Description: 软件复位时序resets the sensor by a softreset
**Input Parameters: 无
**Output Parameters: 无
**********************************************************************************************************/
unsigned char SHT10_Softreset(void)
{
unsigned char error=0;
SHT10_Connectionreset(); //reset communication
error+=SHT10_WriteByte(CMD_Soft_Reset); //send RESET-command to sensor
return error; //error=1 in case of no response form the sensor
}
/**********************************************************************************************************
**Function Name: SHT10_WriteStatusReg
**Description: 写状态寄存器
**Input Parameters: *p_value
**Output Parameters: 无
**********************************************************************************************************/
unsigned char SHT10_WriteStatusReg(unsigned char RegVlaue)
{
unsigned char error=0;
SHT10_Transstart(); //transmission start
error+=SHT10_WriteByte(CMD_Write_STATUS_REG); //send command to sensor
error+=SHT10_WriteByte(RegVlaue); //send value of status register
return error; //error>=1 in case of no response form the sensor
}
unsigned char SHT10_ReadStatusReg(void)
{
unsigned char tmp=0;
SHT10_Transstart(); //transmission start
SHT10_WriteByte(CMD_Read_STATUS_REG); //send command to sensor
tmp = SHT10_ReadByte(ACK); //send value of status register
return tmp; //error>=1 in case of no response form the sensor
}
/**********************************************************************************************************
**Function Name: SHT10_Mearsure
**Description: 读时序 makes a measurement (humidity/temperature) with checksum
**Input Parameters: *p_value ,*p_checknum ,mode
**Output Parameters: 无
**********************************************************************************************************/
unsigned char SHT10_Measure(unsigned int *p_value, unsigned char *p_checksum, unsigned char mode)
{
unsigned error=0;
unsigned int i;
SHT10_Transstart(); //transmission start
switch(mode)
{ //send command to sensor
case TEMPERATURE:
error+=SHT10_WriteByte(CMD_TEM_MES);
break;
case HUMIDITY:
error+=SHT10_WriteByte(CMD_HUMI_MES);
break;
}
SDIO_DIR_IN;
for(i=0;i<1500;i++) //wait until sensor has finished the measurement
{
if(READ_SDIO == 0)
break;
else
DELAY(100);
}
if(READ_SDIO)
error+=1; //or timeout (~2 sec.) is reached
*(p_value)=SHT10_ReadByte(ACK); //read the first byte (MSB)
*(p_value)=SHT10_ReadByte(ACK)+(*(p_value)<<8); //read the second byte (LSB)
*p_checksum=SHT10_ReadByte(noACK); //read checksum
return(error);
}
/**********************************************************************************************************
**Function Name: SHT10_Calculate
**Description: 计算
**Input Parameters: humi [Ticks] (12 bit)
** temp [Ticks] (14 bit)
**Output Parameters: humi [%RH]
** temp []
**********************************************************************************************************/
float SHT10_Calculate(unsigned int data,unsigned char mode)
{
const float C1=-4.0; // for 8 Bit
const float C2=+0.648; // for 8 Bit
const float C3=-0.0000072; // for 8 Bit
const float D1=-39.6; // for 12 Bit @ 3V
const float D2=+0.04; // for 12 Bit @ 3V
const float T1=0.01; // for 8 bit
const float T2=0.00128; // for 8 bit
float rh_lin; // rh_lin: Humidity linear
float rh_true; // rh_true: Temperature compensated humidity
float t_C; // t_C : Temperature []
if (mode == 1)
{
t_C=data*D2+D1; //calc. temperature from ticks to []
return (t_C);
}
else if(mode == 2)
{
rh_lin=C3*data*data + C2*data + C1; //calc. humidity from ticks to [%RH]
rh_true=(t_C-25)*(T1+T2*data)+rh_lin; //calc. temperature compensated humidity [%RH]
if(rh_true>100)rh_true=100; //cut if the value is outside of
if(rh_true<0.1)rh_true=0.1; //the physical possible range
return (rh_true);
}
else
return 0;
}
/**********************************************************************************************************
**Function Name: SHT10_init
**Description: 初始化SHT10
**********************************************************************************************************/
void SHT10_init(unsigned int Initial_Reg)
{
SHT10_Connectionreset();
SHT10_WriteStatusReg(Initial_Reg);
}

View File

@@ -0,0 +1,47 @@
#include "uart_rx.h"
static uchar temp;
/****************************************************************
*函数功能 初始化串口1
*入口参数 :无
*返 回 值 :无
*说 明 57600-8-n-1
****************************************************************/
void initUARTrx(void)
{
CLKCONCMD &= ~0x40; //晶振
while(!(SLEEPSTA & 0x40)); //等待晶振稳定
CLKCONCMD &= ~0x47; //TICHSPD128分频CLKSPD不分频
SLEEPCMD |= 0x04; //关闭不用的RC振荡器
PERCFG = 0x00; //位置1 P0口
P0SEL = 0x3c; //P0用作串口
U0CSR |= 0x80; //UART方式
U0GCR |= 10; //baud_e
U0BAUD |= 59; //波特率设为57600
UTX0IF = 1;
U0CSR |= 0X40; //允许接收
IEN0 |= 0x84; //开总中断,接收中断
}
uchar ReceiveData(void){
return(temp);
}
/****************************************************************
*函数功能 :串口接收一个字符
*入口参数 : 无
*返 回 值 :无
*说 明 :接收完成后打开接收
****************************************************************/
#pragma vector = URX0_VECTOR
__interrupt void UART0_ISR(void)
{
URX0IF = 0; //清中断标志
temp = U0DBUF;
}

View File

@@ -0,0 +1,418 @@
/**************************************************************************************************
Filename: _hal_uart_usb.c
Revised: $Date: 2010-03-10 20:36:55 -0800 (Wed, 10 Mar 2010) $
Revision: $Revision: 21890 $
Description: This file contains the interface to the H/W UART driver by USB.
Copyright 2009-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_uart.h"
#if defined MT_TASK
#include "MT_UART.h"
#endif
#include "usb_board_cfg.h"
#include "usb_cdc.h"
#include "usb_cdc_hooks.h"
#include "usb_firmware_library_config.h"
#include "usb_firmware_library_headers.h"
/*********************************************************************
* MACROS
*/
#if !defined HAL_UART_BAUD_RATE
#define HAL_UART_BAUD_RATE 115200
#endif
// The timeout tick is at 32-kHz, so multiply msecs by 33.
#define HAL_UART_MSECS_TO_TICKS 33
#if defined MT_TASK
#define HAL_UART_USB_HIGH MT_UART_DEFAULT_THRESHOLD
#define HAL_UART_USB_IDLE (MT_UART_DEFAULT_IDLE_TIMEOUT * HAL_UART_MSECS_TO_TICKS)
#define HAL_UART_USB_RX_MAX MT_UART_DEFAULT_MAX_RX_BUFF
#else
#if !defined HAL_UART_USB_HIGH
#define HAL_UART_USB_HIGH (HAL_UART_USB_RX_MAX / 2 - 16)
#endif
#if !defined HAL_UART_USB_IDLE
#define HAL_UART_USB_IDLE (6 * HAL_UART_MSECS_TO_TICKS)
#endif
#if !defined HAL_UART_USB_RX_MAX
#define HAL_UART_USB_RX_MAX 128
#endif
#endif
// Max USB packet size, per specification; see also usb_cdc_descriptor.s51
#if !defined HAL_UART_USB_TX_MAX
#define HAL_UART_USB_TX_MAX 64
#endif
/***********************************************************************************
* EXTERNAL VARIABLES
*/
/***********************************************************************************
* GLOBAL VARIABLES
*/
/***********************************************************************************
* LOCAL DATA
*/
static uint8 halUartRxH, halUartRxT, halUartRxQ[256];
static uint8 halUartTxH, halUartTxT, halUartTxQ[256];
#if !defined HAL_SB_BOOT_CODE
static uint8 rxTick;
static uint8 rxShdw;
static uint8 txMT;
static halUARTCBack_t uartCB;
#endif
/***********************************************************************************
* LOCAL FUNCTIONS
*/
static void HalUARTInitUSB(void);
static void HalUARTPollUSB(void);
static void halUartPollEvt(void);
static void halUartPollRx(void);
static void halUartPollTx(void);
/******************************************************************************
* FUNCTIONS
*/
/***********************************************************************************
* @fn usbUartInitUSB
*
* @brief USB UART init function.
* - Set initial line decoding to 8/NONE/1.
* - Initialise the USB Firmware Library and the USB controller.
*
* @param none
*
* @return none
*/
void HalUARTInitUSB(void)
{
// Set default line coding.
currentLineCoding.dteRate = HAL_UART_BAUD_RATE;
currentLineCoding.charFormat = CDC_CHAR_FORMAT_1_STOP_BIT;
currentLineCoding.parityType = CDC_PARITY_TYPE_NONE;
currentLineCoding.dataBits = 8;
// Init USB library
usbfwInit();
// Initialize the USB interrupt handler with bit mask containing all processed USBIRQ events
usbirqInit(0xFFFF);
// Enable pullup on D+
HAL_USB_PULLUP_ENABLE();
#if !defined HAL_SB_BOOT_CODE
txMT = TRUE;
#endif
}
/******************************************************************************
* @fn HalUARTUnInitUSB
*
* @brief UnInitialize the USB.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTUnInitUSB(void)
{
P2IEN = 0;
IEN2 = 0;
HAL_USB_PULLUP_DISABLE();
HAL_USB_DISABLE;
}
/******************************************************************************
* @fn HalUARTOpenUSB
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param config - contains configuration information
*
* @return none
*****************************************************************************/
static void HalUARTOpenUSB(halUARTCfg_t *config)
{
// Synchronize initial value to any value between 0 and 255
halUartRxH = halUartRxT;
#if !defined HAL_SB_BOOT_CODE
uartCB = config->callBackFunc;
#else
(void)config;
#endif
}
/***********************************************************************************
* @fn HalUartPollUSB
*
* @brief The USB UART main task function. Should be called from the OSAL main loop.
*
* @param none
*
* @return none
*/
void HalUARTPollUSB(void)
{
halUartPollEvt();
halUartPollRx();
halUartPollTx();
}
uint8 HalUARTRx(uint8 *buf, uint8 max);
uint8 HalUARTRx(uint8 *buf, uint8 max)
{
uint8 cnt = 0;
while ((halUartRxH != halUartRxT) && (cnt < max))
{
*buf++ = halUartRxQ[halUartRxH++];
cnt++;
}
return cnt;
}
void HalUARTTx(uint8 *buf, uint8 cnt);
void HalUARTTx(uint8 *buf, uint8 cnt)
{
while (cnt--)
{
halUartTxQ[halUartTxT++] = *buf++;
}
#if !defined HAL_SB_BOOT_CODE
txMT = FALSE;
#endif
}
/**************************************************************************************************
* @fn HalUARTRxAvailUSB()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param none
*
* @return length of current Rx Buffer
**************************************************************************************************/
static uint16 HalUARTRxAvailUSB(void)
{
return ((halUartRxT >= halUartRxH)?
halUartRxT - halUartRxH : sizeof(halUartRxQ) - halUartRxH + halUartRxT);
}
/***********************************************************************************
* @fn halUartPollEvt
*
* @brief Poll for USB events which are not directly related to the UART.
*
* @param none
*
* @return none
*/
static void halUartPollEvt(void)
{
// Handle reset signaling on the bus
if (USBIRQ_GET_EVENT_MASK() & USBIRQ_EVENT_RESET)
{
USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_RESET);
usbfwResetHandler();
}
// Handle packets on EP0
if (USBIRQ_GET_EVENT_MASK() & USBIRQ_EVENT_SETUP)
{
USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_SETUP);
usbfwSetupHandler();
}
// Handle USB suspend
if (USBIRQ_GET_EVENT_MASK() & USBIRQ_EVENT_SUSPEND)
{
// Clear USB suspend interrupt
USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_SUSPEND);
#if HAL_UART_USB_SUSPEND
// Take the chip into PM1 until a USB resume is deteceted.
usbsuspEnter();
#endif
// Running again; first clear RESUME interrupt
USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_RESUME);
}
}
/***********************************************************************************
* @fn halUartPollRx
*
* @brief Poll for data from USB.
*
* @param none
*
* @return none
*/
static void halUartPollRx(void)
{
uint8 cnt;
uint8 ep = USBFW_GET_SELECTED_ENDPOINT();
USBFW_SELECT_ENDPOINT(4);
// If the OUT endpoint has received a complete packet.
if (USBFW_OUT_ENDPOINT_DISARMED())
{
halIntState_t intState;
HAL_ENTER_CRITICAL_SECTION(intState);
// Get length of USB packet, this operation must not be interrupted.
cnt = USBFW_GET_OUT_ENDPOINT_COUNT_LOW();
cnt += USBFW_GET_OUT_ENDPOINT_COUNT_HIGH() >> 8;
HAL_EXIT_CRITICAL_SECTION(intState);
while (cnt--)
{
halUartRxQ[halUartRxT++] = USBF4;
}
USBFW_ARM_OUT_ENDPOINT();
#if !defined HAL_SB_BOOT_CODE
// If the USB has transferred in more Rx bytes, reset the Rx idle timer.
// Re-sync the shadow on any 1st byte(s) received.
if (rxTick == 0)
{
rxShdw = ST0;
}
rxTick = HAL_UART_USB_IDLE;
#endif
}
#if !defined HAL_SB_BOOT_CODE
else if (rxTick)
{
// Use the LSB of the sleep timer (ST0 must be read first anyway).
uint8 decr = ST0 - rxShdw;
if (rxTick > decr)
{
rxTick -= decr;
rxShdw = ST0;
}
else
{
rxTick = 0;
}
}
{
uint8 evt = 0;
cnt = halUartRxT - halUartRxH;
if (cnt >= HAL_UART_USB_HIGH)
{
evt = HAL_UART_RX_ABOUT_FULL;
}
else if (cnt && !rxTick)
{
evt = HAL_UART_RX_TIMEOUT;
}
if (evt && (NULL != uartCB))
{
uartCB(0, evt);
}
}
#endif
USBFW_SELECT_ENDPOINT(ep);
}
/***********************************************************************************
* @fn halUartPollTx
*
* @brief Poll for data to USB.
*
* @param none
*
* @return none
*/
static void halUartPollTx(void)
{
uint8 ep = USBFW_GET_SELECTED_ENDPOINT();
USBFW_SELECT_ENDPOINT(4);
// If the IN endpoint is ready to accept data.
if (USBFW_IN_ENDPOINT_DISARMED())
{
if (halUartTxT == halUartTxH)
{
#if !defined HAL_SB_BOOT_CODE
if (!txMT)
{
txMT = TRUE;
uartCB(0, HAL_UART_TX_EMPTY);
}
#endif
}
else
{
uint8 max = HAL_UART_USB_TX_MAX;
do
{
USBF4 = halUartTxQ[halUartTxH++];
} while ((halUartTxH != halUartTxT) && (0 != --max));
USBFW_ARM_IN_ENDPOINT();
}
}
USBFW_SELECT_ENDPOINT(ep);
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,240 @@
/**************************************************************************************************
Filename: hal_adc.c
Revised: $Date: 2010-03-12 16:10:36 -0800 (Fri, 12 Mar 2010) $
Revision: $Revision: 21910 $
Description: This file contains the interface to the HAL ADC.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_adc.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_ADC_EOC 0x80 /* End of Conversion bit */
#define HAL_ADC_START 0x40 /* Starts Conversion */
#define HAL_ADC_STSEL_EXT 0x00 /* External Trigger */
#define HAL_ADC_STSEL_FULL 0x10 /* Full Speed, No Trigger */
#define HAL_ADC_STSEL_T1C0 0x20 /* Timer1, Channel 0 Compare Event Trigger */
#define HAL_ADC_STSEL_ST 0x30 /* ADCCON1.ST =1 Trigger */
#define HAL_ADC_RAND_NORM 0x00 /* Normal Operation */
#define HAL_ADC_RAND_LFSR 0x04 /* Clock LFSR */
#define HAL_ADC_RAND_SEED 0x08 /* Seed Modulator */
#define HAL_ADC_RAND_STOP 0x0c /* Stop Random Generator */
#define HAL_ADC_RAND_BITS 0x0c /* Bits [3:2] */
#define HAL_ADC_DEC_064 0x00 /* Decimate by 64 : 8-bit resolution */
#define HAL_ADC_DEC_128 0x10 /* Decimate by 128 : 10-bit resolution */
#define HAL_ADC_DEC_256 0x20 /* Decimate by 256 : 12-bit resolution */
#define HAL_ADC_DEC_512 0x30 /* Decimate by 512 : 14-bit resolution */
#define HAL_ADC_DEC_BITS 0x30 /* Bits [5:4] */
#define HAL_ADC_STSEL HAL_ADC_STSEL_ST
#define HAL_ADC_RAND_GEN HAL_ADC_RAND_STOP
#define HAL_ADC_REF_VOLT HAL_ADC_REF_AVDD
#define HAL_ADC_DEC_RATE HAL_ADC_DEC_064
#define HAL_ADC_SCHN HAL_ADC_CHN_VDD3
#define HAL_ADC_ECHN HAL_ADC_CHN_GND
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
#if (HAL_ADC == TRUE)
static uint8 adcRef;
#endif
/**************************************************************************************************
* @fn HalAdcInit
*
* @brief Initialize ADC Service
*
* @param None
*
* @return None
**************************************************************************************************/
void HalAdcInit (void)
{
#if (HAL_ADC == TRUE)
adcRef = HAL_ADC_REF_VOLT;
#endif
}
/**************************************************************************************************
* @fn HalAdcRead
*
* @brief Read the ADC based on given channel and resolution
*
* @param channel - channel where ADC will be read
* @param resolution - the resolution of the value
*
* @return 16 bit value of the ADC in offset binary format.
*
* Note that the ADC is "bipolar", which means the GND (0V) level is mid-scale.
* Note2: This function assumes that ADCCON3 contains the voltage reference.
**************************************************************************************************/
uint16 HalAdcRead (uint8 channel, uint8 resolution)
{
int16 reading = 0;
#if (HAL_ADC == TRUE)
uint8 i, resbits;
uint8 adcChannel = 1;
/*
* If Analog input channel is AIN0..AIN7, make sure corresponing P0 I/O pin is enabled. The code
* does NOT disable the pin at the end of this function. I think it is better to leave the pin
* enabled because the results will be more accurate. Because of the inherent capacitance on the
* pin, it takes time for the voltage on the pin to charge up to its steady-state level. If
* HalAdcRead() has to turn on the pin for every conversion, the results may show a lower voltage
* than actuality because the pin did not have time to fully charge.
*/
if (channel < 8)
{
for (i=0; i < channel; i++)
{
adcChannel <<= 1;
}
}
/* Enable channel */
ADCCFG |= adcChannel;
/* Convert resolution to decimation rate */
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
resbits = HAL_ADC_DEC_064;
break;
case HAL_ADC_RESOLUTION_10:
resbits = HAL_ADC_DEC_128;
break;
case HAL_ADC_RESOLUTION_12:
resbits = HAL_ADC_DEC_256;
break;
case HAL_ADC_RESOLUTION_14:
default:
resbits = HAL_ADC_DEC_512;
break;
}
/* writing to this register starts the extra conversion */
ADCCON3 = channel | resbits | adcRef;
/* Wait for the conversion to be done */
while (!(ADCCON1 & HAL_ADC_EOC));
/* Disable channel after done conversion */
ADCCFG &= (adcChannel ^ 0xFF);
/* Read the result */
reading = (int16) (ADCL);
reading |= (int16) (ADCH << 8);
/* Treat small negative as 0 */
if (reading < 0)
reading = 0;
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
reading >>= 8;
break;
case HAL_ADC_RESOLUTION_10:
reading >>= 6;
break;
case HAL_ADC_RESOLUTION_12:
reading >>= 4;
break;
case HAL_ADC_RESOLUTION_14:
default:
reading >>= 2;
break;
}
#else
// unused arguments
(void) channel;
(void) resolution;
#endif
return ((uint16)reading);
}
/**************************************************************************************************
* @fn HalAdcSetReference
*
* @brief Sets the reference voltage for the ADC and initializes the service
*
* @param reference - the reference voltage to be used by the ADC
*
* @return none
*
**************************************************************************************************/
void HalAdcSetReference ( uint8 reference )
{
#if (HAL_ADC == TRUE)
adcRef = reference;
#endif
}
/*********************************************************************
* @fn HalAdcCheckVdd
*
* @brief Check for minimum Vdd specified.
*
* @param vdd - The board-specific Vdd reading to check for.
*
* @return TRUE if the Vdd measured is greater than the 'vdd' minimum parameter;
* FALSE if not.
*
*********************************************************************/
bool HalAdcCheckVdd(uint8 vdd)
{
ADCCON3 = 0x0F;
while (!(ADCCON1 & 0x80));
return (ADCH > vdd);
}
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,124 @@
/**************************************************************************************************
Filename: hal_aes.h
Revised: $Date: 2010-01-11 14:10:07 -0800 (Mon, 11 Jan 2010) $
Revision: $Revision: 21476 $
Description: Support for HW/SW AES encryption.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_AES_H_
#define HAL_AES_H_
#include "ZComDef.h"
#define STATE_BLENGTH 16 // Number of bytes in State
#define KEY_BLENGTH 16 // Number of bytes in Key
#define KEY_EXP_LENGTH 176 // Nb * (Nr+1) * 4
/* AES Engine is default to hardware AES. To turn on software AES, #define one of the followings:
* #define SOFTWARE_AES TRUE, uses software aes ( slowest setting )
* #define SW_AES_AND_KEY_EXP TRUE, enables software aes with key expansion ( improves speed at the cost of 176 bytes of data (RAM) )
*/
#if ((defined SOFTWARE_AES) && (SOFTWARE_AES == TRUE)) && ((defined SW_AES_AND_KEY_EXP) && (SW_AES_AND_KEY_EXP == TRUE))
#error "SOFTWARE_AES and SW_AES_AND_KEY_EXP cannot be both defined."
#endif
extern void HalAesInit( void );
extern void AesLoadBlock( uint8 * );
extern void AesStartBlock( uint8 *, uint8 * );
extern void AesStartShortBlock( uint8 *, uint8 * );
extern void AesLoadIV(uint8 *);
extern void AesDmaSetup( uint8 *, uint16, uint8 *, uint16 );
extern void AesLoadKey( uint8 * );
extern void (*pSspAesEncrypt)( uint8 *, uint8 * );
extern void ssp_HW_KeyInit (uint8 *);
extern void sspKeyExpansion (uint8 *, uint8 *);
extern void sspAesEncryptHW (uint8 *, uint8 *);
extern void sspAesEncryptKeyExp (uint8 *, uint8 *);
extern void sspAesEncryptBasic (uint8 *, uint8 *);
extern void sspAesEncrypt( uint8 *key, uint8 *buf );
#define AES_BUSY 0x08
#define ENCRYPT 0x00
#define DECRYPT 0x01
// Macro for setting the mode of the AES operation
#define AES_SETMODE(mode) do { ENCCS &= ~0x70; ENCCS |= mode; } while (0)
// _mode_ is one of
#define CBC 0x00
#define CFB 0x10
#define OFB 0x20
#define CTR 0x30
#define ECB 0x40
#define CBC_MAC 0x50
// Macro for starting or stopping encryption or decryption
#define AES_SET_ENCR_DECR_KEY_IV(mode) \
do { \
ENCCS = (ENCCS & ~0x07) | mode \
} while(0)
// Where _mode_ is one of
#define AES_ENCRYPT 0x00;
#define AES_DECRYPT 0x02;
#define AES_LOAD_KEY 0x04;
#define AES_LOAD_IV 0x06;
// Macro for starting the AES module for either encryption, decryption,
// key or initialisation vector loading.
#define AES_START() ENCCS |= 0x01
/* Used by DMA macros to shift 1 to create a mask for DMA registers. */
#define HAL_DMA_AES_IN 1
#define HAL_DMA_AES_OUT 2
/* AES registers */
#define HAL_AES_IN_ADDR 0x70B1
#define HAL_AES_OUT_ADDR 0x70B2
#if !defined (HAL_AES_DMA) || (HAL_AES_DMA == FALSE)
#define HAL_AES_DELAY() \
do { \
uint8 delay = 15; \
while(delay--); \
} while(0)
#endif
// End of CC2530 hardware AES engine definitions
#endif // HAL_AES_H_

View File

@@ -0,0 +1,349 @@
/**************************************************************************************************
Filename: hal_board_cfg.h
Revised: $Date: 2010-06-24 11:52:41 -0700 (Thu, 24 Jun 2010) $
Revision: $Revision: 22814 $
Description: Declarations for the CC2531 USB dongle.
Copyright 2009-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_BOARD_CFG_H
#define HAL_BOARD_CFG_H
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "usb_board_cfg.h"
/* ------------------------------------------------------------------------------------------------
* CC2590/CC2591 support
*
* Define HAL_PA_LNA_CC2590 if CC2530+CC2590EM is used
* Define HAL_PA_LNA if CC2530+CC2591EM is used
* Note that only one of them can be defined
* ------------------------------------------------------------------------------------------------
*/
#define xHAL_PA_LNA
#define xHAL_PA_LNA_CC2590
/* ------------------------------------------------------------------------------------------------
* Board Indentifier
*
* Define the Board Identifier to HAL_BOARD_CC2530EB_REV13 for SmartRF05 EB 1.3 board
* ------------------------------------------------------------------------------------------------
*/
#if !defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_BOARD_CC2530EB_REV13)
#define HAL_BOARD_CC2530EB_REV17
#endif
#define HAL_BOARD_CC2530USB
/* ------------------------------------------------------------------------------------------------
* Clock Speed
* ------------------------------------------------------------------------------------------------
*/
#define HAL_CPU_CLOCK_MHZ 32
/* This flag should be defined if the SoC uses the 32MHz crystal
* as the main clock source (instead of DCO).
*/
#define HAL_CLOCK_CRYSTAL
#define OSC32K_CRYSTAL_INSTALLED FALSE
/* 32 kHz clock source select in CLKCONCMD */
#if !defined (OSC32K_CRYSTAL_INSTALLED) || (defined (OSC32K_CRYSTAL_INSTALLED) && (OSC32K_CRYSTAL_INSTALLED == TRUE))
#define OSC_32KHZ 0x00 /* external 32 KHz xosc */
#else
#define OSC_32KHZ 0x80 /* internal 32 KHz rcosc */
#endif
#define HAL_CLOCK_STABLE() st( while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); )
/* ------------------------------------------------------------------------------------------------
* LED Configuration
* ------------------------------------------------------------------------------------------------
*/
#define HAL_NUM_LEDS 2
#define HAL_LED_BLINK_DELAY() st( { volatile uint32 i; for (i=0; i<0x5800; i++) { }; } )
/* 1 - Green */
#define LED1_BV BV(0)
#define LED1_SBIT P0_0
#define LED1_DDR P0DIR
#define LED1_POLARITY ACTIVE_LOW
/* 2 - Red */
#define LED2_BV BV(1)
#define LED2_SBIT P1_1
#define LED2_DDR P1DIR
#define LED2_POLARITY ACTIVE_HIGH
/* ------------------------------------------------------------------------------------------------
* Push Button Configuration
* ------------------------------------------------------------------------------------------------
*/
#define ACTIVE_LOW !
#define ACTIVE_HIGH !! /* double negation forces result to be '1' */
/* S1 */
#define PUSH1_BV BV(2)
#define PUSH1_SBIT P1_2
#define PUSH1_POLARITY ACTIVE_LOW
/* S2 */
#define PUSH2_BV BV(3)
#define PUSH2_SBIT P1_3
#define PUSH2_POLARITY ACTIVE_LOW
/* ------------------------------------------------------------------------------------------------
* OSAL NV implemented by internal flash pages.
* ------------------------------------------------------------------------------------------------
*/
// Flash is partitioned into 8 banks of 32 KB or 16 pages.
#define HAL_FLASH_PAGE_PER_BANK 16
// Flash is constructed of 128 pages of 2 KB.
#define HAL_FLASH_PAGE_SIZE 2048
#define HAL_FLASH_WORD_SIZE 4
// CODE banks get mapped into the XDATA range 8000-FFFF.
#define HAL_FLASH_PAGE_MAP 0x8000
// The last 16 bytes of the last available page are reserved for flash lock bits.
// NV page definitions must coincide with segment declaration in project *.xcl file.
#if defined NON_BANKED
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 30
#define HAL_NV_PAGE_CNT 2
#else
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 126
#define HAL_NV_PAGE_CNT 6
#endif
// Re-defining Z_EXTADDR_LEN here so as not to include a Z-Stack .h file.
#define HAL_FLASH_IEEE_SIZE 8
#define HAL_FLASH_IEEE_PAGE (HAL_NV_PAGE_END+1)
#define HAL_FLASH_IEEE_OSET (HAL_FLASH_PAGE_SIZE - HAL_FLASH_LOCK_BITS - HAL_FLASH_IEEE_SIZE)
#define HAL_INFOP_IEEE_OSET 0xC
#define HAL_FLASH_DEV_PRIVATE_KEY_OSET 0x7D2
#define HAL_FLASH_CA_PUBLIC_KEY_OSET 0x7BC
#define HAL_FLASH_IMPLICIT_CERT_OSET 0x78C
#define HAL_NV_PAGE_BEG (HAL_NV_PAGE_END-HAL_NV_PAGE_CNT+1)
// Used by DMA macros to shift 1 to create a mask for DMA registers.
#define HAL_NV_DMA_CH 0
#define HAL_DMA_CH_RX 3
#define HAL_DMA_CH_TX 4
#define HAL_NV_DMA_GET_DESC() HAL_DMA_GET_DESC0()
#define HAL_NV_DMA_SET_ADDR(a) HAL_DMA_SET_ADDR_DESC0((a))
/* ------------------------------------------------------------------------------------------------
* Serial Boot Loader: reserving the first 4 pages of flash and other memory in cc2530-sb.xcl.
* ------------------------------------------------------------------------------------------------
*/
#define HAL_SB_IMG_ADDR 0x2000
#define HAL_SB_CRC_ADDR 0x2090
// Size of internal flash less 4 pages for boot loader, 6 pages for NV, & 1 page for lock bits.
#define HAL_SB_IMG_SIZE (0x40000 - 0x2000 - 0x3000 - 0x0800)
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/* ----------- Cache Prefetch control ---------- */
#define PREFETCH_ENABLE() st( FCTL = 0x08; )
#define PREFETCH_DISABLE() st( FCTL = 0x04; )
/* ----------- Board Initialization ---------- */
#define HAL_BOARD_INIT() \
{ \
uint16 i; \
\
SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \
while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \
asm("NOP"); /* chip bug workaround */ \
for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \
CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \
SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \
\
/* Turn on cache prefetch mode */ \
PREFETCH_ENABLE(); \
\
HAL_TURN_OFF_LED1(); \
LED1_DDR |= LED1_BV; \
HAL_TURN_OFF_LED2(); \
LED2_DDR |= LED2_BV; \
}
/* ----------- Debounce ---------- */
#define HAL_DEBOUNCE(expr) { int i; for (i=0; i<500; i++) { if (!(expr)) i = 0; } }
/* ----------- Push Buttons ---------- */
#define HAL_PUSH_BUTTON1() (PUSH1_POLARITY (PUSH1_SBIT))
#define HAL_PUSH_BUTTON2() (PUSH2_POLARITY (PUSH2_SBIT))
#define HAL_PUSH_BUTTON3() (0)
#define HAL_PUSH_BUTTON4() (0)
#define HAL_PUSH_BUTTON5() (0)
#define HAL_PUSH_BUTTON6() (0)
/* ----------- LED's ---------- */
#define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); )
#define HAL_TURN_OFF_LED2() st( LED2_SBIT = LED2_POLARITY (0); )
#define HAL_TURN_OFF_LED3() HAL_TURN_OFF_LED1()
#define HAL_TURN_OFF_LED4() HAL_TURN_OFF_LED2()
#define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); )
#define HAL_TURN_ON_LED2() st( LED2_SBIT = LED2_POLARITY (1); )
#define HAL_TURN_ON_LED3() HAL_TURN_ON_LED1()
#define HAL_TURN_ON_LED4() HAL_TURN_ON_LED2()
#define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} )
#define HAL_TOGGLE_LED2() st( if (LED2_SBIT) { LED2_SBIT = 0; } else { LED2_SBIT = 1;} )
#define HAL_TOGGLE_LED3() HAL_TOGGLE_LED1()
#define HAL_TOGGLE_LED4() HAL_TOGGLE_LED2()
#define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT))
#define HAL_STATE_LED2() (LED2_POLARITY (LED2_SBIT))
#define HAL_STATE_LED3() HAL_STATE_LED1()
#define HAL_STATE_LED4() HAL_STATE_LED2()
/* ----------- Minimum safe bus voltage ---------- */
// Vdd/3 / Internal Reference X ENOB --> (Vdd / 3) / 1.15 X 127
#define VDD_2_0 74 // 2.0 V required to safely read/write internal flash.
#define VDD_MIN_RUN VDD_2_0
#define VDD_MIN_NV (VDD_2_0+4) // 5% margin over minimum to survive a page erase and compaction.
/* ------------------------------------------------------------------------------------------------
* Driver Configuration
* ------------------------------------------------------------------------------------------------
*/
/* Set to TRUE enable H/W TIMER usage, FALSE disable it */
#ifndef HAL_TIMER
#define HAL_TIMER FALSE
#endif
/* Set to TRUE enable ADC usage, FALSE disable it */
#ifndef HAL_ADC
#define HAL_ADC TRUE
#endif
/* Set to TRUE enable DMA usage, FALSE disable it */
#ifndef HAL_DMA
#define HAL_DMA TRUE
#endif
/* Set to TRUE enable Flash access, FALSE disable it */
#ifndef HAL_FLASH
#define HAL_FLASH TRUE
#endif
/* Set to TRUE enable AES usage, FALSE disable it */
#ifndef HAL_AES
#define HAL_AES TRUE
#endif
#ifndef HAL_AES_DMA
#define HAL_AES_DMA TRUE
#endif
/* Set to TRUE enable LCD usage, FALSE disable it */
#ifndef HAL_LCD
#define HAL_LCD FALSE
#endif
/* Set to TRUE enable LED usage, FALSE disable it */
#ifndef HAL_LED
#define HAL_LED TRUE
#endif
#if (!defined BLINK_LEDS) && (HAL_LED == TRUE)
#define BLINK_LEDS
#endif
/* Set to TRUE enable KEY usage, FALSE disable it */
#ifndef HAL_KEY
#define HAL_KEY TRUE
#endif
/* Set to TRUE enable UART usage, FALSE disable it */
#ifndef HAL_UART
#define HAL_UART TRUE
#define HAL_UART_DMA 0
#define HAL_UART_ISR 0
#define HAL_UART_USB 1
#endif
#ifndef HAL_UART_DMA
#define HAL_UART_DMA 0
#endif
#ifndef HAL_UART_ISR
#define HAL_UART_ISR 0
#endif
#ifndef HAL_UART_USB
# if HAL_UART
# define HAL_UART_USB 1
# else
# define HAL_UART_USB 0
# endif
#endif
/* Set to TRUE enable HID usage, FALSE disable it */
#ifndef HAL_HID
#define HAL_HID FALSE
#endif
#endif
/*******************************************************************************************************
*/

View File

@@ -0,0 +1,167 @@
/**************************************************************************************************
Filename: hal_dma.c
Revised: $Date: 2010-07-21 16:20:44 -0700 (Wed, 21 Jul 2010) $
Revision: $Revision: 23090 $
Description: This file contains the interface to the DMA.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_defs.h"
#include "hal_dma.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
#include "hal_irgen.h"
#endif
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
#include "hal_spi.h"
#endif
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
halDMADesc_t dmaCh0;
halDMADesc_t dmaCh1234[4];
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
/*********************************************************************
* LOCAL FUNCTIONS
*/
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
void HalDmaInit( void )
{
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
HAL_DMA_SET_ADDR_DESC1234( dmaCh1234 );
#if (HAL_UART_DMA || \
((defined HAL_SPI) && (HAL_SPI == TRUE)) || \
((defined HAL_IRGEN) && (HAL_IRGEN == TRUE)))
DMAIE = 1;
#endif
}
#if (HAL_UART_DMA || \
((defined HAL_SPI) && (HAL_SPI == TRUE)) || \
((defined HAL_IRGEN) && (HAL_IRGEN == TRUE)))
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
HAL_ISR_FUNCTION( halDmaIsr, DMA_VECTOR )
{
extern void HalUARTIsrDMA(void);
HAL_ENTER_ISR();
DMAIF = 0;
#if HAL_UART_DMA
if (HAL_DMA_CHECK_IRQ(HAL_DMA_CH_TX))
{
HalUARTIsrDMA();
}
#endif // HAL_UART_DMA
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_RX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_RX );
HalSpiRxIsr();
}
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_TX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_TX );
HalSpiTxIsr();
}
#endif // (defined HAL_SPI) && (HAL_SPI == TRUE)
#if (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
if ( HAL_IRGEN == TRUE && HAL_DMA_CHECK_IRQ( HAL_IRGEN_DMA_CH ) )
{
HAL_DMA_CLEAR_IRQ( HAL_IRGEN_DMA_CH );
HalIrGenDmaIsr();
}
#endif // (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
#endif
#endif // #if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,302 @@
/**************************************************************************************************
Filename: hal_dma.h
Revised: $Date: 2009-03-29 10:51:47 -0700 (Sun, 29 Mar 2009) $
Revision: $Revision: 19585 $
Description: This file contains the interface to the DMA Service.
Copyright 2007-2011 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_DMA_H
#define HAL_DMA_H
#ifdef __cplusplus
extern "C"
{
#endif
/*********************************************************************
* INCLUDES
*/
#include "hal_board.h"
#include "hal_types.h"
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
#define HAL_DMA_SET_ADDR_DESC0( a ) \
st( \
DMA0CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA0CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_SET_ADDR_DESC1234( a ) \
st( \
DMA1CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA1CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_GET_DESC0() &dmaCh0
#define HAL_DMA_GET_DESC1234( a ) (dmaCh1234+((a)-1))
#define HAL_DMA_ARM_CH( ch ) DMAARM = (0x01 << (ch))
#define HAL_DMA_CH_ARMED( ch ) (DMAARM & (0x01 << (ch)))
#define HAL_DMA_ABORT_CH( ch ) DMAARM = (0x80 | (0x01 << (ch)))
#define HAL_DMA_MAN_TRIGGER( ch ) DMAREQ = (0x01 << (ch))
#define HAL_DMA_START_CH( ch ) HAL_DMA_MAN_TRIGGER( (ch) )
#define HAL_DMA_CLEAR_IRQ( ch ) DMAIRQ = ~( 1 << (ch) )
#define HAL_DMA_CHECK_IRQ( ch ) (DMAIRQ & ( 1 << (ch) ))
// Macro for quickly setting the source address of a DMA structure.
#define HAL_DMA_SET_SOURCE( pDesc, src ) \
st( \
pDesc->srcAddrH = (uint8)((uint16)(src) >> 8); \
pDesc->srcAddrL = (uint8)( (uint16)(src) & 0xFF ); \
)
// Macro for quickly setting the destination address of a DMA structure.
#define HAL_DMA_SET_DEST( pDesc, dst ) \
st( \
pDesc->dstAddrH = (uint8)((uint16)(dst) >> 8); \
pDesc->dstAddrL = (uint8)( (uint16)(dst) & 0xFF ); \
)
// Macro for quickly setting the number of bytes to be transferred by the DMA,
// max length is 0x1FFF.
#define HAL_DMA_SET_LEN( pDesc, len ) \
st( \
pDesc->xferLenL = (uint8)( (uint16)(len) & 0xFF); \
pDesc->xferLenV &= ~HAL_DMA_LEN_H; \
pDesc->xferLenV |= (uint8)((uint16)(len) >> 8); \
)
#define HAL_DMA_GET_LEN( pDesc ) \
(((uint16)(pDesc->xferLenV & HAL_DMA_LEN_H) << 8) | pDesc->xferLenL)
#define HAL_DMA_SET_VLEN( pDesc, vMode ) \
st( \
pDesc->xferLenV &= ~HAL_DMA_LEN_V; \
pDesc->xferLenV |= (vMode << 5); \
)
#define HAL_DMA_SET_WORD_SIZE( pDesc, xSz ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_WORD_SIZE; \
pDesc->ctrlA |= (xSz << 7); \
)
#define HAL_DMA_SET_TRIG_MODE( pDesc, tMode ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_MODE; \
pDesc->ctrlA |= (tMode << 5); \
)
#define HAL_DMA_GET_TRIG_MODE( pDesc ) ((pDesc->ctrlA >> 5) & 0x3)
#define HAL_DMA_SET_TRIG_SRC( pDesc, tSrc ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_SRC; \
pDesc->ctrlA |= tSrc; \
)
#define HAL_DMA_SET_SRC_INC( pDesc, srcInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_SRC_INC; \
pDesc->ctrlB |= (srcInc << 6); \
)
#define HAL_DMA_SET_DST_INC( pDesc, dstInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_DST_INC; \
pDesc->ctrlB |= (dstInc << 4); \
)
#define HAL_DMA_SET_IRQ( pDesc, enable ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_IRQ_MASK; \
pDesc->ctrlB |= (enable << 3); \
)
#define HAL_DMA_SET_M8( pDesc, m8 ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_M8; \
pDesc->ctrlB |= (m8 << 2); \
)
#define HAL_DMA_SET_PRIORITY( pDesc, pri ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_PRIORITY; \
pDesc->ctrlB |= pri; \
)
/*********************************************************************
* CONSTANTS
*/
// Use LEN for transfer count
#define HAL_DMA_VLEN_USE_LEN 0x00
// Transfer the first byte + the number of bytes indicated by the first byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST 0x01
// Transfer the number of bytes indicated by the first byte (starting with the first byte)
#define HAL_DMA_VLEN_VALOFFIRST 0x02
// Transfer the first byte + the number of bytes indicated by the first byte + 1 more byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_1 0x03
// Transfer the first byte + the number of bytes indicated by the first byte + 2 more bytes
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_2 0x04
#define HAL_DMA_WORDSIZE_BYTE 0x00 /* Transfer a byte at a time. */
#define HAL_DMA_WORDSIZE_WORD 0x01 /* Transfer a 16-bit word at a time. */
#define HAL_DMA_TMODE_SINGLE 0x00 /* Transfer a single byte/word after each DMA trigger. */
#define HAL_DMA_TMODE_BLOCK 0x01 /* Transfer block of data (length len) after each DMA trigger. */
#define HAL_DMA_TMODE_SINGLE_REPEATED 0x02 /* Transfer single byte/word (after len transfers, rearm DMA). */
#define HAL_DMA_TMODE_BLOCK_REPEATED 0x03 /* Transfer block of data (after len transfers, rearm DMA). */
#define HAL_DMA_TRIG_NONE 0 /* No trigger, setting DMAREQ.DMAREQx bit starts transfer. */
#define HAL_DMA_TRIG_PREV 1 /* DMA channel is triggered by completion of previous channel. */
#define HAL_DMA_TRIG_T1_CH0 2 /* Timer 1, compare, channel 0. */
#define HAL_DMA_TRIG_T1_CH1 3 /* Timer 1, compare, channel 1. */
#define HAL_DMA_TRIG_T1_CH2 4 /* Timer 1, compare, channel 2. */
#define HAL_DMA_TRIG_T2_COMP 5 /* Timer 2, compare. */
#define HAL_DMA_TRIG_T2_OVFL 6 /* Timer 2, overflow. */
#define HAL_DMA_TRIG_T3_CH0 7 /* Timer 3, compare, channel 0. */
#define HAL_DMA_TRIG_T3_CH1 8 /* Timer 3, compare, channel 1. */
#define HAL_DMA_TRIG_T4_CH0 9 /* Timer 4, compare, channel 0. */
#define HAL_DMA_TRIG_T4_CH1 10 /* Timer 4, compare, channel 1. */
#define HAL_DMA_TRIG_ST 11 /* Sleep Timer compare. */
#define HAL_DMA_TRIG_IOC_0 12 /* Port 0 I/O pin input transition. */
#define HAL_DMA_TRIG_IOC_1 13 /* Port 1 I/O pin input transition. */
#define HAL_DMA_TRIG_URX0 14 /* USART0 RX complete. */
#define HAL_DMA_TRIG_UTX0 15 /* USART0 TX complete. */
#define HAL_DMA_TRIG_URX1 16 /* USART1 RX complete. */
#define HAL_DMA_TRIG_UTX1 17 /* USART1 TX complete. */
#define HAL_DMA_TRIG_FLASH 18 /* Flash data write complete. */
#define HAL_DMA_TRIG_RADIO 19 /* RF packet byte received/transmit. */
#define HAL_DMA_TRIG_ADC_CHALL 20 /* ADC end of a conversion in a sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH0 21 /* ADC end of conversion channel 0 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH1 22 /* ADC end of conversion channel 1 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH2 23 /* ADC end of conversion channel 2 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH3 24 /* ADC end of conversion channel 3 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH4 25 /* ADC end of conversion channel 4 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH5 26 /* ADC end of conversion channel 5 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH6 27 /* ADC end of conversion channel 6 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH7 28 /* ADC end of conversion channel 7 in sequence, sample ready. */
#define HAL_DMA_TRIG_ENC_DW 29 /* AES encryption processor requests download input data. */
#define HAL_DMA_TRIG_ENC_UP 30 /* AES encryption processor requests upload output data. */
#define HAL_DMA_SRCINC_0 0x00 /* Increment source pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_1 0x01 /* Increment source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_2 0x02 /* Increment source pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_M1 0x03 /* Decrement source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_0 0x00 /* Increment destination pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_1 0x01 /* Increment destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_2 0x02 /* Increment destination pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_M1 0x03 /* Decrement destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_IRQMASK_DISABLE 0x00 /* Disable interrupt generation. */
#define HAL_DMA_IRQMASK_ENABLE 0x01 /* Enable interrupt generation upon DMA channel done. */
#define HAL_DMA_M8_USE_8_BITS 0x00 /* Use all 8 bits for transfer count. */
#define HAL_DMA_M8_USE_7_BITS 0x01 /* Use 7 LSB for transfer count. */
#define HAL_DMA_PRI_LOW 0x00 /* Low, CPU has priority. */
#define HAL_DMA_PRI_GUARANTEED 0x01 /* Guaranteed, DMA at least every second try. */
#define HAL_DMA_PRI_HIGH 0x02 /* High, DMA has priority. */
#define HAL_DMA_PRI_ABSOLUTE 0x03 /* Highest, DMA has priority. Reserved for DMA port access.. */
#define HAL_DMA_MAX_ARM_CLOCKS 45 // Maximum number of clocks required if arming all 5 at once.
/*********************************************************************
* TYPEDEFS
*/
// Bit fields of the 'lenModeH'
#define HAL_DMA_LEN_V 0xE0
#define HAL_DMA_LEN_H 0x1F
// Bit fields of the 'ctrlA'
#define HAL_DMA_WORD_SIZE 0x80
#define HAL_DMA_TRIG_MODE 0x60
#define HAL_DMA_TRIG_SRC 0x1F
// Bit fields of the 'ctrlB'
#define HAL_DMA_SRC_INC 0xC0
#define HAL_DMA_DST_INC 0x30
#define HAL_DMA_IRQ_MASK 0x08
#define HAL_DMA_M8 0x04
#define HAL_DMA_PRIORITY 0x03
typedef struct {
uint8 srcAddrH;
uint8 srcAddrL;
uint8 dstAddrH;
uint8 dstAddrL;
uint8 xferLenV;
uint8 xferLenL;
uint8 ctrlA;
uint8 ctrlB;
} halDMADesc_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
extern halDMADesc_t dmaCh0;
extern halDMADesc_t dmaCh1234[4];
/*********************************************************************
* FUNCTIONS - API
*/
void HalDmaInit( void );
#endif // #if (defined HAL_DMA) && (HAL_DMA == TRUE)
#ifdef __cplusplus
}
#endif
#endif // #ifndef HAL_DMA_H
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,171 @@
/**************************************************************************************************
Filename: hal_flash.c
Revised: $Date: 2010-10-07 02:19:52 -0700 (Thu, 07 Oct 2010) $
Revision: $Revision: 24049 $
Description: This file contains the interface to the H/W Flash driver.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* @fn HalFlashRead
*
* @brief This function reads 'cnt' bytes from the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number.
* @param offset - A valid offset into the page.
* @param buf - A valid buffer space at least as big as the 'cnt' parameter.
* @param cnt - A valid number of bytes to read.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashRead(uint8 pg, uint16 offset, uint8 *buf, uint16 cnt)
{
// Calculate the offset into the containing flash bank as it gets mapped into XDATA.
uint8 *pData = (uint8 *)(offset + HAL_FLASH_PAGE_MAP) +
((pg % HAL_FLASH_PAGE_PER_BANK) * HAL_FLASH_PAGE_SIZE);
uint8 memctr = MEMCTR; // Save to restore.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
halIntState_t is;
#endif
pg /= HAL_FLASH_PAGE_PER_BANK; // Calculate the flash bank from the flash page.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_ENTER_CRITICAL_SECTION(is);
#endif
// Calculate and map the containing flash bank into XDATA.
MEMCTR = (MEMCTR & 0xF8) | pg;
while (cnt--)
{
*buf++ = *pData++;
}
MEMCTR = memctr;
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_EXIT_CRITICAL_SECTION(is);
#endif
}
/**************************************************************************************************
* @fn HalFlashWrite
*
* @brief This function writes 'cnt' bytes to the internal flash.
*
* input parameters
*
* @param addr - Valid HAL flash write address: actual addr / 4 and quad-aligned.
* @param buf - Valid buffer space at least as big as 'cnt' X 4.
* @param cnt - Number of 4-byte blocks to write.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashWrite(uint16 addr, uint8 *buf, uint16 cnt)
{
#if (defined HAL_DMA) && (HAL_DMA == TRUE)
halDMADesc_t *ch = HAL_NV_DMA_GET_DESC();
HAL_DMA_SET_SOURCE(ch, buf);
HAL_DMA_SET_DEST(ch, &FWDATA);
HAL_DMA_SET_VLEN(ch, HAL_DMA_VLEN_USE_LEN);
HAL_DMA_SET_LEN(ch, (cnt * HAL_FLASH_WORD_SIZE));
HAL_DMA_SET_WORD_SIZE(ch, HAL_DMA_WORDSIZE_BYTE);
HAL_DMA_SET_TRIG_MODE(ch, HAL_DMA_TMODE_SINGLE);
HAL_DMA_SET_TRIG_SRC(ch, HAL_DMA_TRIG_FLASH);
HAL_DMA_SET_SRC_INC(ch, HAL_DMA_SRCINC_1);
HAL_DMA_SET_DST_INC(ch, HAL_DMA_DSTINC_0);
// The DMA is to be polled and shall not issue an IRQ upon completion.
HAL_DMA_SET_IRQ(ch, HAL_DMA_IRQMASK_DISABLE);
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS);
HAL_DMA_SET_PRIORITY(ch, HAL_DMA_PRI_HIGH);
HAL_DMA_CLEAR_IRQ(HAL_NV_DMA_CH);
HAL_DMA_ARM_CH(HAL_NV_DMA_CH);
FADDRL = (uint8)addr;
FADDRH = (uint8)(addr >> 8);
FCTL |= 0x02; // Trigger the DMA writes.
while (FCTL & 0x80); // Wait until writing is done.
#endif
}
/**************************************************************************************************
* @fn HalFlashErase
*
* @brief This function erases the specified page of the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number to erase.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashErase(uint8 pg)
{
FADDRH = pg * (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE / 256);
FCTL |= 0x01;
}
/**************************************************************************************************
*/

View File

@@ -0,0 +1,293 @@
/**************************************************************************************************
Filename: hal_key.c
Revised: $Date:$
Revision: $Revision:$
Description: This file contains the interface to the H/W Key driver.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board.h"
#include "hal_drivers.h"
#include "hal_key.h"
#include "hal_types.h"
#include "osal.h"
#include "usb_interrupt.h"
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
#define HAL_KEY_CLR_INT() \
st ( \
/* PxIFG has to be cleared before PxIF. */\
P1IFG = 0; \
P1IF = 0; \
)
/* ------------------------------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------------------------------------
* Typedefs
* ------------------------------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------------------------------------
* Global Variables
* ------------------------------------------------------------------------------------------------
*/
uint8 Hal_KeyIntEnable;
/* ------------------------------------------------------------------------------------------------
* Global Functions
* ------------------------------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
static halKeyCBack_t pHalKeyProcessFunction;
static volatile uint8 isrKeys;
static uint8 halKeys;
/* ------------------------------------------------------------------------------------------------
* Local Functions
* ------------------------------------------------------------------------------------------------
*/
/**************************************************************************************************
* @fn HalKeyInit
*
* @brief This function is called by HalDriverInit to initialize the H/W keys.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalKeyInit(void)
{
}
/**************************************************************************************************
* @fn HalKeyConfig
*
* @brief This function is called by HalDriverInit to initialize the H/W keys.
*
* input parameters
*
* @param interruptEnable - TRUE/FALSE to enable the key interrupt.
* @param cback - The callback function for the key change event.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalKeyConfig(bool interruptEnable, halKeyCBack_t cback)
{
if ((Hal_KeyIntEnable = interruptEnable))
{
HAL_KEY_CLR_INT(); // Clear spurious ints.
PICTL |= 0x01; // P1ICONL: Falling edge ints on pins 0-3.
P1IEN |= PUSH1_BV | PUSH2_BV; // Enable specific P1 bits for ints by bit mask.
IEN2 |= 0x10; // Enable general P1 interrupts.
}
else
{
(void)osal_set_event(Hal_TaskID, HAL_KEY_EVENT);
}
pHalKeyProcessFunction = cback;
}
/**************************************************************************************************
* @fn HalKeyPoll
*
* @brief This function is called by Hal_ProcessEvent() on a HAL_KEY_EVENT.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalKeyPoll(void)
{
uint8 newKeys;
if (Hal_KeyIntEnable)
{
halIntState_t intState;
HAL_ENTER_CRITICAL_SECTION(intState);
newKeys = isrKeys;
isrKeys = 0;
HAL_EXIT_CRITICAL_SECTION(intState);
}
else
{
uint8 keys = HalKeyRead();
newKeys = (halKeys ^ keys) & keys;
halKeys = keys;
}
if (newKeys && pHalKeyProcessFunction)
{
(pHalKeyProcessFunction)(newKeys, HAL_KEY_STATE_NORMAL);
}
}
/**************************************************************************************************
* @fn HalKeyRead
*
* @brief This function is called anywhere.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return The bit mask of all keys pressed.
**************************************************************************************************
*/
uint8 HalKeyRead(void)
{
uint8 keys = 0;
if (HAL_PUSH_BUTTON1())
{
keys |= HAL_KEY_SW_1;
}
if (HAL_PUSH_BUTTON2())
{
keys |= HAL_KEY_SW_2;
}
return keys;
}
/**************************************************************************************************
* @fn HalKeyEnterSleep
*
* @brief - Get called to enter sleep mode
*
* @param
*
* @return
**************************************************************************************************/
void HalKeyEnterSleep ( void )
{
}
/**************************************************************************************************
* @fn HalKeyExitSleep
*
* @brief - Get called when sleep is over
*
* @param
*
* @return - return saved keys
**************************************************************************************************/
uint8 HalKeyExitSleep ( void )
{
/* Wake up and read keys */
return ( HalKeyRead () );
}
/**************************************************************************************************
* @fn usbKeyISR
*
* @brief This function is the ISR for the Port2 USB/Key interrupt.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
HAL_ISR_FUNCTION( usbKeyISR, P1INT_VECTOR )
{
HAL_ENTER_ISR();
if (P1IFG & PUSH1_BV)
{
isrKeys |= HAL_KEY_SW_1;
}
if (P1IFG & PUSH2_BV)
{
isrKeys |= HAL_KEY_SW_2;
}
HAL_KEY_CLR_INT();
(void)osal_set_event(Hal_TaskID, HAL_KEY_EVENT);
HAL_EXIT_ISR();
}
/**************************************************************************************************
*/

View File

@@ -0,0 +1,763 @@
/**************************************************************************************************
Filename: hal_lcd.c
Revised: $Date: 2010-02-25 12:33:58 -0800 (Thu, 25 Feb 2010) $
Revision: $Revision: 21797 $
Description: This file contains the interface to the HAL LCD Service.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_types.h"
#include "hal_lcd.h"
#include "OSAL.h"
#include "OnBoard.h"
#include "hal_assert.h"
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#include "DebugTrace.h"
#endif
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/*
LCD pins
//control
P0.0 - LCD_MODE
P1.1 - LCD_FLASH_RESET
P1.2 - LCD_CS
//spi
P1.5 - CLK
P1.6 - MOSI
P1.7 - MISO
*/
/* LCD Control lines */
#define HAL_LCD_MODE_PORT 0
#define HAL_LCD_MODE_PIN 0
#define HAL_LCD_RESET_PORT 1
#define HAL_LCD_RESET_PIN 1
#define HAL_LCD_CS_PORT 1
#define HAL_LCD_CS_PIN 2
/* LCD SPI lines */
#define HAL_LCD_CLK_PORT 1
#define HAL_LCD_CLK_PIN 5
#define HAL_LCD_MOSI_PORT 1
#define HAL_LCD_MOSI_PIN 6
#define HAL_LCD_MISO_PORT 1
#define HAL_LCD_MISO_PIN 7
/* SPI settings */
#define HAL_SPI_CLOCK_POL_LO 0x00
#define HAL_SPI_CLOCK_PHA_0 0x00
#define HAL_SPI_TRANSFER_MSB_FIRST 0x20
/* LCD lines */
#define LCD_MAX_LINE_COUNT 3
#define LCD_MAX_LINE_LENGTH 16
#define LCD_MAX_BUF 25
/* Defines for HW LCD */
/* Set power save mode */
#define OSC_OFF 0x00
#define OSC_ON 0x01
#define POWER_SAVE_OFF 0x00
#define POWER_SAVE_ON 0x02
#define SET_POWER_SAVE_MODE(options) HalLcd_HW_Control(0x0C | (options))
/* Function Set */
#define CGROM 0x00
#define CGRAM 0x01
#define COM_FORWARD 0x00
#define COM_BACKWARD 0x02
#define TWO_LINE 0x00
#define THREE_LINE 0x04
#define FUNCTION_SET(options) HalLcd_HW_Control(0x10 | (options))
/* Set Display Start Line */
#define LINE1 0x00
#define LINE2 0x01
#define LINE3 0x02
#define LINE4 0x03
#define SET_DISPLAY_START_LINE(line) HalLcd_HW_Control(0x18 | (line))
/* Bias control */
#define BIAS_1_5 0x00
#define BIAS_1_4 0x01
#define SET_BIAS_CTRL(bias) HalLcd_HW_Control(0x1C | (bias))
/* Power control */
#define VOLTAGE_DIVIDER_OFF 0x00
#define VOLTAGE_DIVIDER_ON 0x01
#define CONVERTER_AND_REG_OFF 0x00
#define CONVERTER_AND_REG_ON 0x04
#define SET_POWER_CTRL(options) HalLcd_HW_Control(0x20 | (options))
// Set display control
#define DISPLAY_CTRL_ON 0x01
#define DISPLAY_CTRL_OFF 0x00
#define DISPLAY_CTRL_BLINK_ON 0x02
#define DISPLAY_CTRL_BLINK_OFF 0x00
#define DISPLAY_CTRL_CURSOR_ON 0x04
#define DISPLAY_CTRL_CURSOR_OFF 0x00
#define SET_DISPLAY_CTRL(options) HalLcd_HW_Control(0x28 | (options))
/* Set DD/ CGRAM address */
#define SET_DDRAM_ADDR(charIndex) HalLcd_HW_Control(0x80 | (charIndex))
#define SET_GCRAM_CHAR(specIndex) HalLcd_HW_Control(0xC0 | (specIndex))
/* Set ICONRAM address */
#define CONTRAST_CTRL_REGISTER 0x10
#define SET_ICONRAM_ADDR(addr) HalLcd_HW_Control(0x40 | (addr))
/* Set double height */
#define LINE_1_AND_2 0x01
#define LINE_2_AND_3 0x02
#define NORMAL_DISPLAY 0x00
#define SET_DOUBLE_HEIGHT(options) HalLcd_HW_Control(0x08 | (options))
/**************************************************************************************************
* MACROS
**************************************************************************************************/
#define HAL_IO_SET(port, pin, val) HAL_IO_SET_PREP(port, pin, val)
#define HAL_IO_SET_PREP(port, pin, val) st( P##port##_##pin## = val; )
#define HAL_CONFIG_IO_OUTPUT(port, pin, val) HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val)
#define HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val) st( P##port##SEL &= ~BV(pin); \
P##port##_##pin## = val; \
P##port##DIR |= BV(pin); )
#define HAL_CONFIG_IO_PERIPHERAL(port, pin) HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin)
#define HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin) st( P##port##SEL |= BV(pin); )
/* SPI interface control */
#define LCD_SPI_BEGIN() HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 0); /* chip select */
#define LCD_SPI_END() \
{ \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1); /* chip select */ \
}
/* clear the received and transmit byte status, write tx data to buffer, wait till transmit done */
#define LCD_SPI_TX(x) { U1CSR &= ~(BV(2) | BV(1)); U1DBUF = x; while( !(U1CSR & BV(1)) ); }
#define LCD_SPI_WAIT_RXRDY() { while(!(U1CSR & BV(1))); }
/* Control macros */
#define LCD_DO_WRITE() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
#define LCD_DO_CONTROL() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 0);
#define LCD_ACTIVATE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 0);
#define LCD_RELEASE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* LOCAL VARIABLES
**************************************************************************************************/
static uint8 *Lcd_Line1;
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
void HalLcd_HW_Init(void);
void HalLcd_HW_WaitUs(uint16 i);
void HalLcd_HW_Clear(void);
void HalLcd_HW_ClearAllSpecChars(void);
void HalLcd_HW_Control(uint8 cmd);
void HalLcd_HW_Write(uint8 data);
void HalLcd_HW_SetContrast(uint8 value);
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text);
void HalLcd_HW_WriteLine(uint8 line, const char *pText);
#endif //LCD
/**************************************************************************************************
* @fn HalLcdInit
*
* @brief Initilize LCD Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
**************************************************************************************************/
void HalLcdInit(void)
{
#if (HAL_LCD == TRUE)
Lcd_Line1 = NULL;
HalLcd_HW_Init();
#endif
}
/*************************************************************************************************
* LCD EMULATION FUNCTIONS
*
* Some evaluation boards are equipped with Liquid Crystal Displays
* (LCD) which may be used to display diagnostic information. These
* functions provide LCD emulation, sending the diagnostic strings
* to Z-Tool via the RS232 serial port. These functions are enabled
* when the "LCD_SUPPORTED" compiler flag is placed in the makefile.
*
* Most applications update both lines (1 and 2) of the LCD whenever
* text is posted to the device. This emulator assumes that line 1 is
* updated first (saved locally) and the formatting and send operation
* is triggered by receipt of line 2. Nothing will be transmitted if
* only line 1 is updated.
*
*************************************************************************************************/
/**************************************************************************************************
* @fn HalLcdWriteString
*
* @brief Write a string to the LCD
*
* @param str - pointer to the string that will be displayed
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteString ( char *str, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 strLen = 0;
uint8 totalLen = 0;
uint8 *buf;
uint8 tmpLen;
if ( Lcd_Line1 == NULL )
{
Lcd_Line1 = osal_mem_alloc( HAL_LCD_MAX_CHARS+1 );
HalLcdWriteString( "TexasInstruments", 1 );
}
strLen = (uint8)osal_strlen( (char*)str );
/* Check boundries */
if ( strLen > HAL_LCD_MAX_CHARS )
strLen = HAL_LCD_MAX_CHARS;
if ( option == HAL_LCD_LINE_1 )
{
/* Line 1 gets saved for later */
osal_memcpy( Lcd_Line1, str, strLen );
Lcd_Line1[strLen] = '\0';
}
else
{
/* Line 2 triggers action */
tmpLen = (uint8)osal_strlen( (char*)Lcd_Line1 );
totalLen = tmpLen + 1 + strLen + 1;
buf = osal_mem_alloc( totalLen );
if ( buf != NULL )
{
/* Concatenate strings */
osal_memcpy( buf, Lcd_Line1, tmpLen );
buf[tmpLen++] = ' ';
osal_memcpy( &buf[tmpLen], str, strLen );
buf[tmpLen+strLen] = '\0';
/* Send it out */
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#if defined(SERIAL_DEBUG_SUPPORTED)
debug_str( (uint8*)buf );
#endif //LCD_SUPPORTED
#endif //ZTOOL_P1
/* Free mem */
osal_mem_free( buf );
}
}
/* Display the string */
HalLcd_HW_WriteLine (option, str);
#endif //HAL_LCD
}
/**************************************************************************************************
* @fn HalLcdWriteValue
*
* @brief Write a value to the LCD
*
* @param value - value that will be displayed
* radix - 8, 10, 16
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteValue ( uint32 value, const uint8 radix, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 buf[LCD_MAX_BUF];
_ltoa( value, &buf[0], radix );
HalLcdWriteString( (char*)buf, option );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteScreen
*
* @brief Write a value to the LCD
*
* @param line1 - string that will be displayed on line 1
* line2 - string that will be displayed on line 2
*
* @return None
**************************************************************************************************/
void HalLcdWriteScreen( char *line1, char *line2 )
{
#if (HAL_LCD == TRUE)
HalLcdWriteString( line1, 1 );
HalLcdWriteString( line2, 2 );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value - value
* format - redix
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValue( char *title, uint16 value, uint8 format, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
osal_memcpy( buf, title, tmpLen );
buf[tmpLen] = ' ';
err = (uint32)(value);
_ltoa( err, &buf[tmpLen+1], format );
HalLcdWriteString( (char*)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value1 - value #1
* format1 - redix of value #1
* value2 - value #2
* format2 - redix of value #2
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValueValue( char *title, uint16 value1, uint8 format1,
uint16 value2, uint8 format2, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
if ( tmpLen )
{
osal_memcpy( buf, title, tmpLen );
buf[tmpLen++] = ' ';
}
err = (uint32)(value1);
_ltoa( err, &buf[tmpLen], format1 );
tmpLen = (uint8)osal_strlen( (char*)buf );
buf[tmpLen++] = ',';
buf[tmpLen++] = ' ';
err = (uint32)(value2);
_ltoa( err, &buf[tmpLen], format2 );
HalLcdWriteString( (char *)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdDisplayPercentBar
*
* @brief Display percentage bar on the LCD
*
* @param title -
* value -
*
* @return None
**************************************************************************************************/
void HalLcdDisplayPercentBar( char *title, uint8 value )
{
#if (HAL_LCD == TRUE)
uint8 percent;
uint8 leftOver;
uint8 buf[17];
uint32 err;
uint8 x;
/* Write the title: */
HalLcdWriteString( title, HAL_LCD_LINE_1 );
if ( value > 100 )
value = 100;
/* convert to blocks */
percent = (uint8)(value / 10);
leftOver = (uint8)(value % 10);
/* Make window */
osal_memcpy( buf, "[ ] ", 15 );
for ( x = 0; x < percent; x ++ )
{
buf[1+x] = '>';
}
if ( leftOver >= 5 )
buf[1+x] = '+';
err = (uint32)value;
_ltoa( err, (uint8*)&buf[13], 10 );
HalLcdWriteString( (char*)buf, HAL_LCD_LINE_2 );
#endif
}
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* HARDWARE LCD
**************************************************************************************************/
/**************************************************************************************************
* @fn halLcd_ConfigIO
*
* @brief Configure IO lines needed for LCD control.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigIO(void)
{
/* GPIO configuration */
HAL_CONFIG_IO_OUTPUT(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1);
}
/**************************************************************************************************
* @fn halLcd_ConfigSPI
*
* @brief Configure SPI lines needed for talking to LCD.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigSPI(void)
{
/* UART/SPI Peripheral configuration */
uint8 baud_exponent;
uint8 baud_mantissa;
/* Set SPI on UART 1 alternative 2 */
PERCFG |= 0x02;
/* Configure clk, master out and master in lines */
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_CLK_PORT, HAL_LCD_CLK_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MOSI_PORT, HAL_LCD_MOSI_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MISO_PORT, HAL_LCD_MISO_PIN);
/* Set SPI speed to 1 MHz (the values assume system clk of 32MHz)
* Confirm on board that this results in 1MHz spi clk.
*/
baud_exponent = 15;
baud_mantissa = 0;
/* Configure SPI */
U1UCR = 0x80; /* Flush and goto IDLE state. 8-N-1. */
U1CSR = 0x00; /* SPI mode, master. */
U1GCR = HAL_SPI_TRANSFER_MSB_FIRST | HAL_SPI_CLOCK_PHA_0 | HAL_SPI_CLOCK_POL_LO | baud_exponent;
U1BAUD = baud_mantissa;
}
/**************************************************************************************************
* @fn HalLcd_HW_Init
*
* @brief Initilize HW LCD Driver.
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Init(void)
{
/* Initialize LCD IO lines */
halLcd_ConfigIO();
/* Initialize SPI */
halLcd_ConfigSPI();
/* Perform reset */
LCD_ACTIVATE_RESET();
HalLcd_HW_WaitUs(15000); // 15 ms
LCD_RELEASE_RESET();
HalLcd_HW_WaitUs(15); // 15 us
/* Perform the initialization sequence */
FUNCTION_SET(CGRAM | COM_FORWARD | THREE_LINE);
/* Set contrast */
HalLcd_HW_SetContrast(15);
/* Set power */
SET_POWER_SAVE_MODE(OSC_OFF | POWER_SAVE_ON);
SET_POWER_CTRL(VOLTAGE_DIVIDER_ON | CONVERTER_AND_REG_ON);
SET_BIAS_CTRL(BIAS_1_5);
HalLcd_HW_WaitUs(21000);// 21 ms
/* Clear the display */
HalLcd_HW_Clear();
HalLcd_HW_ClearAllSpecChars();
SET_DISPLAY_CTRL(DISPLAY_CTRL_ON | DISPLAY_CTRL_BLINK_OFF | DISPLAY_CTRL_CURSOR_OFF);
}
/**************************************************************************************************
* @fn HalLcd_HW_Control
*
* @brief Write 1 command to the LCD
*
* @param uint8 cmd - command to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Control(uint8 cmd)
{
LCD_SPI_BEGIN();
LCD_DO_CONTROL();
LCD_SPI_TX(cmd);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_Write
*
* @brief Write 1 byte to the LCD
*
* @param uint8 data - data to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Write(uint8 data)
{
LCD_SPI_BEGIN();
LCD_DO_WRITE();
LCD_SPI_TX(data);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_SetContrast
*
* @brief Set display contrast
*
* @param uint8 value - contrast value
*
* @return none
**************************************************************************************************/
void HalLcd_HW_SetContrast(uint8 value)
{
SET_ICONRAM_ADDR(CONTRAST_CTRL_REGISTER);
HalLcd_HW_Write(value);
}
/**************************************************************************************************
* @fn HalLcd_HW_Clear
*
* @brief Clear the HW LCD
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Clear(void)
{
uint8 n;
SET_DDRAM_ADDR(0x00);
for (n = 0; n < (LCD_MAX_LINE_COUNT * LCD_MAX_LINE_LENGTH); n++)
{
HalLcd_HW_Write(' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_ClearAllSpecChars
*
* @brief Clear all special chars
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_ClearAllSpecChars(void)
{
uint8 n = 0;
SET_GCRAM_CHAR(0);
for (n = 0; n < (8 * 8); n++)
{
HalLcd_HW_Write(0x00);
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WriteChar
*
* @brief Write one char to the display
*
* @param uint8 line - line number that the char will be displayed
* uint8 col - colum where the char will be displayed
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text)
{
if (col < LCD_MAX_LINE_LENGTH)
{
SET_DDRAM_ADDR((line - 1) * LCD_MAX_LINE_LENGTH + col);
HalLcd_HW_Write(text);
}
else
{
return;
}
}
/**************************************************************************************************
* @fn halLcdWriteLine
*
* @brief Write one line on display
*
* @param uint8 line - display line
* char *pText - text buffer to write
*
* @return none
**************************************************************************************************/
void HalLcd_HW_WriteLine(uint8 line, const char *pText)
{
uint8 count;
uint8 totalLength = (uint8)osal_strlen( (char *)pText );
/* Write the content first */
for (count=0; count<totalLength; count++)
{
HalLcd_HW_WriteChar(line, count, (*(pText++)));
}
/* Write blank spaces to rest of the line */
for(count=totalLength; count<LCD_MAX_LINE_LENGTH;count++)
{
HalLcd_HW_WriteChar(line, count, ' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WaitUs
*
* @brief wait for x us. @ 32MHz MCU clock it takes 32 "nop"s for 1 us delay.
*
* @param x us. range[0-65536]
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WaitUs(uint16 microSecs)
{
while(microSecs--)
{
/* 32 NOPs == 1 usecs */
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop");
}
}
#endif
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,517 @@
/**************************************************************************************************
Filename: hal_led.c
Revised: $Date: 2011-04-15 10:47:58 -0700 (Fri, 15 Apr 2011) $
Revision: $Revision: 25723 $
Description: This file contains the interface to the HAL LED Service.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/***************************************************************************************************
* INCLUDES
***************************************************************************************************/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_drivers.h"
#include "hal_led.h"
#include "osal.h"
#include "hal_board.h"
/***************************************************************************************************
* CONSTANTS
***************************************************************************************************/
/***************************************************************************************************
* MACROS
***************************************************************************************************/
/***************************************************************************************************
* TYPEDEFS
***************************************************************************************************/
/* LED control structure */
typedef struct {
uint8 mode; /* Operation mode */
uint8 todo; /* Blink cycles left */
uint8 onPct; /* On cycle percentage */
uint16 time; /* On/off cycle time (msec) */
uint32 next; /* Time for next change */
} HalLedControl_t;
typedef struct
{
HalLedControl_t HalLedControlTable[HAL_LED_DEFAULT_MAX_LEDS];
uint8 sleepActive;
} HalLedStatus_t;
/***************************************************************************************************
* GLOBAL VARIABLES
***************************************************************************************************/
static uint8 HalLedState; // LED state at last set/clr/blink update
#if HAL_LED == TRUE
static uint8 HalSleepLedState; // LED state at last set/clr/blink update
static uint8 preBlinkState; // Original State before going to blink mode
// bit 0, 1, 2, 3 represent led 0, 1, 2, 3
#endif
#ifdef BLINK_LEDS
static HalLedStatus_t HalLedStatusControl;
#endif
/***************************************************************************************************
* LOCAL FUNCTION
***************************************************************************************************/
#if (HAL_LED == TRUE)
void HalLedUpdate (void);
void HalLedOnOff (uint8 leds, uint8 mode);
#endif /* HAL_LED */
/***************************************************************************************************
* FUNCTIONS - API
***************************************************************************************************/
/***************************************************************************************************
* @fn HalLedInit
*
* @brief Initialize LED Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
***************************************************************************************************/
void HalLedInit (void)
{
#if (HAL_LED == TRUE)
/* Initialize all LEDs to OFF */
HalLedSet (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Initialize sleepActive to FALSE */
HalLedStatusControl.sleepActive = FALSE;
#endif
}
/***************************************************************************************************
* @fn HalLedSet
*
* @brief Tun ON/OFF/TOGGLE given LEDs
*
* @param led - bit mask value of leds to be turned ON/OFF/TOGGLE
* mode - BLINK, FLASH, TOGGLE, ON, OFF
* @return None
***************************************************************************************************/
uint8 HalLedSet (uint8 leds, uint8 mode)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
switch (mode)
{
case HAL_LED_MODE_BLINK:
/* Default blink, 1 time, D% duty cycle */
HalLedBlink (leds, 1, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_FLASH:
/* Default flash, N times, D% duty cycle */
HalLedBlink (leds, HAL_LED_DEFAULT_FLASH_COUNT, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_ON:
case HAL_LED_MODE_OFF:
case HAL_LED_MODE_TOGGLE:
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
if (mode != HAL_LED_MODE_TOGGLE)
{
sts->mode = mode; /* ON or OFF */
}
else
{
sts->mode ^= HAL_LED_MODE_ON; /* Toggle */
}
HalLedOnOff (led, sts->mode);
leds ^= led;
}
led <<= 1;
sts++;
}
break;
default:
break;
}
#elif (HAL_LED == TRUE)
LedOnOff(leds, mode);
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) mode;
#endif /* BLINK_LEDS && HAL_LED */
return ( HalLedState );
}
/***************************************************************************************************
* @fn HalLedBlink
*
* @brief Blink the leds
*
* @param leds - bit mask value of leds to be blinked
* numBlinks - number of blinks
* percent - the percentage in each period where the led
* will be on
* period - length of each cycle in milliseconds
*
* @return None
***************************************************************************************************/
void HalLedBlink (uint8 leds, uint8 numBlinks, uint8 percent, uint16 period)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
if (leds && percent && period)
{
if (percent < 100)
{
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
/* Store the current state of the led before going to blinking if not already blinking */
if(sts->mode < HAL_LED_MODE_BLINK )
preBlinkState |= (led & HalLedState);
sts->mode = HAL_LED_MODE_OFF; /* Stop previous blink */
sts->time = period; /* Time for one on/off cycle */
sts->onPct = percent; /* % of cycle LED is on */
sts->todo = numBlinks; /* Number of blink cycles */
if (!numBlinks) sts->mode |= HAL_LED_MODE_FLASH; /* Continuous */
sts->next = osal_GetSystemClock(); /* Start now */
sts->mode |= HAL_LED_MODE_BLINK; /* Enable blinking */
leds ^= led;
}
led <<= 1;
sts++;
}
osal_set_event (Hal_TaskID, HAL_LED_BLINK_EVENT);
}
else
{
HalLedSet (leds, HAL_LED_MODE_ON); /* >= 100%, turn on */
}
}
else
{
HalLedSet (leds, HAL_LED_MODE_OFF); /* No on time, turn off */
}
#elif (HAL_LED == TRUE)
percent = (leds & HalLedState) ? HAL_LED_MODE_OFF : HAL_LED_MODE_ON;
HalLedOnOff (leds, percent); /* Toggle */
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) numBlinks;
(void) percent;
(void) period;
#endif /* BLINK_LEDS && HAL_LED */
}
#if (HAL_LED == TRUE)
/***************************************************************************************************
* @fn HalLedUpdate
*
* @brief Update leds to work with blink
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedUpdate (void)
{
uint8 led;
uint8 pct;
uint8 leds;
HalLedControl_t *sts;
uint32 time;
uint16 next;
uint16 wait;
next = 0;
led = HAL_LED_1;
leds = HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
/* Check if sleep is active or not */
if (!HalLedStatusControl.sleepActive)
{
while (leds)
{
if (leds & led)
{
if (sts->mode & HAL_LED_MODE_BLINK)
{
time = osal_GetSystemClock();
if (time >= sts->next)
{
if (sts->mode & HAL_LED_MODE_ON)
{
pct = 100 - sts->onPct; /* Percentage of cycle for off */
sts->mode &= ~HAL_LED_MODE_ON; /* Say it's not on */
HalLedOnOff (led, HAL_LED_MODE_OFF); /* Turn it off */
if (!(sts->mode & HAL_LED_MODE_FLASH))
{
sts->todo--; /* Not continuous, reduce count */
if (!sts->todo)
{
sts->mode ^= HAL_LED_MODE_BLINK; /* No more blinks */
}
}
}
else
{
pct = sts->onPct; /* Percentage of cycle for on */
sts->mode |= HAL_LED_MODE_ON; /* Say it's on */
HalLedOnOff (led, HAL_LED_MODE_ON); /* Turn it on */
}
if (sts->mode & HAL_LED_MODE_BLINK)
{
wait = (((uint32)pct * (uint32)sts->time) / 100);
sts->next = time + wait;
}
else
{
/* no more blink, no more wait */
wait = 0;
/* After blinking, set the LED back to the state before it blinks */
HalLedSet (led, ((preBlinkState & led)!=0)?HAL_LED_MODE_ON:HAL_LED_MODE_OFF);
/* Clear the saved bit */
preBlinkState &= (led ^ 0xFF);
}
}
else
{
wait = sts->next - time; /* Time left */
}
if (!next || ( wait && (wait < next) ))
{
next = wait;
}
}
leds ^= led;
}
led <<= 1;
sts++;
}
if (next)
{
osal_start_timerEx(Hal_TaskID, HAL_LED_BLINK_EVENT, next); /* Schedule event */
}
}
}
/***************************************************************************************************
* @fn HalLedOnOff
*
* @brief Turns specified LED ON or OFF
*
* @param leds - LED bit mask
* mode - LED_ON,LED_OFF,
*
* @return none
***************************************************************************************************/
void HalLedOnOff (uint8 leds, uint8 mode)
{
if (leds & HAL_LED_1)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
}
if (leds & HAL_LED_2)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED2();
}
else
{
HAL_TURN_OFF_LED2();
}
}
if (leds & HAL_LED_3)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED3();
}
else
{
HAL_TURN_OFF_LED3();
}
}
if (leds & HAL_LED_4)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED4();
}
else
{
HAL_TURN_OFF_LED4();
}
}
/* Remember current state */
if (mode)
{
HalLedState |= leds;
}
else
{
HalLedState &= (leds ^ 0xFF);
}
}
#endif /* HAL_LED */
/***************************************************************************************************
* @fn HalGetLedState
*
* @brief Dim LED2 - Dim (set level) of LED2
*
* @param none
*
* @return led state
***************************************************************************************************/
uint8 HalLedGetState ()
{
#if (HAL_LED == TRUE)
return HalLedState;
#else
return 0;
#endif
}
/***************************************************************************************************
* @fn HalLedEnterSleep
*
* @brief Store current LEDs state before sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedEnterSleep( void )
{
#ifdef BLINK_LEDS
/* Sleep ON */
HalLedStatusControl.sleepActive = TRUE;
#endif /* BLINK_LEDS */
#if (HAL_LED == TRUE)
/* Save the state of each led */
HalSleepLedState = 0;
HalSleepLedState |= HAL_STATE_LED1();
HalSleepLedState |= HAL_STATE_LED2() << 1;
HalSleepLedState |= HAL_STATE_LED3() << 2;
HalSleepLedState |= HAL_STATE_LED4() << 3;
/* TURN OFF all LEDs to save power */
HalLedOnOff (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
}
/***************************************************************************************************
* @fn HalLedExitSleep
*
* @brief Restore current LEDs state after sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedExitSleep( void )
{
#if (HAL_LED == TRUE)
/* Load back the saved state */
HalLedOnOff(HalSleepLedState, HAL_LED_MODE_ON);
/* Restart - This takes care BLINKING LEDS */
HalLedUpdate();
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Sleep OFF */
HalLedStatusControl.sleepActive = FALSE;
#endif /* BLINK_LEDS */
}
/***************************************************************************************************
***************************************************************************************************/

View File

@@ -0,0 +1,71 @@
/**************************************************************************************************
Filename: hal_mac_cfg.h
Revised: $Date: 2009-06-05 09:21:31 -0700 (Fri, 05 Jun 2009) $
Revision: $Revision: 20106 $
Description: Describe the purpose and contents of the file.
Copyright 2007-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_MAC_CFG_H
#define HAL_MAC_CFG_H
/*
* Board Configuration File for low-level MAC
* --------------------------------------------
* Manufacturer : Texas Instruments
* Part Number : CC2530EB
* Processor : Texas Instruments CC2530
*
*/
/* ------------------------------------------------------------------------------------------------
* Board Specific Configuration
* ------------------------------------------------------------------------------------------------
*/
#define HAL_MAC_RSSI_OFFSET -73 /* no units */
#if defined (HAL_PA_LNA)
/* CC22591 RSSI offset */
#define HAL_MAC_RSSI_LNA_HGM_OFFSET -9
#define HAL_MAC_RSSI_LNA_LGM_OFFSET 4
#elif defined (HAL_PA_LNA_CC2590)
/* CC22590 RSSI offset */
#define HAL_MAC_RSSI_LNA_HGM_OFFSET -10 /* TBD: place holder */
#define HAL_MAC_RSSI_LNA_LGM_OFFSET 0 /* TBD: place holder */
#endif
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,190 @@
/**************************************************************************************************
Filename: hal_mcu.h
Revised: $Date: 2010-07-21 16:20:44 -0700 (Wed, 21 Jul 2010) $
Revision: $Revision: 23090 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef _HAL_MCU_H
#define _HAL_MCU_H
/*
* Target : Texas Instruments CC2530 (8051 core)
*
*/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_defs.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* Target Defines
* ------------------------------------------------------------------------------------------------
*/
#define HAL_MCU_CC2530
/* ------------------------------------------------------------------------------------------------
* Compiler Abstraction
* ------------------------------------------------------------------------------------------------
*/
/* ---------------------- IAR Compiler ---------------------- */
#ifdef __IAR_SYSTEMS_ICC__
#include <ioCC2530.h>
#define HAL_COMPILER_IAR
#define HAL_MCU_LITTLE_ENDIAN() __LITTLE_ENDIAN__
#define _PRAGMA(x) _Pragma(#x)
#define HAL_ISR_FUNC_DECLARATION(f,v) _PRAGMA(vector=v) __near_func __interrupt void f(void)
#define HAL_ISR_FUNC_PROTOTYPE(f,v) _PRAGMA(vector=v) __near_func __interrupt void f(void)
#define HAL_ISR_FUNCTION(f,v) HAL_ISR_FUNC_PROTOTYPE(f,v); HAL_ISR_FUNC_DECLARATION(f,v)
/* ---------------------- Keil Compiler ---------------------- */
#elif defined __KEIL__
#include <CC2530.h>
#define HAL_COMPILER_KEIL
#define HAL_MCU_LITTLE_ENDIAN() 0
#define HAL_ISR_FUNC_DECLARATION(f,v) void f(void) interrupt v
#define HAL_ISR_FUNC_PROTOTYPE(f,v) void f(void)
#define HAL_ISR_FUNCTION(f,v) HAL_ISR_FUNC_PROTOTYPE(f,v); HAL_ISR_FUNC_DECLARATION(f,v)
/* ------------------ Unrecognized Compiler ------------------ */
#else
#error "ERROR: Unknown compiler."
#endif
/* ------------------------------------------------------------------------------------------------
* Interrupt Macros
* ------------------------------------------------------------------------------------------------
*/
#define HAL_ENABLE_INTERRUPTS() st( EA = 1; )
#define HAL_DISABLE_INTERRUPTS() st( EA = 0; )
#define HAL_INTERRUPTS_ARE_ENABLED() (EA)
typedef unsigned char halIntState_t;
#define HAL_ENTER_CRITICAL_SECTION(x) st( x = EA; HAL_DISABLE_INTERRUPTS(); )
#define HAL_EXIT_CRITICAL_SECTION(x) st( EA = x; )
#define HAL_CRITICAL_STATEMENT(x) st( halIntState_t _s; HAL_ENTER_CRITICAL_SECTION(_s); x; HAL_EXIT_CRITICAL_SECTION(_s); )
#ifdef __IAR_SYSTEMS_ICC__
/* IAR library uses XCH instruction with EA. It may cause the higher priority interrupt to be
* locked out, therefore, may increase interrupt latency. It may also create a lockup condition.
* This workaround should only be used with 8051 using IAR compiler. When IAR fixes this by
* removing XCH usage in its library, compile the following macros to null to disable them.
*/
#define HAL_ENTER_ISR() { halIntState_t _isrIntState = EA; HAL_ENABLE_INTERRUPTS();
#define HAL_EXIT_ISR() EA = _isrIntState; }
#else
#define HAL_ENTER_ISR()
#define HAL_EXIT_ISR()
#endif /* __IAR_SYSTEMS_ICC__ */
/* ------------------------------------------------------------------------------------------------
* Reset Macro
* ------------------------------------------------------------------------------------------------
*/
#define WD_EN BV(3)
#define WD_MODE BV(2)
#define WD_INT_1900_USEC (BV(0) | BV(1))
#define WD_RESET1 (0xA0 | WD_EN | WD_INT_1900_USEC)
#define WD_RESET2 (0x50 | WD_EN | WD_INT_1900_USEC)
#define WD_KICK() st( WDCTL = (0xA0 | WDCTL & 0x0F); WDCTL = (0x50 | WDCTL & 0x0F); )
/* disable interrupts, set watchdog timer, wait for reset */
#define HAL_SYSTEM_RESET() st( HAL_DISABLE_INTERRUPTS(); WDCTL = WD_RESET1; WDCTL = WD_RESET2; for(;;); )
/* ------------------------------------------------------------------------------------------------
* CC2530 rev numbers
* ------------------------------------------------------------------------------------------------
*/
#define REV_A 0x00 /* workaround turned off */
#define REV_B 0x11 /* PG1.1 */
#define REV_C 0x20 /* PG2.0 */
#define REV_D 0x21 /* PG2.1 */
/* ------------------------------------------------------------------------------------------------
* CC2530 sleep common code
* ------------------------------------------------------------------------------------------------
*/
/* PCON bit definitions */
#define PCON_IDLE BV(0) /* Writing 1 to force CC2530 to enter sleep mode */
/* SLEEPCMD bit definitions */
#define OSC_PD BV(2) /* Idle Osc: powered down=1 */
#define PMODE (BV(1) | BV(0)) /* Power mode bits */
/* SLEEPSTA bit definitions */
#define XOSC_STB BV(6) /* XOSC: powered, stable=1 */
#define HFRC_STB BV(5) /* HFRCOSC: powered, stable=1 */
/* SLEEPCMD and SLEEPSTA bit definitions */
#define OSC_PD BV(2) /* 0: Both oscillators powered up and stable
* 1: oscillators not stable */
/* CLKCONCMD bit definitions */
#define OSC BV(6)
#define TICKSPD(x) (x << 3)
#define CLKSPD(x) (x << 0)
#define CLKCONCMD_32MHZ (0)
#define CLKCONCMD_16MHZ (CLKSPD(1) | TICKSPD(1) | OSC)
/* STLOAD */
#define LDRDY BV(0) /* Load Ready. This bit is 0 while the sleep timer
* loads the 24-bit compare value and 1 when the sleep
* timer is ready to start loading a newcompare value. */
#ifdef POWER_SAVING
extern volatile __data uint8 halSleepPconValue;
/* Any ISR that is used to wake up the chip shall call this macro. This prevents the race condition
* when the PCON IDLE bit is set after such a critical ISR fires during the prep for sleep.
*/
#define CLEAR_SLEEP_MODE() st( halSleepPconValue = 0; )
#define ALLOW_SLEEP_MODE() st( halSleepPconValue = PCON_IDLE; )
#else
#define CLEAR_SLEEP_MODE()
#define ALLOW_SLEEP_MODE()
#endif
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,577 @@
/**************************************************************************************************
Filename: _hal_oad.c
Revised: $Date: 2010-07-08 18:39:25 -0700 (Thu, 08 Jul 2010) $
Revision: $Revision: 22957 $
Description: This module contains optionally-compiled Boot Code to support OAD.
The rest of the functionality is the H/W specific drivers to read/write
the flash/NV containing the ACTIVE and the DOWNLOADED images.
Notes: This version targets the Texas Instruments CC253x family of processors.
Copyright 2008-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "comdef.h"
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_oad.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
#if HAL_OAD_BOOT_CODE
halDMADesc_t dmaCh0;
#endif
/* ------------------------------------------------------------------------------------------------
* Local Functions
* ------------------------------------------------------------------------------------------------
*/
static uint16 runPoly(uint16 crc, uint8 val);
#if HAL_OAD_XNV_IS_SPI
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len);
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len);
#endif
#if HAL_OAD_BOOT_CODE
static void vddWait(uint8 vdd);
static void dl2rc(void);
static uint16 crcCalc(void);
/**************************************************************************************************
* @fn main
*
* @brief ISR for the reset vector.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
#pragma location="NEAR_CODE"
void main(void)
{
HAL_BOARD_INIT();
vddWait(VDD_MIN_RUN);
#if HAL_OAD_XNV_IS_SPI
XNV_SPI_INIT();
#endif
/* This is in place of calling HalDmaInit() which would require init of the other 4 DMA
* descriptors in addition to just Channel 0.
*/
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
while (1)
{
uint16 crc[2];
HalFlashRead(HAL_OAD_CRC_ADDR / HAL_FLASH_PAGE_SIZE,
HAL_OAD_CRC_ADDR % HAL_FLASH_PAGE_SIZE,
(uint8 *)crc, sizeof(crc));
if (crc[0] == crc[1])
{
break;
}
else if ((crc[0] != 0) && (crc[0] == crcCalc()))
{
crc[1] = crc[0];
HalFlashWrite((HAL_OAD_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)crc, 1);
}
else
{
dl2rc();
}
}
// Simulate a reset for the Application code by an absolute jump to location 0x0800.
asm("LJMP 0x800\n");
}
/*********************************************************************
* @fn vddWait
*
* @brief Loop waiting for 256 reads of the Vdd over the requested limit.
*
* @param vdd - Vdd level to wait for.
*
* @return None.
*********************************************************************/
static void vddWait(uint8 vdd)
{
uint8 cnt = 16;
do {
do {
ADCCON3 = 0x0F;
while (!(ADCCON1 & 0x80));
} while (ADCH < vdd);
} while (--cnt);
}
/*********************************************************************
* @fn dl2rc
*
* @brief Copy the DL image to the RC image location.
*
* NOTE: Assumes that DL image ends on a flash word boundary.
*
* @param None.
*
* @return None.
*********************************************************************/
static void dl2rc(void)
{
preamble_t preamble;
uint32 oset;
uint16 addr = HAL_OAD_RC_START / HAL_FLASH_WORD_SIZE;
uint8 buf[4];
vddWait(VDD_MIN_OAD);
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_DL);
for (oset = 0; oset < preamble.len; oset += HAL_FLASH_WORD_SIZE)
{
HalOADRead(oset, buf, HAL_FLASH_WORD_SIZE, HAL_OAD_DL);
if ((addr % (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE)) == 0)
{
HalFlashErase(addr / (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE));
}
HalFlashWrite(addr++, buf, 1);
}
}
/*********************************************************************
* @fn crcCalc
*
* @brief Run the CRC16 Polynomial calculation over the RC image.
*
* @param None.
*
* @return The CRC16 calculated.
*/
static uint16 crcCalc(void)
{
preamble_t preamble;
uint32 oset;
uint16 crc = 0;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
if (preamble.len > HAL_OAD_DL_SIZE)
{
return 0;
}
// Run the CRC calculation over the active body of code.
for (oset = 0; oset < preamble.len; oset++)
{
if (oset == HAL_OAD_CRC_OSET)
{
oset += 3;
}
else
{
uint8 buf;
HalOADRead(oset, &buf, 1, HAL_OAD_RC);
crc = runPoly(crc, buf);
}
}
// IAR note explains that poly must be run with value zero for each byte of crc.
crc = runPoly(crc, 0);
crc = runPoly(crc, 0);
return crc;
}
#endif
/*********************************************************************
* @fn runPoly
*
* @brief Run the CRC16 Polynomial calculation over the byte parameter.
*
* @param crc - Running CRC calculated so far.
* @param val - Value on which to run the CRC16.
*
* @return crc - Updated for the run.
*/
static uint16 runPoly(uint16 crc, uint8 val)
{
const uint16 poly = 0x1021;
uint8 cnt;
for (cnt = 0; cnt < 8; cnt++, val <<= 1)
{
uint8 msb = (crc & 0x8000) ? 1 : 0;
crc <<= 1;
if (val & 0x80) crc |= 0x0001;
if (msb) crc ^= poly;
}
return crc;
}
/*********************************************************************
* @fn HalOADChkDL
*
* @brief Run the CRC16 Polynomial calculation over the DL image.
*
* @param dlImagePreambleOffset - Offset into the monolithic DL image to read the preamble.
*
* @return SUCCESS or FAILURE.
*********************************************************************/
uint8 HalOADChkDL(uint8 dlImagePreambleOffset)
{
preamble_t preamble;
uint32 oset;
uint16 crc = 0, crc2;
HalOADRead(dlImagePreambleOffset, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_DL);
// Run the CRC calculation over the downloaded image.
for (oset = 0; oset < preamble.len; oset++)
{
if ((oset < HAL_OAD_CRC_OSET) || (oset >= HAL_OAD_CRC_OSET+4))
{
uint8 buf;
HalOADRead(oset, &buf, 1, HAL_OAD_DL);
crc = runPoly(crc, buf);
}
}
// IAR note explains that poly must be run with value zero for each byte of crc.
crc = runPoly(crc, 0);
crc = runPoly(crc, 0);
HalOADRead(HAL_OAD_CRC_OSET, (uint8 *)&crc2, sizeof(crc2), HAL_OAD_DL);
return (crc2 == crc) ? SUCCESS : FAILURE;
}
/*********************************************************************
* @fn HalOADInvRC
*
* @brief Invalidate the active image so that the boot code will instantiate the DL image on the
* next reset.
*
* @param None.
*
* @return None.
*********************************************************************/
void HalOADInvRC(void)
{
uint16 crc[2] = {0,0xFFFF};
HalFlashWrite((HAL_OAD_CRC_ADDR / HAL_FLASH_WORD_SIZE), (uint8 *)crc, 1);
}
/*********************************************************************
* @fn HalOADRead
*
* @brief Read from the storage medium according to image type.
*
* @param oset - Offset into the monolithic image.
* @param pBuf - Pointer to the buffer in which to copy the bytes read.
* @param len - Number of bytes to read.
* @param type - Which image: HAL_OAD_RC or HAL_OAD_DL.
*
* @return None.
*********************************************************************/
void HalOADRead(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OAD_RC != type)
{
#if HAL_OAD_XNV_IS_INT
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
//oset += HAL_OAD_RC_START + preamble.len;
oset += HAL_OAD_RC_START + HAL_OAD_DL_OSET;
#elif HAL_OAD_XNV_IS_SPI
oset += HAL_OAD_DL_OSET;
HalSPIRead(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OAD_RC_START;
}
HalFlashRead(oset / HAL_FLASH_PAGE_SIZE, oset % HAL_FLASH_PAGE_SIZE, pBuf, len);
}
/*********************************************************************
* @fn HalOADWrite
*
* @brief Write to the storage medium according to the image type.
*
* NOTE: Destructive write on page boundary! When writing to the first flash word
* of a page boundary, the page is erased without saving/restoring the bytes not written.
* Writes anywhere else on a page assume that the location written to has been erased.
*
* @param oset - Offset into the monolithic image, aligned to HAL_FLASH_WORD_SIZE.
* @param pBuf - Pointer to the buffer in from which to write.
* @param len - Number of bytes to write. If not an even multiple of HAL_FLASH_WORD_SIZE,
* remainder bytes are overwritten with garbage.
* @param type - Which image: HAL_OAD_RC or HAL_OAD_DL.
*
* @return None.
*********************************************************************/
void HalOADWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type)
{
if (HAL_OAD_RC != type)
{
#if HAL_OAD_XNV_IS_INT
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
//oset += HAL_OAD_RC_START + preamble.len;
oset += HAL_OAD_RC_START + HAL_OAD_DL_OSET;
#elif HAL_OAD_XNV_IS_SPI
oset += HAL_OAD_DL_OSET;
HalSPIWrite(oset, pBuf, len);
return;
#endif
}
else
{
oset += HAL_OAD_RC_START;
}
if ((oset % HAL_FLASH_PAGE_SIZE) == 0)
{
HalFlashErase(oset / HAL_FLASH_PAGE_SIZE);
}
HalFlashWrite(oset / HAL_FLASH_WORD_SIZE, pBuf, len / HAL_FLASH_WORD_SIZE);
}
#if HAL_OAD_XNV_IS_INT
/*********************************************************************
* @fn HalOADAvail
*
* @brief Determine the space available for downloading an image.
*
* @param None.
*
* @return Number of bytes available for storing an OAD image.
*********************************************************************/
uint32 HalOADAvail(void)
{
/*
preamble_t preamble;
HalOADRead(PREAMBLE_OFFSET, (uint8 *)&preamble, sizeof(preamble_t), HAL_OAD_RC);
return HAL_OAD_DL_MAX - preamble.len;
*/
return HAL_OAD_DL_MAX - HAL_OAD_DL_OSET;
}
#elif HAL_OAD_XNV_IS_SPI
/*********************************************************************
* CONSTANTS
*/
#define XNV_STAT_CMD 0x05
#define XNV_WREN_CMD 0x06
#define XNV_WRPG_CMD 0x0A
#define XNV_READ_CMD 0x0B
#define XNV_STAT_WIP 0x01
/*********************************************************************
* @fn xnvSPIWrite
*
* @brief SPI write sequence for code size savings.
*
* @param ch - The byte to write to the SPI.
*
* @return None.
*********************************************************************/
static void xnvSPIWrite(uint8 ch);
static void xnvSPIWrite(uint8 ch)
{
XNV_SPI_TX(ch);
XNV_SPI_WAIT_RXRDY();
}
/*********************************************************************
* @fn HalOADAvail
*
* @brief Determine the space available for downloading an image.
*
* @param None.
*
* @return Number of bytes available for storing an OAD image.
*********************************************************************/
uint32 HalOADAvail(void)
{
return HAL_OAD_DL_MAX - HAL_OAD_DL_OSET;
}
/*********************************************************************
* @fn HalSPIRead
*
* @brief Read from the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to the buffer in which to copy the bytes read from external NV.
* @param len - Number of bytes to read from external NV.
*
* @return None.
*********************************************************************/
static void HalSPIRead(uint32 addr, uint8 *pBuf, uint16 len)
{
#if !HAL_OAD_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
XNV_SPI_BEGIN();
do {
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_READ_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
xnvSPIWrite(0);
while (len--)
{
xnvSPIWrite(0);
*pBuf++ = XNV_SPI_RX();
}
XNV_SPI_END();
#if !HAL_OAD_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
/*********************************************************************
* @fn HalSPIWrite
*
* @brief Write to the external NV storage via SPI.
*
* @param addr - Offset into the external NV.
* @param pBuf - Pointer to the buffer in from which to write bytes to external NV.
* @param len - Number of bytes to write to external NV.
*
* @return None.
*********************************************************************/
static void HalSPIWrite(uint32 addr, uint8 *pBuf, uint16 len)
{
uint8 cnt;
#if !HAL_OAD_BOOT_CODE
uint8 shdw = P1DIR;
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
P1DIR |= BV(3);
#endif
while (len)
{
XNV_SPI_BEGIN();
do {
xnvSPIWrite(XNV_STAT_CMD);
} while (XNV_SPI_RX() & XNV_STAT_WIP);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WREN_CMD);
XNV_SPI_END();
asm("NOP"); asm("NOP");
XNV_SPI_BEGIN();
xnvSPIWrite(XNV_WRPG_CMD);
xnvSPIWrite(addr >> 16);
xnvSPIWrite(addr >> 8);
xnvSPIWrite(addr);
// Can only write within any one page boundary, so prepare for next page write if bytes remain.
cnt = 0 - (uint8)addr;
if (cnt)
{
addr += cnt;
}
else
{
addr += 256;
}
do
{
xnvSPIWrite(*pBuf++);
cnt--;
len--;
} while (len && cnt);
XNV_SPI_END();
}
#if !HAL_OAD_BOOT_CODE
P1DIR = shdw;
HAL_EXIT_CRITICAL_SECTION(his);
#endif
}
#else
#error Invalid Xtra-NV for OAD.
#endif
/**************************************************************************************************
*/

View File

@@ -0,0 +1,130 @@
/**************************************************************************************************
Filename: hal_oad.h
Revised: $Date:$
Revision: $Revision:$
Description: This module defines optionally-compiled Boot Code parameters for the CC2x3x.
Copyright 2008-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_OAD_H
#define HAL_OAD_H
/*********************************************************************
* INCLUDES
*/
#include "hal_board_cfg.h"
#include "hal_types.h"
/*********************************************************************
* MACROS
*/
#if !defined HAL_OAD_BOOT_CODE
#define HAL_OAD_BOOT_CODE FALSE
#endif
// MSP430 needs to explicitly pack OAD data structures - 8051 is automatic with byte alignment.
#define PACK_1
/*********************************************************************
* CONSTANTS
*/
// Placement controlled by oad.xcl.
#define HAL_OAD_RC_START 0x0800
#define HAL_OAD_CRC_ADDR 0x0888
#define HAL_OAD_CRC_OSET (HAL_OAD_CRC_ADDR - HAL_OAD_RC_START)
/* Note that corresponding changes must be made to oad.xcl when changing the source of Xtra-NV.
* When using internal flash for XNV, (HAL_OAD_BOOT_PG_CNT + HAL_NV_PAGE_CNT) must be even.
*/
#define HAL_OAD_XNV_IS_INT TRUE
#define HAL_OAD_XNV_IS_SPI !HAL_OAD_XNV_IS_INT
/* The oad/oad-boot.xcl files only need 1 page of boot code (located on the first flash page),
* but the Lock Bits Page is lost with OAD since it is not programmable.
* So discard it here by faking that boot needs 2 pages.
*/
#define HAL_OAD_BOOT_PG_CNT 2
/* To reduce the binary image size due to padding un-used code space, reduce HAL_OAD_DL_SIZE
* to the minimum required for your Application and make the corresponding changes to oad_app.xcl.
* This size must be an even multiple of HAL_FLASH_PAGE_SIZE.
*/
#if HAL_OAD_XNV_IS_SPI && !defined HAL_BOARD_CC2530EB_REV13
#define HAL_OAD_DL_MAX 0x40000
#define HAL_OAD_DL_SIZE (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OAD_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OAD_DL_OSET 0x0 // Configurable offset into an external NV.
#else
#define HAL_OAD_DL_MAX (0x40000 - ((HAL_NV_PAGE_CNT+HAL_OAD_BOOT_PG_CNT)*HAL_FLASH_PAGE_SIZE))
#define HAL_OAD_DL_SIZE (HAL_OAD_DL_MAX / 2)
#define HAL_OAD_DL_OSET (HAL_OAD_DL_MAX / 2)
#endif
// To run OAD with the legacy ZOAD.exe PC tool, place the preamble in this legacy location.
#define PREAMBLE_OFFSET 0x8C
#if HAL_OAD_XNV_IS_INT
#define VDD_MIN_OAD VDD_MIN_NV
#else
#error CC2531 OAD by external NV not characterized.
#endif
/*********************************************************************
* TYPEDEFS
*/
typedef enum {
HAL_OAD_RC, /* Run code / active image. */
HAL_OAD_DL /* Downloaded code to be activated later. */
} image_t;
typedef struct {
uint8 magic[2];
uint32 len;
uint16 vers;
uint16 manu;
uint16 prod;
} preamble_t;
/*********************************************************************
* FUNCTIONS
*/
uint8 HalOADChkDL(uint8 dlImagePreambleOffset);
void HalOADInvRC(void);
uint32 HalOADAvail(void);
void HalOADRead(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
void HalOADWrite(uint32 oset, uint8 *pBuf, uint16 len, image_t type);
#endif

View File

@@ -0,0 +1,520 @@
/**************************************************************************************************
Filename: hal_sleep.c
Revised: $Date: 2011-04-04 09:40:22 -0700 (Mon, 04 Apr 2011) $
Revision: $Revision: 25578 $
Description: This module contains the HAL power management procedures for the CC2530.
Copyright 2006-2011 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_types.h"
#include "hal_mcu.h"
#include "hal_board.h"
#include "hal_sleep.h"
#include "hal_led.h"
#include "hal_key.h"
#include "mac_api.h"
#include "OSAL.h"
#include "OSAL_Timers.h"
#include "OSAL_Tasks.h"
#include "OSAL_PwrMgr.h"
#include "OnBoard.h"
#include "hal_drivers.h"
#include "hal_assert.h"
#include "mac_mcu.h"
#ifndef ZG_BUILD_ENDDEVICE_TYPE
# define ZG_BUILD_ENDDEVICE_TYPE FALSE
#endif
#if ZG_BUILD_ENDDEVICE_TYPE && defined (NWK_AUTO_POLL)
#include "nwk_globals.h"
#include "ZGlobals.h"
#endif
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/* POWER CONSERVATION DEFINITIONS
* Sleep mode H/W definitions (enabled with POWER_SAVING compile option)
*/
#define CC2530_PM0 0 /* PM0, Clock oscillators on, voltage regulator on */
#define CC2530_PM1 1 /* PM1, 32.768 kHz oscillators on, voltage regulator on */
#define CC2530_PM2 2 /* PM2, 32.768 kHz oscillators on, voltage regulator off */
#define CC2530_PM3 3 /* PM3, All clock oscillators off, voltage regulator off */
/* HAL power management mode is set according to the power management state. The default
* setting is HAL_SLEEP_OFF. The actual value is tailored to different HW platform. Both
* HAL_SLEEP_TIMER and HAL_SLEEP_DEEP selections will:
* 1. turn off the system clock, and
* 2. halt the MCU.
* HAL_SLEEP_TIMER can be woken up by sleep timer interrupt, I/O interrupt and reset.
* HAL_SLEEP_DEEP can be woken up by I/O interrupt and reset.
*/
#define HAL_SLEEP_OFF CC2530_PM0
#define HAL_SLEEP_TIMER CC2530_PM2
#define HAL_SLEEP_DEEP CC2530_PM3
/* MAX_SLEEP_TIME calculation:
* Sleep timer maximum duration = 0xFFFF7F / 32768 Hz = 511.996 seconds
* Round it to 510 seconds or 510000 ms
*/
#define MAX_SLEEP_TIME 510000 /* maximum time to sleep allowed by ST */
/* minimum time to sleep, this macro is to:
* 1. avoid thrashing in-and-out of sleep with short OSAL timer (~2ms)
* 2. define minimum safe sleep period
*/
#if !defined (PM_MIN_SLEEP_TIME)
#define PM_MIN_SLEEP_TIME 14 /* default to minimum safe sleep time minimum CAP */
#endif
/* The PCON instruction must be 4-byte aligned. The following code may cause excessive power
* consumption if not aligned. See linker file ".xcl" for actual placement.
*/
#pragma location = "SLEEP_CODE"
void halSetSleepMode(void);
/* This value is used to adjust the sleep timer compare value such that the sleep timer
* compare takes into account the amount of processing time spent in function halSleep().
* The first value is determined by measuring the number of sleep timer ticks it from
* the beginning of the function to entering sleep mode or more precisely, when
* MAC_PwrNextTimeout() is called. The second value is determined by measuring the number
* of sleep timer ticks from exit of sleep mode to the call to MAC_PwrOnReq() where the
* MAC timer is restarted.
*/
#define HAL_SLEEP_ADJ_TICKS (11 + 12)
#ifndef HAL_SLEEP_DEBUG_POWER_MODE
/* set CC2530 power mode; always use PM2 */
#define HAL_SLEEP_PREP_POWER_MODE(mode) st( SLEEPCMD &= ~PMODE; /* clear mode bits */ \
SLEEPCMD |= mode; /* set mode bits */ \
while (!(STLOAD & LDRDY)); \
halSleepPconValue = PCON_IDLE; \
)
#define HAL_SLEEP_SET_POWER_MODE() halSetSleepMode()
#else
/* Debug: don't set power mode, just block until sleep timer interrupt */
#define HAL_SLEEP_PREP_POWER_MODE(mode) /* nothing */
#define HAL_SLEEP_SET_POWER_MODE() st( while(halSleepInt == FALSE); \
halSleepInt = FALSE; \
HAL_DISABLE_INTERRUPTS(); \
)
#endif
/* sleep and external interrupt port masks */
#define STIE_BV BV(5)
#define P0IE_BV BV(5)
#define P1IE_BV BV(4)
#define P2IE_BV BV(1)
/* sleep timer interrupt control */
#define HAL_SLEEP_TIMER_ENABLE_INT() st(IEN0 |= STIE_BV;) /* enable sleep timer interrupt */
#define HAL_SLEEP_TIMER_DISABLE_INT() st(IEN0 &= ~STIE_BV;) /* disable sleep timer interrupt */
#define HAL_SLEEP_TIMER_CLEAR_INT() st(STIF = 0;) /* clear sleep interrupt flag */
/* backup interrupt enable registers before sleep */
#define HAL_SLEEP_IE_BACKUP_AND_DISABLE(ien0, ien1, ien2) st(ien0 = IEN0; /* backup IEN0 register */ \
ien1 = IEN1; /* backup IEN1 register */ \
ien2 = IEN2; /* backup IEN2 register */ \
IEN0 &= STIE_BV; /* disable IEN0 except STIE */ \
IEN1 &= P0IE_BV; /* disable IEN1 except P0IE */ \
IEN2 &= (P1IE_BV|P2IE_BV);) /* disable IEN2 except P1IE, P2IE */
/* restore interrupt enable registers before sleep */
#define HAL_SLEEP_IE_RESTORE(ien0, ien1, ien2) st(IEN0 = ien0; /* restore IEN0 register */ \
IEN1 = ien1; /* restore IEN1 register */ \
IEN2 = ien2;) /* restore IEN2 register */
/* convert msec to 320 usec units with round */
#define HAL_SLEEP_MS_TO_320US(ms) (((((uint32) (ms)) * 100) + 31) / 32)
/* for optimized indexing of uint32's */
#if HAL_MCU_LITTLE_ENDIAN()
#define UINT32_NDX0 0
#define UINT32_NDX1 1
#define UINT32_NDX2 2
#define UINT32_NDX3 3
#else
#define UINT32_NDX0 3
#define UINT32_NDX1 2
#define UINT32_NDX2 1
#define UINT32_NDX3 0
#endif
/* ------------------------------------------------------------------------------------------------
* Global Variables
* ------------------------------------------------------------------------------------------------
*/
/* PCON register value to program when setting power mode */
volatile __data uint8 halSleepPconValue = PCON_IDLE;
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
/* HAL power management mode is set according to the power management state.
*/
static uint8 halPwrMgtMode = HAL_SLEEP_OFF;
#ifdef HAL_SLEEP_DEBUG_POWER_MODE
static bool halSleepInt = FALSE;
#endif
/* ------------------------------------------------------------------------------------------------
* Function Prototypes
* ------------------------------------------------------------------------------------------------
*/
void halSleepSetTimer(uint32 timeout);
/**************************************************************************************************
* @fn halSleep
*
* @brief This function put the CC2530 to sleep. The PCON instruction must be 4-byte aligned.
* The following code may cause excessive power consumption if not aligned. See linker
* file ".xcl" for actual placement.
*
* input parameters
*
* @param None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSetSleepMode(void)
{
PCON = halSleepPconValue;
HAL_DISABLE_INTERRUPTS();
}
/**************************************************************************************************
* @fn halSleep
*
* @brief This function is called from the OSAL task loop using and existing OSAL
* interface. It sets the low power mode of the MAC and the CC2530.
*
* input parameters
*
* @param osal_timeout - Next OSAL timer timeout.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSleep( uint16 osal_timeout )
{
uint32 timeout;
uint32 macTimeout = 0;
/* get next OSAL timer expiration converted to 320 usec units */
timeout = HAL_SLEEP_MS_TO_320US(osal_timeout);
if (timeout == 0)
{
timeout = MAC_PwrNextTimeout();
}
else
{
/* get next MAC timer expiration */
macTimeout = MAC_PwrNextTimeout();
/* get lesser of two timeouts */
if ((macTimeout != 0) && (macTimeout < timeout))
{
timeout = macTimeout;
}
}
/* HAL_SLEEP_PM2 is entered only if the timeout is zero and
* the device is a stimulated device.
*/
halPwrMgtMode = (timeout == 0) ? HAL_SLEEP_DEEP : HAL_SLEEP_TIMER;
/* DEEP sleep can only be entered when zgPollRate == 0.
* This is to eliminate any possibility of entering PM3 between
* two network timers.
*/
#if ZG_BUILD_ENDDEVICE_TYPE && defined (NWK_AUTO_POLL)
if ((timeout > HAL_SLEEP_MS_TO_320US(PM_MIN_SLEEP_TIME)) ||
(timeout == 0 && zgPollRate == 0))
#else
if ((timeout > HAL_SLEEP_MS_TO_320US(PM_MIN_SLEEP_TIME)) ||
(timeout == 0))
#endif
{
halIntState_t ien0, ien1, ien2;
HAL_ASSERT(HAL_INTERRUPTS_ARE_ENABLED());
HAL_DISABLE_INTERRUPTS();
/* always use "deep sleep" to turn off radio VREG on CC2530 */
if (halSleepPconValue != 0 && MAC_PwrOffReq(MAC_PWR_SLEEP_DEEP) == MAC_SUCCESS)
{
/* The PCON value is not zero. There is no interrupt overriding the
* sleep decision. Also, the radio granted the sleep request.
*/
#if ((defined HAL_KEY) && (HAL_KEY == TRUE))
/* get peripherals ready for sleep */
HalKeyEnterSleep();
#endif
#ifdef HAL_SLEEP_DEBUG_LED
HAL_TURN_OFF_LED3();
#else
/* use this to turn LEDs off during sleep */
HalLedEnterSleep();
#endif
/* enable sleep timer interrupt */
if (timeout != 0)
{
if (timeout > HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME ))
{
timeout -= HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME );
halSleepSetTimer(HAL_SLEEP_MS_TO_320US( MAX_SLEEP_TIME ));
}
else
{
/* set sleep timer */
halSleepSetTimer(timeout);
}
/* set up sleep timer interrupt */
HAL_SLEEP_TIMER_CLEAR_INT();
HAL_SLEEP_TIMER_ENABLE_INT();
}
#ifdef HAL_SLEEP_DEBUG_LED
if (halPwrMgtMode == CC2530_PM1)
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
#endif
/* Prep CC2530 power mode */
HAL_SLEEP_PREP_POWER_MODE(halPwrMgtMode);
/* save interrupt enable registers and disable all interrupts */
HAL_SLEEP_IE_BACKUP_AND_DISABLE(ien0, ien1, ien2);
HAL_ENABLE_INTERRUPTS();
/* set CC2530 power mode, interrupt is disabled after this function
* Note that an ISR (that could wake up from power mode) which runs
* between the previous instruction enabling interrupts and before
* power mode is set would switch the halSleepPconValue so that
* power mode shall not be entered in such a case.
*/
HAL_SLEEP_SET_POWER_MODE();
/* the interrupt is disabled - see halSetSleepMode() */
/* restore interrupt enable registers */
HAL_SLEEP_IE_RESTORE(ien0, ien1, ien2);
/* disable sleep timer interrupt */
HAL_SLEEP_TIMER_DISABLE_INT();
#ifdef HAL_SLEEP_DEBUG_LED
HAL_TURN_ON_LED3();
#else
/* use this to turn LEDs back on after sleep */
HalLedExitSleep();
#endif
#if ((defined HAL_KEY) && (HAL_KEY == TRUE))
/* handle peripherals */
(void)HalKeyExitSleep();
#endif
/* power on the MAC; blocks until completion */
MAC_PwrOnReq();
HAL_ENABLE_INTERRUPTS();
/* For CC2530, T2 interrupt wont be generated when the current count is greater than
* the comparator. The interrupt is only generated when the current count is equal to
* the comparator. When the CC2530 is waking up from sleep, there is a small window
* that the count may be grater than the comparator, therefore, missing the interrupt.
* This workaround will call the T2 ISR when the current T2 count is greater than the
* comparator. The problem only occurs when POWER_SAVING is turned on, i.e. the 32KHz
* drives the chip in sleep and SYNC start is used.
*/
macMcuTimer2OverflowWorkaround();
}
else
{
/* An interrupt may have changed the sleep decision. Do not sleep at all. Turn on
* the interrupt, exit normally, and the next sleep will be allowed.
*/
HAL_ENABLE_INTERRUPTS();
}
}
}
/**************************************************************************************************
* @fn halSleepSetTimer
*
* @brief This function sets the CC2530 sleep timer compare value. First it reads and
* stores the value of the sleep timer; this value is used later to update OSAL
* timers. Then the timeout value is converted from 320 usec units to 32 kHz
* period units and the compare value is set to the timeout.
*
* input parameters
*
* @param timeout - Timeout value in 320 usec units. The sleep timer compare is set to
* this value.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halSleepSetTimer(uint32 timeout)
{
uint32 ticks;
/* read the sleep timer; ST0 must be read first */
((uint8 *) &ticks)[UINT32_NDX0] = ST0;
((uint8 *) &ticks)[UINT32_NDX1] = ST1;
((uint8 *) &ticks)[UINT32_NDX2] = ST2;
((uint8 *) &ticks)[UINT32_NDX3] = 0;
/* Compute sleep timer compare value. The ratio of 32 kHz ticks to 320 usec ticks
* is 32768/3125 = 10.48576. This is nearly 671/64 = 10.484375.
*/
ticks += (timeout * 671) / 64;
/* subtract the processing time spent in function halSleep() */
ticks -= HAL_SLEEP_ADJ_TICKS;
/* set sleep timer compare; ST0 must be written last */
ST2 = ((uint8 *) &ticks)[UINT32_NDX2];
ST1 = ((uint8 *) &ticks)[UINT32_NDX1];
ST0 = ((uint8 *) &ticks)[UINT32_NDX0];
}
/**************************************************************************************************
* @fn TimerElapsed
*
* @brief Determine the number of OSAL timer ticks elapsed during sleep.
* Deprecated for CC2530 and CC2430 SoC.
*
* input parameters
*
* @param None.
*
* output parameters
*
* None.
*
* @return Number of timer ticks elapsed during sleep.
**************************************************************************************************
*/
uint32 TimerElapsed( void )
{
/* Stubs */
return (0);
}
/**************************************************************************************************
* @fn halRestoreSleepLevel
*
* @brief Restore the deepest timer sleep level.
*
* input parameters
*
* @param None
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void halRestoreSleepLevel( void )
{
/* Stubs */
}
/**************************************************************************************************
* @fn halSleepTimerIsr
*
* @brief Sleep timer ISR.
*
* input parameters
*
* None.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
HAL_ISR_FUNCTION(halSleepTimerIsr, ST_VECTOR)
{
HAL_ENTER_ISR();
HAL_SLEEP_TIMER_CLEAR_INT();
#ifdef HAL_SLEEP_DEBUG_POWER_MODE
halSleepInt = TRUE;
#endif
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}

View File

@@ -0,0 +1,103 @@
/**************************************************************************************************
Filename: hal_startup.c
Revised: $Date: 2010-01-28 16:31:53 -0800 (Thu, 28 Jan 2010) $
Revision: $Revision: 21613 $
Description: Contains code that needs to run before main()
Copyright 2008 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
*************************************************************************************************/
#include "hal_board.h"
#include "hal_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#pragma language=extended
//
// Locate low_level_init in the CSTART module
//
#pragma location="CSTART"
//
// If the code model is banked, low_level_init must be declared
// __near_func elsa a ?BRET is performed
//
#if (__CODE_MODEL__ == 2)
__near_func __root char
#else
__root char
#endif
__low_level_init(void);
/**************************************************************************************************
* @fn __low_level_init
*
* @brief The function __low_level_init is called by the start-up code before doing
* the normal initialization of data segments. If the return value is zero,
* initialization is not performed.
*
* @param None
*
* @return 0 - don't intialize data segments / 1 - do initialization
**************************************************************************************************/
#if (__CODE_MODEL__ == 2)
__near_func __root char
#else
__root char
#endif
__low_level_init(void)
{
/*==================================*/
/* Initialize hardware. */
/*==================================*/
// Map flash bank #1 into XDATA for access to "ROM mapped as data".
MEMCTR = (MEMCTR & 0xF8) | 0x01;
/*==================================*/
/* Choose if segment initialization */
/* should be done or not. */
/* Return: 0 to omit seg_init */
/* 1 to run seg_init */
/*==================================*/
return 1;
}
#pragma language=default
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,45 @@
/**************************************************************************************************
Filename: hal_timer.c
Revised: $Date: 2010-05-28 15:26:34 -0700 (Fri, 28 May 2010) $
Revision: $Revision: 22676 $
Description: This file contains the interface to the Timer Service.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
NOTE: Z-Stack and TIMAC no longer use CC2530 Timer 1, Timer 3, and
Timer 4. The supporting timer driver module is removed and left
for the users to implement their own application timer
functions.
*********************************************************************/

View File

@@ -0,0 +1,103 @@
/**************************************************************************************************
Filename: hal_types.h
Revised: $Date: 2008-03-20 17:17:05 -0700 (Thu, 20 Mar 2008) $
Revision: $Revision: 16618 $
Description: Describe the purpose and contents of the file.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef _HAL_TYPES_H
#define _HAL_TYPES_H
/* Texas Instruments CC2530 */
/* ------------------------------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------------------------------
*/
typedef signed char int8;
typedef unsigned char uint8;
typedef signed short int16;
typedef unsigned short uint16;
typedef signed long int32;
typedef unsigned long uint32;
typedef unsigned char bool;
typedef uint8 halDataAlign_t;
/* ------------------------------------------------------------------------------------------------
* Memory Attributes
* ------------------------------------------------------------------------------------------------
*/
/* ----------- IAR Compiler ----------- */
#ifdef __IAR_SYSTEMS_ICC__
#define CODE __code
#define XDATA __xdata
/* ----------- GNU Compiler ----------- */
#elif defined __KEIL__
#define CODE code
#define XDATA xdata
/* ----------- Unrecognized Compiler ----------- */
#else
#error "ERROR: Unknown compiler."
#endif
/* ------------------------------------------------------------------------------------------------
* Standard Defines
* ------------------------------------------------------------------------------------------------
*/
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef NULL
#define NULL 0
#endif
/**************************************************************************************************
*/
#endif

View File

@@ -0,0 +1,311 @@
/**************************************************************************************************
Filename: _hal_uart.c
Revised: $Date: 2009-06-12 09:16:43 -0700 (Fri, 12 Jun 2009) $
Revision: $Revision: 20142 $
Description: This file contains the interface to the H/W UART driver.
Copyright 2006-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_board_cfg.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_uart.h"
/*********************************************************************
* MACROS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
/*********************************************************************
* LOCAL FUNCTIONS
*/
#if HAL_UART_DMA
#include "_hal_uart_dma.c"
#endif
#if HAL_UART_ISR
#include "_hal_uart_isr.c"
#endif
#if HAL_UART_USB
#include "_hal_uart_usb.c"
#endif
/******************************************************************************
* @fn HalUARTInit
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTInit(void)
{
#if HAL_UART_DMA
HalUARTInitDMA();
#endif
#if HAL_UART_ISR
HalUARTInitISR();
#endif
#if HAL_UART_USB
HalUARTInitUSB();
#endif
}
/******************************************************************************
* @fn HalUARTOpen
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param port - UART port
* config - contains configuration information
*
* @return Status of the function call
*****************************************************************************/
uint8 HalUARTOpen(uint8 port, halUARTCfg_t *config)
{
(void)port;
(void)config;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) HalUARTOpenDMA(config);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) HalUARTOpenDMA(config);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) HalUARTOpenISR(config);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) HalUARTOpenISR(config);
#endif
#if (HAL_UART_USB)
HalUARTOpenUSB(config);
#endif
return HAL_UART_SUCCESS;
}
/*****************************************************************************
* @fn HalUARTRead
*
* @brief Read a buffer from the UART
*
* @param port - USART module designation
* buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
uint16 HalUARTRead(uint8 port, uint8 *buf, uint16 len)
{
(void)port;
(void)buf;
(void)len;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTReadDMA(buf, len);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTReadDMA(buf, len);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTReadISR(buf, len);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTReadISR(buf, len);
#endif
#if HAL_UART_USB
return HalUARTRx(buf, len);
#else
return 0;
#endif
}
/******************************************************************************
* @fn HalUARTWrite
*
* @brief Write a buffer to the UART.
*
* @param port - UART port
* buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
uint16 HalUARTWrite(uint8 port, uint8 *buf, uint16 len)
{
(void)port;
(void)buf;
(void)len;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTWriteDMA(buf, len);
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTWriteDMA(buf, len);
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTWriteISR(buf, len);
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTWriteISR(buf, len);
#endif
#if HAL_UART_USB
HalUARTTx(buf, len);
return len;
#else
return 0;
#endif
}
/******************************************************************************
* @fn HalUARTSuspend
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
void HalUARTSuspend( void )
{
#if HAL_UART_DMA
HalUARTSuspendDMA();
#endif
#if HAL_UART_ISR
HalUARTSuspendISR();
#endif
}
/******************************************************************************
* @fn HalUARTResume
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
void HalUARTResume( void )
{
#if HAL_UART_DMA
HalUARTResumeDMA();
#endif
#if HAL_UART_ISR
HalUARTResumeISR();
#endif
}
/***************************************************************************************************
* @fn HalUARTPoll
*
* @brief Poll the UART.
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTPoll(void)
{
#if HAL_UART_DMA
HalUARTPollDMA();
#endif
#if HAL_UART_ISR
HalUARTPollISR();
#endif
#if HAL_UART_USB
HalUARTPollUSB();
#endif
}
/**************************************************************************************************
* @fn Hal_UART_RxBufLen()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param port - UART port
*
* @return length of current Rx Buffer
**************************************************************************************************/
uint16 Hal_UART_RxBufLen( uint8 port )
{
(void)port;
#if (HAL_UART_DMA == 1)
if (port == HAL_UART_PORT_0) return HalUARTRxAvailDMA();
#endif
#if (HAL_UART_DMA == 2)
if (port == HAL_UART_PORT_1) return HalUARTRxAvailDMA();
#endif
#if (HAL_UART_ISR == 1)
if (port == HAL_UART_PORT_0) return HalUARTRxAvailISR();
#endif
#if (HAL_UART_ISR == 2)
if (port == HAL_UART_PORT_1) return HalUARTRxAvailISR();
#endif
#if HAL_UART_USB
return HalUARTRxAvailUSB();
#else
return 0;
#endif
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,118 @@
/***********************************************************************************
Filename: usb_cdc.h
Description: USB CDC definitions.
***********************************************************************************/
#ifndef USB_CDC_H
#define USB_CDC_H
/* Device Class Code */
#define CDC_DEVICE 0x02
/* Communication Interface Class Code */
#define COMM_INTF 0x02
/* Communication Interface Class SubClass Codes */
#define ABSTRACT_CONTROL_MODEL 0x02
/* Communication Interface Class Control Protocol Codes */
#define V25TER 0x01 // Common AT commands ("Hayes(TM)")
/* Data Interface Class Codes */
#define DATA_INTF 0x0A
/* Data Interface Class Protocol Codes */
#define NO_PROTOCOL 0x00 // No class specific protocol required
/* Communication Feature Selector Codes */
#define ABSTRACT_STATE 0x01
#define COUNTRY_SETTING 0x02
/* Functional Descriptors */
/* Type Values for the bDescType Field */
#define CS_INTERFACE 0x24
#define CS_ENDPOINT 0x25
/* bDescSubType in Functional Descriptors */
#define DSC_FN_HEADER 0x00
#define DSC_FN_CALL_MGT 0x01
#define DSC_FN_ACM 0x02 // ACM - Abstract Control Management
#define DSC_FN_DLM 0x03 // DLM - Direct Line Managment
#define DSC_FN_TELEPHONE_RINGER 0x04
#define DSC_FN_RPT_CAPABILITIES 0x05
#define DSC_FN_UNION 0x06
#define DSC_FN_COUNTRY_SELECTION 0x07
#define DSC_FN_TEL_OP_MODES 0x08
#define DSC_FN_USB_TERMINAL 0x09
/* more.... see Table 25 in USB CDC Specification 1.1 */
#define CDC_COMM_INTF_ID 0x00
#define CDC_DATA_INTF_ID 0x01
// CLASS REQUESTS
#define CDC_SEND_ENCAPSULATED_COMMAND 0x00
#define CDC_GET_ENCAPSULATED_RESPONSE 0x01
#define CDC_SET_COMM_FEATURE 0x02 //optional
#define CDC_GET_COMM_FEATURE 0x03 //optional
#define CDC_CLEAR_COMM_FEATURE 0x04 //optional
#define CDC_SET_LINE_CODING 0x20 //optional
#define CDC_GET_LINE_CODING 0x21 //optional
#define CDC_SET_CONTROL_LINE_STATE 0x22 //optional
#define CDC_SEND_BREAK 0x23 //optional
#define CDC_CHAR_FORMAT_1_STOP_BIT 0
#define CDC_CHAR_FORMAT_1_5_STOP_BIT 1
#define CDC_CHAR_FORMAT_2_STOP_BIT 2
#define CDC_PARITY_TYPE_NONE 0
#define CDC_PARITY_TYPE_ODD 1
#define CDC_PARITY_TYPE_EVEN 2
#define CDC_PARITY_TYPE_MARK 3
#define CDC_PARITY_TYPE_SPACE 4
/*
+------------------------------------------------------------------------------
| Copyright 2004-2009 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,234 @@
/***********************************************************************************
Filename: usb_cdc_descriptor.s51
Description: Descriptor for USB CDC class.
***********************************************************************************/
/*
+------------------------------------------------------------------------------
|The default USB descriptor defines a minimum configuration, with no endpoints
|apart from EP0. The application can define 3 IN and OUT endpoints, and override
|the configuration and interface descriptor (only one of each).
|The device and string descriptors are locked.
+------------------------------------------------------------------------------*/
#define ASM_FILE
#include "..\library\usb_descriptor.h"
#include "usb_cdc.h"
/* Z-Stack needs local definition here - without it CC2531 shows up as CC1111. */
#if !defined chip
#define chip 2531
#endif
MODULE usb_descriptor
RSEG RCODE
PUBLIC usbDescStart;
PUBLIC usbDescEnd;
PUBLIC usbDescLut;
PUBLIC usbDescLutEnd;
PUBLIC usbDblbufLut;
PUBLIC usbDblbufLutEnd;
;;-------------------------------------------------------------------------------------------------------
;; USB descriptors
usbDescStart:
deviceDesc: ; Device descriptor
DB deviceDescEnd - deviceDesc
DB DESC_TYPE_DEVICE ; bDescriptorType
DB 00H, 02H ; bcdUSB
DB CDC_DEVICE ; bDeviceClass
DB 00H ; bDeviceSubClass
DB 00H ; bDeviceProtocol
DB EP0_PACKET_SIZE
DB 51H, 04H ; idVendor Texas Instruments
#if (chip==2531)
DB 0A8H, 16H ; idProduct CC2531
#elif (chip==2511)
DB 0A4H, 16H ; idProduct CC2511
#else
DB 0A6H, 16H ; idProduct CC1111
#endif
DB 09H, 00H ; bcdDevice
DB 01H ; iManufacturer
DB 02H ; iProduct
DB 03H ; iSerialNumber
DB 01H ; bNumConfigurations
deviceDescEnd:
config1LengthStart:
configDesc: ; Configuration descriptor
DB configDescEnd - configDesc
DB DESC_TYPE_CONFIG ; bDescriptorType
DB config1LengthEnd - config1LengthStart, 00H
DB 02H ; NumInterfaces
DB 01H ; bConfigurationValue
DB 00H ; iConfiguration
DB 80H ; bmAttributes
DB 25 ; MaxPower
configDescEnd:
;
; INTERFACE 0
;
interface0Desc: ; Interface descriptor
DB interface0DescEnd - interface0Desc
DB DESC_TYPE_INTERFACE ; bDescriptorType
DB 00H ; bInterfaceNumber
DB 00H ; bAlternateSetting
DB 01H ; bNumEndpoints
DB COMM_INTF ; bInterfaceClass
DB ABSTRACT_CONTROL_MODEL ; bInterfaceSubClass
DB V25TER ; bInterfaceProcotol
DB 00H ; iInterface
interface0DescEnd:
;; CDC Class-Specific Descriptors
headerFunctionalDesc: ; Header Functional Descriptor
DB headerFunctionalDescEnd - headerFunctionalDesc
DB CS_INTERFACE
DB DSC_FN_HEADER
DB 10H, 01H
headerFunctionalDescEnd:
absCtrlManFuncDesc: ; Abstract Control Management Functional Descriptor
DB absCtrlManFuncDescEnd - absCtrlManFuncDesc
DB CS_INTERFACE
DB DSC_FN_ACM
DB 02H ;set the supported class requests
absCtrlManFuncDescEnd:
unionFunctionalDesc: ; Union Functional Descriptor
DB unionFunctionalDescEnd - unionFunctionalDesc
DB CS_INTERFACE
DB DSC_FN_UNION
DB CDC_COMM_INTF_ID
DB CDC_DATA_INTF_ID
unionFunctionalDescEnd:
callMngFuncDesc: ; Call Management Functional Descriptor
DB callMngFuncDescEnd - callMngFuncDesc
DB CS_INTERFACE
DB DSC_FN_CALL_MGT
DB 00H
DB CDC_DATA_INTF_ID
callMngFuncDescEnd:
endpoint0Desc: ; Endpoint descriptor (EP2 IN)
DB endpoint0DescEnd - endpoint0Desc
DB DESC_TYPE_ENDPOINT ; bDescriptorType
DB 82H ; bEndpointAddress
DB EP_ATTR_INT ; bmAttributes
DB 40H, 00H ; wMaxPacketSize
DB 40H ; bInterval
endpoint0DescEnd:
;
; INTERFACE 1
;
interface1Desc: ; Interface descriptor
DB interface1DescEnd - interface1Desc
DB DESC_TYPE_INTERFACE ; Interface descriptor type
DB 01H ; Interface Number
DB 00H ; Alternate Setting Number
DB 02H ; Number of endpoints in this intf
DB DATA_INTF ; Class code
DB 00H ; Subclass code
DB NO_PROTOCOL ; Protocol code
DB 00H ; Interface string index
interface1DescEnd:
endpoint1Desc: ; Endpoint descriptor (EP4 OUT)
DB endpoint1DescEnd - endpoint1Desc
DB DESC_TYPE_ENDPOINT ; bDescriptorType
DB 84H ; bEndpointAddress
DB EP_ATTR_BULK ; bmAttributes
DB 40H, 00H ; wMaxPacketSize
DB 00H ; bInterval
endpoint1DescEnd:
endpoint2Desc: ; Endpoint descriptor (EP4 IN)
DB endpoint2DescEnd - endpoint2Desc
DB DESC_TYPE_ENDPOINT ; bDescriptorType
DB 04H ; bEndpointAddress
DB EP_ATTR_BULK ; bmAttributes
DB 40H, 00H ; wMaxPacketSize
DB 00H ; bInterval
endpoint2DescEnd:
config1LengthEnd:
;;-------------------------------------------------------------------------------------------------------
usbDescEnd:
;;-------------------------------------------------------------------------------------------------------
;;-------------------------------------------------------------------------------------------------------
;; Look-up table for descriptors that are not returned through requests for DSC_DEVICE, DSC_CONFIG or
;; DSC_STRING (e.g. HID report descriptors)
usbDescLut:
usbDescLutEnd:
;;-------------------------------------------------------------------------------------------------------
;;-------------------------------------------------------------------------------------------------------
;; Look-up table for double buffer settings (one set of bit masks for each defined interface)
usbDblbufLut: DW interface0Desc ; pInterface
DB 00H ; inMask
DB 00H ; outMask
DW interface1Desc ; pInterface
DB 00H ; inMask
DB 00H ; outMask
usbDblbufLutEnd:
;;-------------------------------------------------------------------------------------------------------
END;
/*
+------------------------------------------------------------------------------
| Copyright 2004-2010 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
*/

View File

@@ -0,0 +1,156 @@
/***********************************************************************************
Filename: usb_cdc_hooks.c
Contains the necessary hook functions for various USB request processing
that is featured from the USB firmware library. Some
functions are empty.
***********************************************************************************/
/**********************************************************************************
* INCLUDES
*/
#include "usb_cdc.h"
#include "usb_cdc_hooks.h"
#include "usb_firmware_library_headers.h"
#include "hal_types.h"
/* Global data */
CDC_LINE_CODING_STRUCTURE currentLineCoding;
// *********************************************************************************
// All Hooks and functions required by the USB library.
// *********************************************************************************
// **************** Process USB class requests with OUT data phase *****************
void usbcrHookProcessOut(void)
{
// Process USB class requests with OUT data phase, or stall endpoint 0 when unsupported
if (usbSetupHeader.request == CDC_SET_CONTROL_LINE_STATE) {
// Control line state from host
if(usbfwData.ep0Status == EP_IDLE)
{
usbfwData.ep0Status = EP_RX;
}
} else if(usbSetupHeader.request == CDC_SET_LINE_CODING) {
if(usbfwData.ep0Status == EP_IDLE)
{
usbSetupData.pBuffer = (uint8 __xdata *) &currentLineCoding;
usbfwData.ep0Status = EP_RX;
}
else if(usbfwData.ep0Status == EP_RX) { }
}
// Unknown request?
else {
usbfwData.ep0Status = EP_STALL;
}
}
// **************** Process USB class requests with IN data phase ******************
void usbcrHookProcessIn(void)
{
// Process USB class requests with IN data phase, or stall endpoint 0 when unsupported
if (usbSetupHeader.request == CDC_GET_LINE_CODING) {
// First the endpoint status is EP_IDLE...
if (usbfwData.ep0Status == EP_IDLE) {
usbSetupData.pBuffer = (uint8 __xdata *) &currentLineCoding;
usbSetupData.bytesLeft = 7;
usbfwData.ep0Status = EP_TX;
// Then the endpoint status is EP_TX (remember: we did that here when setting up the buffer)
} else if (usbfwData.ep0Status == EP_TX) {
// usbfwData.ep0Status is automatically reset to EP_IDLE when returning to usbfwSetupHandler()
}
} else {
usbfwData.ep0Status = EP_STALL;
}
}
// ******************************** Unsupported USB hooks *************************
void usbvrHookProcessOut(void) {usbfwData.ep0Status = EP_STALL; }
void usbvrHookProcessIn(void) {usbfwData.ep0Status = EP_STALL; }
// ************************ unsupported/unhandled standard requests ***************
void usbsrHookSetDescriptor(void) { usbfwData.ep0Status = EP_STALL; }
void usbsrHookSynchFrame(void) { usbfwData.ep0Status = EP_STALL; }
void usbsrHookClearFeature(void) { usbfwData.ep0Status = EP_STALL; }
void usbsrHookSetFeature(void) { usbfwData.ep0Status = EP_STALL; }
void usbsrHookModifyGetStatus(uint8 recipient, uint8 index, uint16 __xdata *pStatus) { }
// ************************ USB standard request event processing ******************
void usbsrHookProcessEvent(uint8 event, uint8 index)
{
// Process relevant events, one at a time.
switch (event) {
case USBSR_EVENT_CONFIGURATION_CHANGING : //(the device configuration is about to change)
break;
case USBSR_EVENT_CONFIGURATION_CHANGED :// (the device configuration has changed)
break;
case USBSR_EVENT_INTERFACE_CHANGING ://(the alternate setting of the given interface is about to change)
break;
case USBSR_EVENT_INTERFACE_CHANGED : //(the alternate setting of the given interface has changed)
break;
case USBSR_EVENT_REMOTE_WAKEUP_ENABLED ://(remote wakeup has been enabled by the host)
break;
case USBSR_EVENT_REMOTE_WAKEUP_DISABLED ://(remote wakeup has been disabled by the host)
break;
case USBSR_EVENT_EPIN_STALL_CLEARED ://(the given IN endpoint's stall condition has been cleared the host)
break;
case USBSR_EVENT_EPIN_STALL_SET ://(the given IN endpoint has been stalled by the host)
break;
case USBSR_EVENT_EPOUT_STALL_CLEARED ://(the given OUT endpoint's stall condition has been cleared the host)
break;
case USBSR_EVENT_EPOUT_STALL_SET ://(the given OUT endpoint has been stalled by the PC)
break;
}
}
// ************************ USB interrupt event processing *************************
void usbirqHookProcessEvents(void)
{
// Handle events that require immediate processing here
}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,23 @@
/***********************************************************************************
Filename: usb_cdc_hooks.h
Description: USB Virtual UART interface.
***********************************************************************************/
#ifndef USB_CDC_HOOKS_H
#define USB_CDC_HOOKS_H
#include "hal_types.h"
typedef struct {
uint32 dteRate;
uint8 charFormat;
uint8 parityType;
uint8 dataBits;
} CDC_LINE_CODING_STRUCTURE;
extern CDC_LINE_CODING_STRUCTURE currentLineCoding;
#endif

View File

@@ -0,0 +1,68 @@
/***********************************************************************************
Filename: usb_firmware_library_config.c
Description: USB library configuration.
***********************************************************************************/
/// \addtogroup module_usb_firmware_library_config
/// @{
#define USBFIRMWARELIBRARYCONFIG_C ///< Modifies the behavior of "EXTERN" in usb_interrupt.h
#include "usb_firmware_library_headers.h"
//-----------------------------------------------------------------------------
// READ THIS!!
//
// This file configures the USB Firmware Library.
// To use the library, make a copy of this file, rename it to "usb_firmware_library_config.c", and
// put it in the project catalog. Then edit the code below as needed:
//-----------------------------------------------------------------------------
// Declaration of global USB descriptor pointers
USB_DESCRIPTOR_MARKER usbDescriptorMarker= {
(uint8 __code *)&usbDescStart,
(uint8 __code *)&usbDescEnd,
(DESC_LUT_INFO __code *) &usbDescLut,
(DESC_LUT_INFO __code *) &usbDescLutEnd,
(DBLBUF_LUT_INFO __code *) &usbDblbufLut,
(DBLBUF_LUT_INFO __code *) &usbDblbufLutEnd
};
/// @}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,64 @@
/***********************************************************************************
Filename: usb_firmware_library_config.h
Description: USB library configuration.
***********************************************************************************/
#ifndef USBFIRMWARELIBRARYCONFIG_H // Don't modify
#define USBFIRMWARELIBRARYCONFIG_H // Don't modify
//-----------------------------------------------------------------------------
// READ THIS!!
//
// This file configures the USB Firmware Library.
// To use the library, make a copy of this file, rename it to "usb_firmware_library_config.h", and
// put it in the project catalog. Then edit the definitions below:
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
// Defines
// Enter the maximum number of interfaces that are used in the configurations (used to calculate the size
// of the table that stores the currently selected alternate setting for each interface)
#define USB_SETUP_MAX_NUMBER_OF_INTERFACES 5
#endif //#ifndef USBFIRMWARELIBRARYCONFIG_H
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,64 @@
/***********************************************************************************
Filename: usb_firmware_library_headers.h
Description: Common inclusion of all USB library headers.
***********************************************************************************/
#ifndef USB_FIRMWARE_LIBRARY_HEADERS_H
#define USB_FIRMWARE_LIBRARY_HEADERS_H
// This file includes all of the USB Library header files.
// When using the library, include this file only.
// Also make a copy of usb_firmware_library_config_template.c and usb_firmware_library_config_template.h
// and add it to your project as usb_firmware_library_config.c and
// usb_firmware_library_config.h. The definitions in these files should be adapted to your project.
#include "usb_firmware_library_config.h"
#include "usb_descriptor.h"
#include "usb_descriptor_parser.h"
#include "usb_interrupt.h"
#include "usb_framework.h"
#include "usb_reg.h"
#include "usb_standard_requests.h"
#include "usb_suspend.h"
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif //USB_FIRMWARE_LIBRARY_HEADERS_H

View File

@@ -0,0 +1,130 @@
;
; Texas Instruments CC2531 Low-power RF to USB Serial Port example setup file
;
; based on Windows USB CDC ACM Setup file
; Copyright (c) 2000 Microsoft Corporation
; Copyright (C) 2009 Texas Instruments Inc
[Version]
Signature="$Windows NT$"
Class=Ports
ClassGuid={4D36E978-E325-11CE-BFC1-08002BE10318}
Provider=%PROVIDER%
LayoutFile=layout.inf
DriverVer=05/01/2009,1.1.0.0
[Manufacturer]
%MFGNAME%=DeviceList, NTx86, NTia64, NTamd64
[DestinationDirs]
DefaultDestDir=12
[SourceDisksFiles]
[SourceDisksNames]
[DeviceList.NTx86]
%DESCRIPTION%=DriverInstall, USB\VID_0451&PID_16A8
[DeviceList.NTia64]
%DESCRIPTION%=DriverInstall, USB\VID_0451&PID_16A8
[DeviceList.NTamd64]
%DESCRIPTION%=DriverInstall, USB\VID_0451&PID_16A8
;------------------------------------------------------------------------------
; 32-bit section for Windows 2000/2003/XP/Vista
;------------------------------------------------------------------------------
[DriverInstall.NTx86]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTx86.AddReg
[DriverInstall.NTx86]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTx86.AddReg
[DriverCopyFiles]
usbser.sys,,,0x20
[DriverInstall.NTx86.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.NTx86.Services]
AddService=usbser, 0x00000002, DriverService
;------------------------------------------------------------------------------
; 64-bit section for Intel Itanium based systems
;------------------------------------------------------------------------------
[DriverInstall.NTia64]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTia64.AddReg
[DriverInstall.NTia64]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTia64.AddReg
[DriverCopyFiles]
usbser.sys,,,0x20
[DriverInstall.NTia64.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.NTia64.Services]
AddService=usbser, 0x00000002, DriverService
;------------------------------------------------------------------------------
; 64-bit section for AMD64 and Intel EM64T based systems
;------------------------------------------------------------------------------
[DriverInstall.NTamd64]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTamd64.AddReg
[DriverInstall.NTamd64]
include=mdmcpq.inf
CopyFiles=DriverCopyFiles
AddReg=DriverInstall.NTamd64.AddReg
[DriverCopyFiles]
usbser.sys,,,0x20
[DriverInstall.NTamd64.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,usbser.sys
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
[DriverInstall.NTamd64.Services]
AddService=usbser, 0x00000002, DriverService
;------------------------------------------------------------------------------
;
;------------------------------------------------------------------------------
[DriverService]
DisplayName=%SERVICE%
ServiceType=1
StartType=3
ErrorControl=1
ServiceBinary=%12%\usbser.sys ;;%12% == "%WINDIR%\system32\"
;------------------------------------------------------------------------------
; String Definitions
;------------------------------------------------------------------------------
[Strings]
PROVIDER="Texas Instruments"
MFGNAME="Texas Instruments"
DESCRIPTION="TI CC2531 Low-Power RF to USB CDC Serial Port"
SERVICE="TI CC2531 Low-Power RF to USB CDC Serial Port"

View File

@@ -0,0 +1,162 @@
/**************************************************************************************************
Filename: usb_board_cfg.h
Revised: $Date:$
Revision: $Revision:$
Description:
This file implements the Temperature/Voltage Sample Application.
Copyright 2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef USB_BOARD_CFG_H
#define USB_BOARD_CFG_H
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board_cfg.h"
#include "hal_mcu.h"
#include "ioCC2531.h"
#include "usb_reg.h"
/* ------------------------------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------------------------------
*/
#define HAL_BOARD_IO_USB_ENABLE_PORT 1 // USB pull-up enable
#define HAL_BOARD_IO_USB_ENABLE_PIN 0
#define BIT0 0x01
#define BIT1 0x02
#define BIT2 0x04
#define BIT3 0x08
#define BIT4 0x10
#define BIT5 0x20
#define BIT6 0x40
#define BIT7 0x80
#if !defined HAL_UART_USB_SUSPEND
#define HAL_UART_USB_SUSPEND FALSE
#endif
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
#define HAL_USB_ENABLE() st( USBCTRL= USBCTRL_PLL_EN | USBCTRL_USB_EN; \
while (!(USBCTRL&USBCTRL_PLL_LOCKED)); )
#define HAL_USB_PLL_DISABLE() st( USBCTRL&= ~USBCTRL_PLL_EN; \
while (USBCTRL&USBCTRL_PLL_LOCKED); )
#define HAL_USB_DISABLE st(USBCTRL = 0; while (USBCTRL & 0x80);)
#define HAL_USB_PULLUP_ENABLE() \
MCU_IO_OUTPUT(HAL_BOARD_IO_USB_ENABLE_PORT, HAL_BOARD_IO_USB_ENABLE_PIN, 1)
#define HAL_USB_PULLUP_DISABLE() \
MCU_IO_OUTPUT(HAL_BOARD_IO_USB_ENABLE_PORT, HAL_BOARD_IO_USB_ENABLE_PIN, 0)
#define HAL_USB_INT_ENABLE() st( P2IEN|= 0x20; IEN2|= 0x02; )
#define HAL_USB_INT_DISABLE() st( P2IEN&= ~0x20; )
#define HAL_USB_INT_CLEAR() st( P2IFG= 0; P2IF= 0; )
#define HAL_USB_RESUME_INT_ENABLE() st ( USBCIE |= 0x02; )
#define HAL_USB_RESUME_INT_DISABLE() st ( USBCIE &= ~0x02; )
#define USBCTRL_PLL_LOCKED 0x80
#define USBCTRL_PLL_EN 0x02
#define USBCTRL_USB_EN 0x01
#define P2IFG_DPIF 0x20
#define CC2530_IS_XOSC_STABLE() (SLEEPSTA & XOSC_STB)
#define NOP() asm("NOP")
#define MCU_IO_TRISTATE 1 // Used as "func" for the macros below
#define MCU_IO_PULLUP 2
#define MCU_IO_PULLDOWN 3
//-----------------------------------------------------------------------------
// Macros for simple configuration of IO pins on TI LPW SoCs
//-----------------------------------------------------------------------------
#define MCU_IO_PERIPHERAL(port, pin) MCU_IO_PERIPHERAL_PREP(port, pin)
#define MCU_IO_INPUT(port, pin, func) MCU_IO_INPUT_PREP(port, pin, func)
#define MCU_IO_OUTPUT(port, pin, val) MCU_IO_OUTPUT_PREP(port, pin, val)
#define MCU_IO_SET(port, pin, val) MCU_IO_SET_PREP(port, pin, val)
#define MCU_IO_SET_HIGH(port, pin) MCU_IO_SET_HIGH_PREP(port, pin)
#define MCU_IO_SET_LOW(port, pin) MCU_IO_SET_LOW_PREP(port, pin)
#define MCU_IO_TGL(port, pin) MCU_IO_TGL_PREP(port, pin)
#define MCU_IO_GET(port, pin) MCU_IO_GET_PREP(port, pin)
#define MCU_IO_DIR_INPUT(port, pin) MCU_IO_DIR_INPUT_PREP(port, pin)
#define MCU_IO_DIR_OUTPUT(port, pin) MCU_IO_DIR_OUTPUT_PREP(port, pin)
//----------------------------------------------------------------------------------
// Macros for internal use (the macros above need a new round in the preprocessor)
//----------------------------------------------------------------------------------
#define MCU_IO_PERIPHERAL_PREP(port, pin) st( P##port##SEL |= BV(pin); )
#define MCU_IO_INPUT_PREP(port, pin, func) st( P##port##SEL &= ~BV(pin); \
P##port##DIR &= ~BV(pin); \
switch (func) { \
case MCU_IO_PULLUP: \
P##port##INP &= ~BV(pin); \
P2INP &= ~BV(port + 5); \
break; \
case MCU_IO_PULLDOWN: \
P##port##INP &= ~BV(pin); \
P2INP |= BV(port + 5); \
break; \
default: \
P##port##INP |= BV(pin); \
break; } )
#define MCU_IO_OUTPUT_PREP(port, pin, val) st( P##port##SEL &= ~BV(pin); \
P##port##_##pin## = val; \
P##port##DIR |= BV(pin); )
#define MCU_IO_SET_HIGH_PREP(port, pin) st( P##port##_##pin## = 1; )
#define MCU_IO_SET_LOW_PREP(port, pin) st( P##port##_##pin## = 0; )
#define MCU_IO_SET_PREP(port, pin, val) st( P##port##_##pin## = val; )
#define MCU_IO_TGL_PREP(port, pin) st( P##port##_##pin## ^= 1; )
#define MCU_IO_GET_PREP(port, pin) (P##port## & BV(pin))
#define MCU_IO_DIR_INPUT_PREP(port, pin) st( P##port##DIR &= ~BV(pin); )
#define MCU_IO_DIR_OUTPUT_PREP(port, pin) st( P##port##DIR |= BV(pin); )
#endif
/**************************************************************************************************
*/

View File

@@ -0,0 +1,140 @@
/***********************************************************************************
Filename: usb_interrupt.c
Description: USB library interrupt initialisation and ISR.
***********************************************************************************/
/// \addtogroup module_usb_interrupt
/// @{
#define USBINTERRUPT_C ///< Modifies the behavior of "EXTERN" in usb_interrupt.h
#include "usb_firmware_library_headers.h"
#include "usb_board_cfg.h"
#include "hal_flash.h"
#include "hal_led.h"
/** \brief Initializes the \ref module_usb_interrupt module
*
* This function should be called after the \ref module_usb_framework module has been initialized.
* Use interrupt group priority control (refer to the CC2531 datasheet) to adjust the priority of the
* USB interrupt relative to other interrupts.
*
* \param[in] irqMask
* A bit mask containing USBIRQ_EVENT bits for all events that shall be reported
*/
void usbirqInit(uint16 irqMask)
{
// Initialize variables
usbirqData.eventMask = 0x0000;
usbirqData.inSuspend = FALSE;
usbirqData.irqMask = irqMask;
// Select which IRQ flags to handle
USBCIE = irqMask;
USBIIE = irqMask >> 4;
USBOIE = (irqMask >> 9) & 0x3E;
HAL_USB_INT_CLEAR();
HAL_USB_INT_ENABLE();
} // usbirqInit
/** \brief USB interrupt handler
*
* Clears the P2 interrupt flag and converts all USB interrupt flags into events.
* The interrupt also lets \ref usbsuspEnter() break from the suspend loop.
*/
#if defined HAL_SB_BOOT_CODE
void usbirqHandler(void)
#else
#pragma vector=P2INT_VECTOR
__interrupt void usbirqHandler(void)
#endif
{
uint8 usbcif;
// First make sure that the crystal oscillator is stable
while (!CC2530_IS_XOSC_STABLE());
// Special handling for reset interrupts
usbcif = USBCIF;
if (usbcif & USBCIF_RSTIF) {
// All interrupts (except suspend) are by default enabled by hardware, so
// re-initialize the enable bits to avoid unwanted interrupts
USBCIE = usbirqData.irqMask;
USBIIE = usbirqData.irqMask >> 4;
USBOIE = (usbirqData.irqMask >> 9) & 0x3E;
// Enable suspend mode when suspend signaling is detected on the bus
USBPOW |= USBPOW_SUSPEND_EN;
}
// Record events (keeping existing)
usbirqData.eventMask |= (uint16) usbcif;
usbirqData.eventMask |= (uint16) USBIIF << 4;
usbirqData.eventMask |= (uint16) USBOIF << 9;
// If we get a suspend event, we should always enter suspend mode. We must,
// however be sure that we exit the suspend loop upon resume or reset
// signaling.
if (usbcif & USBCIF_SUSPENDIF) {
usbirqData.inSuspend = TRUE;
}
if (usbcif & (USBCIF_RSTIF | USBCIF_RESUMEIF)) {
usbirqData.inSuspend = FALSE;
}
if (P2IFG & P2IFG_DPIF) {
// Resume interrupt detected on D+ line while in suspend
P2IFG = ~P2IFG_DPIF;
usbirqData.inSuspend = FALSE;
}
// Handle event which need immediate processing
usbirqHookProcessEvents();
// Clear the interrupt
HAL_USB_INT_CLEAR();
} // usbirqHandler
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2008-2009 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,139 @@
/***********************************************************************************
Filename: usb_suspend.c
Description: USB library common functionality.
***********************************************************************************/
/// \addtogroup module_usb_suspend
/// @{
#include "usb_firmware_library_headers.h"
#include "hal_board.h"
#include "hal_mcu.h"
#include "hal_led.h"
__xdata VFPTR pFnSuspendEnterHook= NULL;
__xdata VFPTR pFnSuspendExitHook= NULL;
#if HAL_UART_USB_SUSPEND
extern void halEnterPowerMode(void);
/** \brief Puts the chip into power mode 1 during USB suspend.
*
* This function must be called from main (i.e. not from interrupt context) upon the reception of a
* \ref USBIRQ_EVENT_SUSPEND event. To comply with the USB specification, this must happen within 10 ms
* after the event occurs. The chip will stay in power mode 1 until a USB resume or USB reset is detected
* on the USB bus, or remote wakeup is used. During this period, the MCU can only run code from
* interrupt context.
*/
void usbsuspEnter(void)
{
if (pFnSuspendEnterHook!=NULL)
pFnSuspendEnterHook();
HAL_USB_INT_CLEAR();
HAL_USB_INT_ENABLE();
// Disable USB clock (PLL) before entering PM1
HAL_USB_PLL_DISABLE();
HAL_LED_CLR_1();
do {
// Enter PM1, in prescribed manner as explained in CC253x User's Guide
SLEEPCMD = 0x05;
halEnterPowerMode();
} while ( usbirqData.inSuspend );
// .... we are now up and running again
// First make sure that the crystal oscillator is stable
while (!CC2530_IS_XOSC_STABLE());
// Restart the USB clock (PLL)
HAL_USB_ENABLE();
if (pFnSuspendExitHook!=NULL)
pFnSuspendExitHook();
} // usbsuspEnter
#endif
/** \brief Attempts USB remote wakeup.
*
* This function can be called from interrupt context while the USB device is suspend mode. If the device
* is privileged to do so (see \c usbfwData.remoteWakeup and the \ref USBSR_EVENT_REMOTE_WAKEUP_ENABLED
* and \ref USBSR_EVENT_REMOTE_WAKEUP_DISABLED events), remote wakeup will be performed. Note that this
* function will block for 10 ms while the resume signal is set on the bus. Note: This function can only
* be called when the 48 MHz XOSC is stable.
*
* \return
* \c TRUE if the remote wakeup was performed (the privilege had been granted), otherwise \c FALSE
* (the device is still in suspend mode).
*/
uint8 usbsuspDoRemoteWakeup(void)
{
extern void halMcuWaitMs(uint16 msec);
halIntState_t intState;
// Make sure that it's OK
if (!usbfwData.remoteWakeup) return FALSE;
HAL_ENTER_CRITICAL_SECTION(intState);
// Make sure that the suspend loop does not power down the chip again
usbirqData.inSuspend = FALSE;
// Perform remote wakeup by holding the USB resume signal for 10 ms
USBPOW |= USBPOW_RESUME;
halMcuWaitMs(10);
USBPOW &= ~USBPOW_RESUME;
// Clear the interrupt flag
HAL_USB_INT_CLEAR();
HAL_EXIT_CRITICAL_SECTION(intState);
return TRUE;
} // usbsuspDoRemoteWakeup
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2009 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,199 @@
/***********************************************************************************
Filename: usb_descriptor.h
Description: Interface to USB descriptors.
***********************************************************************************/
#ifndef USBDESCRIPTOR_H
#define USBDESCRIPTOR_H
#ifndef ASM_FILE
#include "usb_framework_structs.h"
#endif
/** \addtogroup module_usb_descriptor USB Descriptor
* \brief This module contains contains USB descriptor definitions, and guidelines on how to write
* descriptor sets that work with the USB library.
*
* Information on the specific USB descriptor types is available in the USB 2.0 specification and
* in device class documentation. Examples of complete descriptor sets can be found in the Chipcon USB
* application examples.
*
* \section section_usbdsc_standard Standard Descriptors
* The library requires the USB descriptor set to be organized as follows:
* - Device descriptor (\ref USB_DEVICE_DESCRIPTOR)
* - Configuration descriptor (\ref USB_CONFIGURATION_DESCRIPTOR)
* - Interface descriptor (\ref USB_INTERFACE_DESCRIPTOR)
* - Endpoint descriptor (\ref USB_ENDPOINT_DESCRIPTOR)
* - More endpoint descriptors
* - More interface descriptors
* - More configuration descriptors
* - String descriptor (\ref USB_STRING_DESCRIPTOR)
* - More string descriptors
*
* Different USB device classes, such as "HID" and "Audio", may add other standard format descriptor
* types to the hierarchy, and even extend the existing types. This is also supported by the library.
*
* Refer to the \ref module_usb_descriptor_parser module for information on
* \li Where in memory the descriptor set can be placed
* \li How to set the required markers (symbols), \ref usbDescStart and \ref usbDescEnd.
*
* \section section_usbdsc_other Other Descriptors
* Differently formatted descriptors are not supported by the parsing mechanism, and are instead located
* through a \ref DESC_LUT_INFO look-up table. Each entry in the \ref usbDescLut table contains the
* index and value parameters for relevant \ref GET_DESCRIPTOR requests, and the locations and lengths
* of the corresponding descriptors:
* \code
* ; Make the symbols public
* PUBLIC usbDescLut;
* PUBLIC usbDescLutEnd;
*
* ...
*
* usbDescLut: DB HID_REPORT, 00H ; value (MSB, LSB)
* DB 00H, 00H ; index (MSB, LSB)
* DW hidReportDesc0Start ; pDescStart
* DW hidReportDesc0End - hidReportDesc0Start ; length
*
* DB HID_REPORT, 01H ; value (MSB, LSB)
* DB 00H, 00H ; index (MSB, LSB)
* DW hidReportDesc1Start ; pDescStart
* DW hidReportDesc1End - hidReportDesc1Start ; length
* usbDescLutEnd:
* \endcode
*
* An additional look-up table is needed configure endpoint double-buffering. The table must contain one
* \ref DBLBUF_LUT_INFO entry for each interface descriptor with non-zero \c bNumEndpoints:
* \code
* ; Make the symbol public
* PUBLIC usbDblbufLut;
*
* ...
*
* usbDblbufLut: DW interface0Desc ; pInterface
* DB 02H ; inMask (example: EP1 IN is double-buffered)
* DB 00H ; outMask (example: No double-buffered OUT endpoints)
*
* DW interface1Desc ; pInterface
* DB 10H ; inMask (example: EP4 IN is double-buffered)
* DB 08H ; outMask (example: EP3 OUT is double-buffered)
* \endcode
* @{
*/
#ifdef EXTERN
#undef EXTERN
#endif
#ifdef USBDESCRIPTORPARSER_C
#define EXTERN ///< Definition used only for usb_descriptor_parser.c
#else
#define EXTERN extern ///< Definition used in other source files to declare external
#endif
//-------------------------------------------------------------------------------------------------------
/// \name Sizes
//@{
#define EP0_PACKET_SIZE 32 ///< The maximum data packet size for endpoint 0
//@}
/// \name Standard Descriptor Types
//@{
#define DESC_TYPE_DEVICE 0x01 ///< Device
#define DESC_TYPE_CONFIG 0x02 ///< Configuration
#define DESC_TYPE_STRING 0x03 ///< String
#define DESC_TYPE_INTERFACE 0x04 ///< Interface
#define DESC_TYPE_ENDPOINT 0x05 ///< Endpoint
//@}
/// \name HID Class Descriptor Types
//@{
#define DESC_TYPE_HID 0x21 ///< HID descriptor (included in the interface descriptor)
#define DESC_TYPE_HIDREPORT 0x22 ///< Report descriptor (referenced in \ref usbDescLut)
//@}
/// \name Endpoint Types
//@{
#define EP_ATTR_CTRL 0x00 ///< Control (endpoint 0 only)
#define EP_ATTR_ISO 0x01 ///< Isochronous (not acknowledged)
#define EP_ATTR_BULK 0x02 ///< Bulk
#define EP_ATTR_INT 0x03 ///< Interrupt (guaranteed polling interval)
#define EP_ATTR_TYPE_BM 0x03 ///< Endpoint type bitmask
//@}
//-------------------------------------------------------------------------------------------------------
#ifndef ASM_FILE
//-------------------------------------------------------------------------------------------------------
/// \name USB Descriptor Marker
//@{
/// USB descriptor markers which the USB Firmware Library imports from the application
typedef struct {
uint8 __code* const pUsbDescStart; ///< USB descriptor start pointer
uint8 __code* const pUsbDescEnd; ///< USB descriptor end pointer
DESC_LUT_INFO __code* const pUsbDescLut; ///< Start of USB desc look-up table pointer
DESC_LUT_INFO __code* const pUsbDescLutEnd; ///< End of USB desc look-up table pointer
DBLBUF_LUT_INFO __code* const pUsbDblbufLut; ///< Start of double-buffering look-up table pointer
DBLBUF_LUT_INFO __code* const pUsbDblbufLutEnd; ///< End of double-buffering look-up table pointer
} USB_DESCRIPTOR_MARKER;
extern USB_DESCRIPTOR_MARKER __xdata usbDescriptorMarker; ///< USB descriptor marker
//-------------------------------------------------------------------------------------------------------
// Import marker symbols for the USB descriptor to use (from <app>_usb_descriptor.s51)
// They need to be defined here or in application FW
// The source file <app>_usb_descriptor.s51 need to use these names, or update
// the names used here with the ones used in <app>_usb_descriptor.s51.
extern void __code* usbDescStart; ///< Pointer to start of (standard) USB descriptor
extern void __code* usbDescEnd; ///< Pointer to end of (standard) USB descriptor
extern void __code* usbDescLut; ///< Pointer to start of lookup table for non-standard USB descriptors
extern void __code* usbDescLutEnd; ///< Pointer to end of lookup table for non-standard USB descriptors
extern void __code* usbDblbufLut; ///< Pointer to start of lookup table for endpoints' double-buffer settings
extern void __code* usbDblbufLutEnd; ///< Pointer to end of lookup table for endpoints' double-buffer settings
//@}
#endif // ASM_FILE
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2009 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,362 @@
/***********************************************************************************
Filename: usb_descriptor_parser.c
Description: Parser for USB descriptor structures.
***********************************************************************************/
/// \addtogroup module_usb_descriptor_parser
/// @{
#define USBDESCRIPTORPARSER_C ///< Modifies the behavior of "EXTERN" in usb_descriptor_parser.h
#include "usb_firmware_library_headers.h"
#include "hal_flash.h"
#include "OnBoard.h"
#include "ZComDef.h"
//-------------------------------------------------------------------------------------------------------
// USBDP internal module data
static USBDP_DATA __xdata usbdpData; ///< USBDP internal module data
//-------------------------------------------------------------------------------------------------------
// String descriptors (2-byte unicode data).
// Language ID.
static const uint8 languageId[4] = {
4,
DESC_TYPE_STRING,
0x09, 0x04 /* US-EN */
};
// Manufacturer.
static const uint8 manufacturer[36] = {
36,
DESC_TYPE_STRING,
'T', 0,
'e', 0,
'x', 0,
'a', 0,
's', 0,
' ', 0,
'I', 0,
'n', 0,
's', 0,
't', 0,
'r', 0,
'u', 0,
'm', 0,
'e', 0,
'n', 0,
't', 0,
's', 0
};
// Product.
static const uint8 product[36] = {
36,
DESC_TYPE_STRING,
'T', 0,
'I', 0,
' ', 0,
'C', 0,
'C', 0,
'2', 0,
'5', 0,
'3', 0,
'1', 0,
' ', 0,
'U', 0,
'S', 0,
'B', 0,
' ', 0,
'C', 0,
'D', 0,
'C', 0
};
// Serial Number.
static uint8 serialNumber[42] = {
0, // Initializing to zero vice 42 is the indication to usbdpGetStringDesc() to fill w/ IEEE.
DESC_TYPE_STRING,
// Setup for using the 16 nibbles of the hex representation of the IEEE address.
'_', 0,
'_', 0,
'0', 0,
'X', 0,
};
const uint8 hexDigit[16] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/** \brief Initializes a search
*
* This function must be called before each new search to reset \ref USBDP_DATA.pDesc.
*/
void usbdpInit(void)
{
usbdpData.pDesc = (const uint8 __code *) usbDescriptorMarker.pUsbDescStart;
} // usbdpInit
/** \brief Locates the descriptor of the wanted type
*
* This function parses through the USB descriptors until:
* \li It hits one with <tt>bDescriptorType = wantedType</tt>, in which case it returns a pointer to
* that descriptor, and exits. \ref USBDP_DATA.pDesc will then point to the next descriptor.
* \li It hits one with <tt>bDescriptorType = haltAtType</tt>, in which case it returns a NULL-pointer,
* and exits. \ref USBDP_DATA.pDesc will then point to that descriptor.
* \li \ref USBDP_DATA.pDesc = \ref usbDescEnd, in which case it returns a NULL-pointer, and exits.
* \ref USBDP_DATA.pDesc will continue to point to \ref usbDescEnd.
*
* \note To begin a search with this function, \ref usbdpInit should be called first. It should not be
* called when continuing a search - for instance after a call to \ref usbdpGetConfigurationDesc().
*
* \param[in] wantedType
* The wanted descriptor type (e.g. \ref DESC_TYPE_CONFIG)
* \param[in] haltAtType
* The parser halts when it reaches this descriptor type, unless \c haltAtType is \c 0 (which in any
* case is an invalid \c bDescriptorType value).
*
* \return
* A pointer to the wanted descriptor type, or \c NULL if it was not found.
*/
void __code* usbdpFindNext(uint8 wantedType, uint8 haltAtType)
{
void __code *pResult;
pResult = NULL;
// As long as we haven't reached the end...
while (usbdpData.pDesc != (void __code *) usbDescriptorMarker.pUsbDescEnd) {
// If we have a match on wantedType...
if (usbdpData.pDesc[DESC_TYPE_IDX] == wantedType) {
pResult = (void __code*) usbdpData.pDesc;
usbdpData.pDesc += usbdpData.pDesc[DESC_LENGTH_IDX];
break;
// If we have a match on haltAtType...
} else if (usbdpData.pDesc[DESC_TYPE_IDX] == haltAtType) {
if (haltAtType) break;
}
// Move on to the next descriptor
usbdpData.pDesc += usbdpData.pDesc[DESC_LENGTH_IDX];
}
return pResult;
} // usbdpFindNext
/** \brief Locates the (one and only) device descriptor
*
* \note It is not necessary to call \ref usbdpInit() before this function.
*
* \return
* A pointer to the \ref USB_DEVICE_DESCRIPTOR, or \c NULL if it was not found.
*/
USB_DEVICE_DESCRIPTOR __code* usbdpGetDeviceDesc(void)
{
usbdpInit();
return usbdpFindNext(DESC_TYPE_DEVICE, 0);
} // usbdpGetDeviceDesc
/** \brief Locates a configuration descriptor
*
* The search will either look for a descriptor with a specific
* \ref USB_CONFIGURATION_DESCRIPTOR.bConfigurationValue, or simply take the n'th descriptor (by "index")
*
* \note It is not necessary to call \ref usbdpInit() before this function.
*
* \param[in] cfgValue
* The configuration value to search for (\ref USB_CONFIGURATION_DESCRIPTOR.bConfigurationValue), or
* 0 to find descriptor by index
* \param[in] cfgIndex
* A zero-based index for the configuration descriptor to find.
* This value is ignored unless \c cfgValue is 0.
*
* \return
* A pointer to the \ref USB_DEVICE_DESCRIPTOR, or \c NULL if it was not found.
*/
USB_CONFIGURATION_DESCRIPTOR __code* usbdpGetConfigurationDesc(uint8 cfgValue, uint8 cfgIndex)
{
USB_CONFIGURATION_DESCRIPTOR __code *pConfigurationDesc;
usbdpInit();
// As long as there are more configuration descriptors...
while (pConfigurationDesc = usbdpFindNext(DESC_TYPE_CONFIG, 0)) {
// Search by value?
if (cfgValue) {
if (cfgValue == pConfigurationDesc->bConfigurationValue) break;
// Search by index? (search cfgIndex+1 times)
} else if (!cfgIndex--) {
break;
}
}
return pConfigurationDesc;
} // usbdpGetConfigurationDesc
/** \brief Locates an interface descriptor
*
* The function will first go to the configuration descriptor that matches the supplied configuration
* value, and then locate the interface descriptor that matches the given interface number and alternate
* setting.
*
* \note It is not necessary to call \ref usbdpInit() before this function.
*
* \param[in] cfgValue
* The configuration value (\ref USB_CONFIGURATION_DESCRIPTOR.bConfigurationValue)
* \param[in] intNumber
* The interface number (\ref USB_INTERFACE_DESCRIPTOR.bInterfaceNumber)
* \param[in] altSetting
* The alternate setting (\ref USB_INTERFACE_DESCRIPTOR.bAlternateSetting)
*
* \return
* A pointer to the \ref USB_INTERFACE_DESCRIPTOR, or \c NULL if it was not found.
*/
USB_INTERFACE_DESCRIPTOR __code* usbdpGetInterfaceDesc(uint8 cfgValue, uint8 intNumber, uint8 altSetting)
{
USB_INTERFACE_DESCRIPTOR __code *pInterfaceDesc;
// First get to the correct configuration
usbdpGetConfigurationDesc(cfgValue, 0);
// Then find a match on the interface
while (pInterfaceDesc = usbdpFindNext(DESC_TYPE_INTERFACE, DESC_TYPE_CONFIG)) {
if ((pInterfaceDesc->bInterfaceNumber == intNumber) && (pInterfaceDesc->bAlternateSetting == altSetting)) {
break;
}
}
return pInterfaceDesc;
} // usbdpGetInterfaceDesc
/** \brief Locates a string descriptor
*
* \note It is not necessary to call \ref usbdpInit() before this function.
*
* \param[in] strIndex
* A zero-based index that matches the "iXxxxxxxxxx" string indexes in the other descriptors
*
* \return
* A pointer to the \ref USB_INTERFACE_DESCRIPTOR, or \c NULL if it was not found.
*/
USB_STRING_DESCRIPTOR* usbdpGetStringDesc(uint8 strIndex)
{
USB_STRING_DESCRIPTOR *pStringDesc = NULL;
#ifdef MS_EXT_C_ID
/* TODO: Find the Microsoft OS String Descriptor?
usbdpInit();
if (strIndex == 0xEE){
// Find the Microsoft OS String Descriptor
do{
pStringDesc = usbdpFindNext(DESC_TYPE_STRING, 0);
}while (pStringDesc != NULL && pStringDesc->bLength != 18);
} else
*/
#endif
{
switch (strIndex)
{
case 0:
pStringDesc = (USB_STRING_DESCRIPTOR *)languageId;
break;
case 1:
pStringDesc = (USB_STRING_DESCRIPTOR *)manufacturer;
break;
case 2:
pStringDesc = (USB_STRING_DESCRIPTOR *)product;
break;
case 3:
if (serialNumber[0] == 0)
{
#if (defined HAL_SB_BOOT_CODE || defined CC253X_MACNP)
#include <string.h>
uint8 nullAddr[Z_EXTADDR_LEN] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8 aExtendedAddress[8];
// Attempt to read the extended address from the location on the lock bits page
// where the programming tools know to reserve it.
HalFlashRead(HAL_FLASH_IEEE_PAGE, HAL_FLASH_IEEE_OSET, aExtendedAddress, Z_EXTADDR_LEN);
if (!memcmp(aExtendedAddress, nullAddr, Z_EXTADDR_LEN))
{
// Attempt to read the extended address from the designated location in the Info Page.
(void)memcpy(aExtendedAddress, (uint8 *)(P_INFOPAGE+HAL_INFOP_IEEE_OSET), Z_EXTADDR_LEN);
}
#endif
// Load the 16 nibbles of the hex representation of the IEEE address into the serialNumber
// string in big-endian (i.e. human-readable) order.
for (uint8 idx = sizeof(serialNumber)-2, cnt = 0; cnt < Z_EXTADDR_LEN; cnt++, idx -= 4)
{
serialNumber[idx] = hexDigit[aExtendedAddress[cnt] & 0x0F];
serialNumber[idx-2] = hexDigit[aExtendedAddress[cnt] / 16];
}
serialNumber[0] = sizeof(serialNumber);
}
pStringDesc = (USB_STRING_DESCRIPTOR *)serialNumber;
break;
default:
break;
}
}
return pStringDesc;
}
/// @}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2011 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,122 @@
/***********************************************************************************
Filename: usb_descriptor_parser.h
Description: Parser for USB descriptor structures.
***********************************************************************************/
#ifndef USBDESCRIPTORPARSER_H
#define USBDESCRIPTORPARSER_H
/** \addtogroup module_usb_descriptor_parser USB Descriptor Parser (usbdp)
* \brief This module contains internally used functions for locating USB descriptors.
*
* The parsing mechanism supports all standard descriptors, i.e. DEVICE, CONFIGURATION, INTERFACE,
* ENDPOINT and STRING, but also other types that use the standard descriptor format:
* \code
* typedef struct {
* uint8 bLength; // Size of this descriptor (in bytes)
* uint8 bDescriptorType; // Descriptor type
* ...
* } USB_XXXXXXXX_DESCRIPTOR;
* \endcode
*
* \section section_usbdp_requirements Requirements
* The standard-formatted descriptors must be placed back-to-back in either XDATA or CODE memory.
* In the current version of the library, the USB descriptors are assumed to reside in CODE.
* Two markers (XDATA or CODE memory pointers), \ref usbDescStart and \ref usbDescEnd, define where
* the first descriptor begins and where the last descriptor ends, respectively
* (so that <tt>usbDescStart - usbDescEnd</tt> equals the total length of the descriptors).
*
* The markers can be dynamic, provided that they are not changed while the descriptor parser is in use.
* However, in most cases the USB descriptor set will be static, hence the markers are also static.
* The following example shows how static markers are declared and made public in 8051 assembler:
* \code
* ; Make the symbols public
* PUBLIC usbDescStart;
* PUBLIC usbDescEnd;
*
* ...
*
* usbDescStart:
* deviceDesc: ; Device descriptor (the first descriptor)
* DB deviceDescEnd - deviceDesc
* DB DESC_TYPE_DEVICE ; bDescriptorType
* DB 10H, 01H ; bcdUSB
* DB 00H ; bDeviceClass
* DB 00H ; bDeviceSubClass
*
* ...
*
* usbDescEnd:
* \endcode
* @{
*/
#include "usb_descriptor.h"
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Indexes Into USB Descriptors
//@{
#define DESC_LENGTH_IDX 0 ///< Index of the bLength field (all descriptors)
#define DESC_TYPE_IDX 1 ///< Index of the bDescriptorType field (all descriptors)
#define DESC_CONFIG_LENGTH_LSB_IDX 2 ///< Index of LOUINT8(USB_CONFIGURATION_DESCRIPTOR.wTotalLength)
#define DESC_CONFIG_LENGTH_MSB_IDX 3 ///< Index of HIUINT8(USB_CONFIGURATION_DESCRIPTOR.wTotalLength)
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
// Function prototypes
void usbdpInit(void);
void __code *usbdpFindNext(uint8 wantedType, uint8 haltAtType);
USB_DEVICE_DESCRIPTOR __code* usbdpGetDeviceDesc(void);
USB_CONFIGURATION_DESCRIPTOR __code* usbdpGetConfigurationDesc(uint8 cfgValue, uint8 cfgIndex);
USB_INTERFACE_DESCRIPTOR __code* usbdpGetInterfaceDesc(uint8 cfgValue, uint8 intNumber, uint8 altSetting);
USB_STRING_DESCRIPTOR* usbdpGetStringDesc(uint8 strIndex);
//-------------------------------------------------------------------------------------------------------
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2010 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,332 @@
/***********************************************************************************
Filename: usb_framework.c
Description: USB library common functionality.
***********************************************************************************/
/// \addtogroup module_usb_framework
/// @{
#define USBFRAMEWORK_C ///< Modifies the behavior of "EXTERN" in usb_framework.h
#include "usb_firmware_library_headers.h"
#include "usb_board_cfg.h"
// Function pointer used by usbfwSetupHandler()
static VFPTR __data ProcessFunc;
/** \brief Initializes the USB framework
*
* This function should be called when the microcontroller is ready to accept USB traffic. It enables the
* USB peripheral unit and enables the pull-up resistor on the D+ line. Endpoint status, current
* configuration value, etc. are initialized and evenetually re-initialized in the
* \ref usbfwResetHandler() function.
*/
void usbfwInit(void)
{
// Set default values
usbfwData.selfPowered = (usbdpGetConfigurationDesc(1, 0)->bmAttributes & 0x40) ? TRUE : FALSE;
usbfwData.remoteWakeup = FALSE;
HAL_USB_ENABLE();
// Enable Resume Interrupt
HAL_USB_RESUME_INT_ENABLE();
} // usbfwInit
/** \brief Handles USB reset signalling
*
* This function should be called, either from the USB interrupt or the main loop, when the \c USBCIF.RST
* flag has been set. Keep in mind that all bits in \c USBCIF register are cleared when the register is
* read. The function puts the device into the default state (not yet addressed), and puts all endpoints
* (except EP0) into the \ref EP_HALT state
*/
void usbfwResetHandler(void)
{
// Reset the USB state
usbfwData.usbState = DEV_DEFAULT;
usbfwData.configurationValue = 0;
// Reset all endpoints
usbfwData.ep0Status = EP_IDLE;
usbfwSetAllEpStatus(EP_HALT);
// Reset last function pointer
ProcessFunc = NULL;
} // usbfwResetHandler
/** \brief USB Setup Handler
*
* This function should be called either from the USB interrupt or the main loop when the \c USBIIF.EP0IF
* flag has been set. Keep in mind that all bits in \c USBIIF register are cleared when the register is
* read. A detailed description of the framework is found in the \ref section_setup_handler_usage
* section.
*
* \note The USB header data is always little-endian, so if a big-endian compiler is used (such as Keil
* C51), the 16-bit values in the \ref usbSetupHeader must be flipped before they are used.
*/
void usbfwSetupHandler(void)
{
uint8 controlReg;
uint8 bytesNow;
uint8 oldEndpoint;
// Save the old index setting, then select endpoint 0 and fetch the control register
oldEndpoint = USBFW_GET_SELECTED_ENDPOINT();
USBFW_SELECT_ENDPOINT(0);
controlReg = USBCS0;
// The last transfer was ended prematurely by a new SETUP packet
if (controlReg & USBCS0_SETUP_END) {
USBCS0 = USBCS0_CLR_SETUP_END;
usbfwData.ep0Status = EP_CANCEL;
if (ProcessFunc) ProcessFunc();
usbfwData.ep0Status = EP_IDLE;
}
// A STALL handshake was transmitted to the PC
if (controlReg & USBCS0_SENT_STALL) {
USBCS0 = 0x00;
usbfwData.ep0Status = EP_IDLE;
}
// Receive OUT packets
if (usbfwData.ep0Status == EP_RX) {
// Read FIFO
bytesNow = USBCNT0;
usbfwReadFifo(&USBF0, bytesNow, usbSetupData.pBuffer);
usbSetupData.bytesLeft -= bytesNow;
usbSetupData.pBuffer += bytesNow;
// Arm the endpoint
USBCS0 = usbSetupData.bytesLeft ? USBCS0_CLR_OUTPKT_RDY : (USBCS0_CLR_OUTPKT_RDY | USBCS0_DATA_END);
// Make a call to the appropriate request handler when done
if (usbSetupData.bytesLeft == 0) {
if (ProcessFunc) ProcessFunc();
usbfwData.ep0Status = EP_IDLE;
}
// Return here since nothing more will happen until the next interrupt
USBFW_SELECT_ENDPOINT(oldEndpoint);
return;
// Let the application handle the reception
} else if (usbfwData.ep0Status == EP_MANUAL_RX) {
ProcessFunc();
}
// Receive SETUP header
if (usbfwData.ep0Status == EP_IDLE) {
if (controlReg & USBCS0_OUTPKT_RDY) {
usbfwReadFifo(&USBF0, 8, (uint8 __xdata *) &usbSetupHeader);
// Handle control transfers individually
ProcessFunc = NULL;
switch (usbSetupHeader.requestType & (RT_MASK_TYPE | RT_MASK_DIR)) {
// Standard requests with data from the host (OUT)
case RT_STD_OUT:
switch (usbSetupHeader.request) {
case SET_ADDRESS: usbsrSetAddress(); break;
case SET_FEATURE: usbsrSetFeature(); break;
case CLEAR_FEATURE: usbsrClearFeature(); break;
case SET_CONFIGURATION: usbsrSetConfiguration(); break;
case SET_INTERFACE: usbsrSetInterface(); break;
case SET_DESCRIPTOR: /*usbsrHookSetDescriptor(); break; - unsupported */
default: usbfwData.ep0Status = EP_STALL; break;
}
break;
// Standard requests with data to the host (IN)
case RT_STD_IN:
switch (usbSetupHeader.request) {
case GET_STATUS: usbsrGetStatus(); break;
case GET_DESCRIPTOR: usbsrGetDescriptor(); break;
case GET_CONFIGURATION: usbsrGetConfiguration(); break;
case GET_INTERFACE: usbsrGetInterface(); break;
case SYNCH_FRAME: /*usbsrHookSynchFrame(); break; - unsupported */
default: usbfwData.ep0Status = EP_STALL; break;
}
break;
// Vendor requests
case RT_VEND_OUT:
ProcessFunc = usbvrHookProcessOut; usbvrHookProcessOut();
break;
case RT_VEND_IN:
ProcessFunc = usbvrHookProcessIn; usbvrHookProcessIn();
break;
// Class requests
case RT_CLASS_OUT:
ProcessFunc = usbcrHookProcessOut; usbcrHookProcessOut();
break;
case RT_CLASS_IN:
ProcessFunc = usbcrHookProcessIn; usbcrHookProcessIn();
break;
// Unrecognized request: Stall the endpoint
default:
usbfwData.ep0Status = EP_STALL;
break;
}
// Arm/stall the endpoint
USBCS0 = (usbfwData.ep0Status == EP_STALL) ? (USBCS0_CLR_OUTPKT_RDY | USBCS0_SEND_STALL) : USBCS0_CLR_OUTPKT_RDY;
}
}
// Transmit IN packets
if (usbfwData.ep0Status == EP_TX) {
controlReg = USBCS0_INPKT_RDY;
// The last frame should contain 0 to (EP0_PACKET_SIZE - 1) bytes
if (usbSetupData.bytesLeft < EP0_PACKET_SIZE) {
bytesNow = usbSetupData.bytesLeft;
controlReg |= USBCS0_DATA_END;
// All other packets should have the maximum length
} else {
bytesNow = EP0_PACKET_SIZE;
}
// Load the FIFO and move the pointer
usbfwWriteFifo(&USBF0, bytesNow, usbSetupData.pBuffer);
usbSetupData.pBuffer += bytesNow;
usbSetupData.bytesLeft -= bytesNow;
// Arm the FIFO (even for a zero-length packet)
USBCS0 = controlReg;
// Make a call to the appropriate request handler when done
if (bytesNow < EP0_PACKET_SIZE) {
if (ProcessFunc) ProcessFunc();
usbfwData.ep0Status = EP_IDLE;
}
// Let the application handle the transmission
} else if (usbfwData.ep0Status == EP_MANUAL_TX) {
ProcessFunc();
}
// Restore the old index setting
USBFW_SELECT_ENDPOINT(oldEndpoint);
} // usbfwSetupHandler
/** \brief Changes the state of endpoint 1-5 IN/OUT
*
* This is an internal function used by the library.
*
* \param[in] status
* The new status for each endpoint
*/
void usbfwSetAllEpStatus(EP_STATUS status)
{
uint8 n;
for (n = 0; n < sizeof(usbfwData.pEpInStatus); n++)
usbfwData.pEpInStatus[n] = status;
for (n = 0; n < sizeof(usbfwData.pEpOutStatus); n++)
usbfwData.pEpOutStatus[n] = status;
} // usbfwSetAllEpStatus
/** \brief Reads from the selected OUT endpoint FIFO, without using DMA
*
* The FIFO must be re-armed after reading it empty (using the \ref USBFW_ARM_OUT_ENDPOINT() macro). This
* is not necessary when flushing the FIFO.
*
* \param[in] *pFifo
* Pointer to the FIFO (\c &USBFx)
* \param[in] count
* The number of bytes to read
* \param[in] *pData
* A pointer to the storage location for the read data (in any memory space)
*/
void usbfwReadFifo(uint8 volatile __xdata *pFifo, uint8 count, void __generic *pData)
{
uint8 __generic *pTemp = pData;
if (count) {
do {
*(pTemp++) = *pFifo;
} while (--count);
}
} // usbfwReadFifo
/** \brief Writes to the selected IN endpoint FIFO, without using DMA
*
* Note that the FIFO must be armed in order to be transmitted (using the \ref USBFW_ARM_IN_ENDPOINT()
* macro).
*
* \param[in] *pFifo
* Pointer to the FIFO (\c &USBFx)
* \param[in] count
* The number of bytes to write
* \param[in] *pData
* A pointer to the data to be written (from any memory space)
*/
void usbfwWriteFifo(uint8 volatile __xdata *pFifo, uint8 count, void __generic *pData)
{
uint8 __generic *pTemp = pData;
if (count) {
do {
*pFifo = *(pTemp++);
} while (--count);
}
} // usbfwWriteFifo
/// @}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,383 @@
/***********************************************************************************
Filename: usb_framework.h
Description: USB library common functionality.
***********************************************************************************/
#ifndef USBFRAMEWORK_H
#define USBFRAMEWORK_H
/** \addtogroup module_usb_framework USB Framework (usbfw)
* \brief This module contains USB status information, functions for initialization, USB device reset
* handling, and most importantly, the framework for transfers on endpoint 0, FIFO access, and endpoint
* control.
*
* \section section_init Framework Initialization
* The framework and the USB peripheral unit can be initialized once the crystal oscillator (48 MHz for
* CC1111/CC2511, 32 MHz for CC2531) is running. This is done by \ref usbfwInit(), which:
* \li Initializes framework variables
* \li Enables the USB peripheral unit by setting the \c SLEEP.USB_EN bit
* \li Enables the pull-up resistor via a GPIO pin
*
* When completing the last step, the host will be recognize the USB device, and start the enumeration
* process. To reply to the shortly incoming standard requests, the call to \ref usbfwInit() must be
* followed immediately by USB Interrupt \ref section_usbirq_initialization.
*
* \section section_endpoint_0_transfers Endpoint 0 Transfers
* The USB interface uses endpoint 0 to perform setup requests of the standard, vendor and class types.
* Such transfers consist of three phases:
* - A setup phase, where an 8-byte \ref USB_SETUP_HEADER is transferred to the device.
* - An IN/OUT data phase, if the length field of the \ref USB_SETUP_HEADER structure is non-zero.
* - A handshake phase, where the application can stall the endpoint to indicate error conditions.
*
* The setup handler, \ref usbfwSetupHandler(), takes care of the low-level parts of these transfers,
* including the IN/OUT buffering during the data phase (when there is one). The transfers fall into two
* categories:
* - Most standard requests are processed internally, with little or no intervention form the user
* application. This is done by the \ref module_usb_standard_requests module.
* - Vendor and class requests are application specific and must always be processed by the application.
* Whenever such a request is received, the following hooks will be called between the phases:
* - \ref usbcrHookProcessOut(): Class requests with OUT data phase
* - \ref usbcrHookProcessIn(): Class requests with IN data phase
* - \ref usbvrHookProcessOut(): Vendor requests with OUT data phase
* - \ref usbvrHookProcessIn(): Vendor requests with IN data phase
*
* \section section_setup_handler_usage Setup Handler Usage
* This section describes what is required to make the vendor and class request hooks work. This
* information also applies to the standard requests that needs application processing
* (\ref usbsrHookSetDescriptor(), \ref usbsrHookSynchFrame(), and some cases of
* \ref usbsrHookSetFeature() and \ref usbsrHookClearFeature()).
*
* The transactions are made using a clean and efficient interface, consisting of two data structures and
* the endpoint 0 status byte:
* - The endpoint status is initially \ref EP_IDLE, which basically means that the setup handler is ready
* for a new setup phase (a new request). Upon an incoming request, the processing hook is called, and
* the \ref usbSetupHeader structure contains the 8 bytes received during the setup phase. At this
* point there are four different outcomes:
* - If the request is unknown or contains errors, the endpoint should be stalled. This is done by
* setting the endpoint status to \ref EP_STALL.
* - If there is no data phase (the length field is zero), the endpoint status should just remain in
* it's current state, \ref EP_IDLE.
* - If the request has an IN data phase, the \ref usbSetupData structure must be prepared. This
* includes setting a pointer to where IN data should be taken from, and the number of bytes to be
* transferred (usually the same number as indicated by the length field, but it can also be a
* lower number). The endpoint state is then changed to \ref EP_TX.
* - If the request has an OUT data phase, the \ref usbSetupData structure must be prepared. This
* includes setting a pointer to where OUT data should be stored, and the number of bytes to be
* transferred (always the same number as indicated by the length field). The endpoint state is
* then changed to \ref EP_RX.
* - When the data phase is complete, the processing hook function will be called a second time to notify
* the application. Under normal conditions the endpoint status will be either \ref EP_TX or \ref EP_RX,
* and does not need to be changed any further (as this is done automatically upon return). If the
* endpoint status is \ref EP_CANCEL, it means that the USB host cancelled the setup transfer.
*
* The following code examples illustrate practical usage (more code is available in the application
* example projects):
*
* \par Example 1: Endpoint 0 Requests With OUT Data phase
*
* \code
* uint8 pLcdBuffer[358];
*
* void usbvrHookProcessOut(void) {
*
* // When this vendor request is received, we should either update a part of pLcdBuffer[] or leave
* // it as it is, and then refresh the LCD display. The index field of the setup header contains the
* // index of the first character to be updated, and the length field how many characters to update.
* if (usbSetupHeader.request == VR_LCD_UPDATE) {
*
* // First the endpoint status is EP_IDLE... (we have just received the Setup packet)
* if (usbfwData.ep0Status == EP_IDLE) {
*
* // There is no new data -> Just refresh the display
* if (usbSetupHeader.length == 0) {
* lcdRefresh();
* // There is no change to the endpoint status in this case
*
* // The PC wants to send data that will be stored outside pLcdBuffer -> stall the endpoint!
* } else if ((usbSetupHeader.length > sizeof(pLcdBuffer) ||
* (usbSetupHeader.index >= sizeof(pLcdBuffer) ||
* ((usbSetupHeader.index + usbSetupHeader.length) > sizeof(pLcdBuffer)) {
* usbfwData.ep0Status = EP_STALL;
*
* // Prepare for OUT data phase, setup the data buffer to receive the LCD data
* } else {
* usbSetupData.pBuffer = &pLcdBuffer[usbSetupHeader.index];
* usbSetupData.bytesLeft = usbSetupHeader.length;
* usbfwData.ep0Status = EP_RX;
* }
*
* // Then the endpoint status is EP_RX (remember: we did that here when setting up the buffer)
* } else if (usbfwData.ep0Status == EP_RX) {
* // usbfwSetupHandler() has now updated pLcdBuffer, so all we need to do is refresh the LCD
* lcdRefresh();
* // usbfwData.ep0Status is automatically reset to EP_IDLE when returning to usbfwSetupHandler()
* }
*
* // Unknown vendor request?
* } else {
* usbfwData.ep0Status = EP_STALL;
* }
* }
* \endcode
*
* \par Example 2: Endpoint 0 Requests With IN Data phase
*
* \code
* uint8 keyBufferPos;
* BOOL blockKeyboard;
* char pKeyBuffer[150];
*
* void usbvrProcessIn(void) {
*
* // When this vendor request is received, we should send all registered key-strokes, and reset the
* // position counter. New keystrokes are blocked during the transfer to avoid overwriting the buffer
* // before it has been sent to the host.
* if (usbSetupHeader.request == VR_GET_KEYS) {
*
* // First the endpoint status is EP_IDLE...
* if (usbfwData.ep0Status == EP_IDLE) {
*
* // Make sure that we do not send more than the PC asked for
* if (usbSetupHeader.length < keyBufferPos) {
* usbfwData.ep0Status = EP_STALL;
*
* // Otherwise...
* } else {
* // Block for new keystrokes
* blockKeyboard = TRUE;
*
* // Setup the buffer
* usbSetupData.pBuffer = pKeyBuffer;
* usbSetupData.bytesLeft = keyBufferPos;
* usbfwData.ep0Status = EP_TX;
*
* // Reset the position counter
* keyBufferPos = 0;
* }
*
* // Then the endpoint status is EP_TX (remember: we did that here when setting up the buffer)
* } else if (usbfwData.ep0Status == EP_TX) {
*
* // pKeyBuffer has now been sent to the host, so new keystrokes can safely be registered
* blockKeyboard = FALSE;
*
* // usbfwData.ep0Status is automatically reset to EP_IDLE when returning to usbfwSetupHandler()
* }
*
* // Unknown request?
* } else {
* usbfwData.ep0Status = EP_STALL;
* }
* }
* \endcode
*
* If automated data transfer is not desired, the application should set \c usbfwData.ep0Status to
* either \ref EP_MANUAL_RX or \ref EP_MANUAL_TX instead of \ref EP_RX or \ref EP_TX, respectively. Until
* the transfer is completed, the processing hook function (e.g. \ref usbvrHookProcessIn()) will be called
* at every endpoint 0 interrupt.
* @{
*/
#include "usb_board_cfg.h"
#include "usb_framework_structs.h"
#ifdef EXTERN
#undef EXTERN
#endif
#ifdef USBFRAMEWORK_C
#define EXTERN ///< Definition used only for usb_framework.c
#else
#define EXTERN extern ///< Definition used in other source files to declare external
#endif
//-------------------------------------------------------------------------------------------------------
/// \name Module Data
//@{
EXTERN USBFW_DATA __xdata usbfwData; ///< USBFW internal module data
//@}
//-------------------------------------------------------------------------------------------------------
/// \name Setup Handler Data
//@{
EXTERN USB_SETUP_DATA __xdata usbSetupData; ///< Setup handler data phase configuration
EXTERN USB_SETUP_HEADER __xdata usbSetupHeader; ///< Setup header
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Request Type Fields
//@{
// Field masks
#define RT_MASK_DIR 0x80 ///< Request direction bit mask
#define RT_MASK_TYPE 0x60 ///< Request type bit mask
#define RT_MASK_RECIP 0x1F ///< Request recipient bit mask
// Direction field
#define RT_DIR_IN 0x80 ///< IN Request
#define RT_DIR_OUT 0x00 ///< OUT Request
// Type field
#define RT_TYPE_STD 0x00 ///< Standard Request
#define RT_TYPE_CLASS 0x20 ///< Class Request
#define RT_TYPE_VEND 0x40 ///< Vendor Request
// Recipient field
#define RT_RECIP_DEV 0x00 ///< Device Request
#define RT_RECIP_IF 0x01 ///< Interface Request
#define RT_RECIP_EP 0x02 ///< Endpoint Request
#define RT_RECIP_OTHER 0x03 ///< Other Request
// Type + direction
#define RT_STD_OUT (RT_TYPE_STD | RT_DIR_OUT) ///< Standard request, direction is OUT
#define RT_STD_IN (RT_TYPE_STD | RT_DIR_IN) ///< Standard request, direction is IN
#define RT_VEND_OUT (RT_TYPE_VEND | RT_DIR_OUT) ///< Vendor request, direction is OUT
#define RT_VEND_IN (RT_TYPE_VEND | RT_DIR_IN) ///< Vendor request, direction is IN
#define RT_CLASS_OUT (RT_TYPE_CLASS | RT_DIR_OUT) ///< Class request, direction is OUT
#define RT_CLASS_IN (RT_TYPE_CLASS | RT_DIR_IN) ///< Class request, direction is IN
// Direction + recepient
#define RT_OUT_DEVICE (RT_DIR_OUT | RT_RECIP_DEV) ///< Request made to device, direction is OUT
#define RT_IN_DEVICE (RT_DIR_IN | RT_RECIP_DEV) ///< Request made to device, direction is IN
#define RT_OUT_INTERFACE (RT_DIR_OUT | RT_RECIP_IF) ///< Request made to interface, direction is OUT
#define RT_IN_INTERFACE (RT_DIR_IN | RT_RECIP_IF) ///< Request made to interface, direction is IN
#define RT_OUT_ENDPOINT (RT_DIR_OUT | RT_RECIP_EP) ///< Request made to endpoint, direction is OUT
#define RT_IN_ENDPOINT (RT_DIR_IN | RT_RECIP_EP) ///< Request made to endpoint, direction is IN
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Vendor and Class Request Hooks
/// Unused hooks must stall endpoint 0.
//@{
/// Hook which is called upon reception of a class request with OUT data phase
void usbcrHookProcessOut(void);
/// Hook which is called upon reception of a class request with IN data phase
void usbcrHookProcessIn(void);
/// Hook which is called upon reception of a vendor request with OUT data phase
void usbvrHookProcessOut(void);
/// Hook which is called upon reception of a vendor request with IN data phase
void usbvrHookProcessIn(void);
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Endpoint Access Macros
/// Note that the endpoint control registers are indexed, meaning that an endpoint must be selected
/// before the control operations listed below can be used. Interrupts using any of these macros, must
/// save the current selection and restore it upon return.
//@{
/// Selects which IN/OUT endpoint (by index 0 to 5) to operate on
#define USBFW_SELECT_ENDPOINT(n) (USBINDEX = (n))
/// Gets the currently selected IN/OUT endpoint
#define USBFW_GET_SELECTED_ENDPOINT() (USBINDEX)
/// Stalls the selected IN endpoint
#define USBFW_STALL_IN_ENDPOINT() st (\
USBCSIL = USBCSIL_SEND_STALL; \
usbfwData.pEpInStatus[USBINDEX - 1] = EP_HALT; )
/// Returns the stall condition for the selected IN endpoint
#define USBFW_IN_ENDPOINT_STALLED() (USBCSIL & USBCSIL_SEND_STALL)
/// Flushes the FIFO for the selected IN endpoint (flush twice when using double-buffering)
#define USBFW_FLUSH_IN_ENDPOINT() st (\
USBCSIL = USBCSIL_FLUSH_PACKET; \
while (USBCSIL & USBCSIL_FLUSH_PACKET); )
/// Arms the selected IN endpoint, so that contents of the endpoint FIFO can be sent to the host
#define USBFW_ARM_IN_ENDPOINT() (USBCSIL = USBCSIL_INPKT_RDY)
/// Is the selected IN endpoint disarmed?
#define USBFW_IN_ENDPOINT_DISARMED() !(USBCSIL & USBCSIL_INPKT_RDY)
/// Is the FIFO for the selected IN endpoint empty?
#define USBFW_IN_ENDPOINT_FIFO_EMPTY() !(USBCSIL & USBCSIL_PKT_PRESENT)
/// Stalls the selected OUT endpoint
#define USBFW_STALL_OUT_ENDPOINT() st ( \
USBCSOL = USBCSOL_SEND_STALL; \
usbfwData.pEpOutStatus[USBINDEX - 1] = EP_HALT; \
}
/// Returns the stall condition for the selected OUT endpoint
#define USBFW_OUT_ENDPOINT_STALLED() (USBCSOL & USBCSOL_SEND_STALL)
/// Flushes the FIFO for the selected OUT endpoint (flush twice when using double-buffering)
#define USBFW_FLUSH_OUT_ENDPOINT() st(\
USBCSOL = USBCSOL_FLUSH_PACKET; \
while (USBCSOL & USBCSOL_FLUSH_PACKET); )
/// Arms the selected OUT endpoint, so that the FIFO can receive data from the host
#define USBFW_ARM_OUT_ENDPOINT() (USBCSOL = 0)
/// Is the selected OUT endpoint disarmed? If so, there is data waiting in the FIFO
#define USBFW_OUT_ENDPOINT_DISARMED() (USBCSOL & USBCSOL_OUTPKT_RDY)
/// Returns the number of bytes currently in the FIFO of the selected OUT endpoint, low byte
#define USBFW_GET_OUT_ENDPOINT_COUNT_LOW() (USBCNTL)
/// Returns the number of bytes currently in the FIFO of the selected OUT endpoint, high byte
#define USBFW_GET_OUT_ENDPOINT_COUNT_HIGH() (USBCNTH)
//@}
//-------------------------------------------------------------------------------------------------------
// Little endian
#define LOBYTEPTR(w) ( (uint8 __generic *)(&(w)) + 1 )
// Big endian
//#define LOBYTEPTR(w) ( (uint8 __generic *)&(w) )
//-------------------------------------------------------------------------------------------------------
// Function prototypes
void usbfwInit(void);
void usbfwResetHandler(void);
void usbfwSetupHandler(void);
void usbfwSetAllEpStatus(EP_STATUS status);
void usbfwWriteFifo(uint8 volatile __xdata *pFifo, uint8 count, void __generic *pData);
void usbfwReadFifo(uint8 volatile __xdata *pFifo, uint8 count, void __generic *pData);
//-------------------------------------------------------------------------------------------------------
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,233 @@
/***********************************************************************************
Filename: usb_framework_structs.h
Description: USB library common data structures.
***********************************************************************************/
#ifndef USBFRAMEWORKSTRUCTS_H
#define USBFRAMEWORKSTRUCTS_H
/** \addtogroup module_usb_framework USB Framework (usbfw)
* \brief This module contains USB status and descriptor structs
*
*
* @{
*/
#include "hal_types.h"
#include "usb_firmware_library_config.h"
#ifdef EXTERN
#undef EXTERN
#endif
#ifdef USBFRAMEWORK_C
#define EXTERN ///< Definition used only for usb_framework.c
#else
#define EXTERN extern ///< Definition used in other source files to declare external
#endif
//-------------------------------------------------------------------------------------------------------
/// \name Module Data
//@{
/// Endpoint status (used with USB_INFO.ep0Status / pEpInStatus[] / pEpOutStatus[])
typedef enum {
EP_IDLE = 0x00, ///< The endpoint is idle, or a setup token has been received
EP_TX = 0x01, ///< Setup IN data is transmitted automatically by the framework
EP_RX = 0x02, ///< Setup OUT data is received automatically by the framework
EP_HALT = 0x03, ///< The endpoint is halted (returns stalls to the host)
EP_STALL = 0x04, ///< Send procedural stall in the next status phase
EP_MANUAL_TX = 0x05, ///< Setup IN data is transmitted manually by the user application
EP_MANUAL_RX = 0x06, ///< Setup OUT data is received manually by the user application
EP_CANCEL = 0x07 ///< The current transfer was cancelled by the host
} EP_STATUS;
/// Device state (used with USB_INFO.usbState)
typedef enum {
DEV_ATTACHED = 0x00, ///< Device attached (invisible state)
DEV_POWERED = 0x01, ///< Device powered (invisible state)
DEV_DEFAULT = 0x02, ///< Default state (the \c USBADDR register is 0)
DEV_ADDRESS = 0x03, ///< Addressed state (the \c USBADDR register has been set)
DEV_CONFIGURED = 0x04, ///< Configured state (\c usbfwData.configurationValue != 0)
DEV_SUSPENDED = 0x05 ///< Suspended state (never set)
} USB_STATE;
/// USBFW internal module data
typedef struct {
USB_STATE usbState; ///< USB device state
uint8 configurationValue; ///< Current configuration value
uint8 pAlternateSetting[USB_SETUP_MAX_NUMBER_OF_INTERFACES]; ///< Current alternate settings
EP_STATUS ep0Status; ///< Endpoint 0 status
EP_STATUS pEpInStatus[5]; ///< Endpoint 1-5 IN status
EP_STATUS pEpOutStatus[5]; ///< Endpoint 1-5 OUT status
uint8 remoteWakeup; ///< Remote wakeup allowed
uint8 selfPowered; ///< Is currently self-powered?
} USBFW_DATA;
//-------------------------------------------------------------------------------------------------------
/// Setup header (contains the 8 bytes received during the setup phase)
typedef struct {
uint8 requestType; ///< Request type (direction, type and recipient, see the \c RT_ definitions)
uint8 request; ///< Request ID
uint16 value; ///< Value field
uint16 index; ///< Index field
uint16 length; ///< Length of data phase
} USB_SETUP_HEADER;
/// Setup handler data phase configuration
typedef struct {
uint8 __generic *pBuffer; ///< Pointer to where IN/OUT data should be taken from/received
uint16 bytesLeft; ///< The number of bytes to transfer
} USB_SETUP_DATA;
//@}
//-------------------------------------------------------------------------------------------------------
// From usb_descriptor.h
/** \addtogroup module_usb_descriptor USB Descriptor*/
//-------------------------------------------------------------------------------------------------------
/// USB device descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< Descriptor type = \ref DESC_TYPE_DEVICE
uint16 bcdUSB; ///< USB specification release number (in BCD, e.g. 0110 for USB 1.1)
uint8 bDeviceClass; ///< Device class code
uint8 bDeviceSubClass; ///< Device subclass code
uint8 bDeviceProtocol; ///< Device protocol code
uint8 bMaxPacketSize0; ///< Maximum packet size for EP0
uint16 idVendor; ///< Vendor ID
uint16 idProduct; ///< Product ID
uint16 bcdDevice; ///< Device release number (in BCD)
uint8 iManufacturer; ///< Index of the string descriptor for manufacturer
uint8 iProduct; ///< Index of the string descriptor for product
uint8 iSerialNumber; ///< Index of the string descriptor for serial number
uint8 bNumConfigurations; ///< Number of possible configurations
} USB_DEVICE_DESCRIPTOR;
/// USB configuration descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< Descriptor type = \ref DESC_TYPE_CONFIG
uint16 wTotalLength; ///< Total length of data for this configuration
uint8 bNumInterfaces; ///< Number of interfaces supported by this configuration (one-based index)
uint8 bConfigurationValue; ///< Designator value for this configuration
uint8 iConfiguration; ///< Index of the string descriptor for this configuration
uint8 bmAttributes; ///< Configuration characteristics
uint8 bMaxPower; ///< Maximum power consumption in this configuration (bMaxPower * 2 mA)
} USB_CONFIGURATION_DESCRIPTOR;
/// USB interface descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< Descriptor type = \ref DESC_TYPE_INTERFACE
uint8 bInterfaceNumber; ///< Number of *this* interface (zero-based index)
uint8 bAlternateSetting; ///< Alternate setting index for this descriptor (zero-based index)
uint8 bNumEndpoints; ///< Number of endpoints for this interface (excl. EP0)
uint8 bInterfaceClass; ///< Interface class code
uint8 bInterfaceSubClass; ///< Interface subclass code
uint8 bInterfaceProtocol; ///< Interface protocol code
uint8 iInterface; ///< Index of the string descriptor for this interface
} USB_INTERFACE_DESCRIPTOR;
/// USB endpoint descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< Descriptor type = \ref DESC_TYPE_ENDPOINT
uint8 bEndpointAddress; ///< Endpoint address (direction[7] + number[3:0])
uint8 bmAttributes; ///< Endpoint attributes (ISO / BULK / INT)
uint16 wMaxPacketSize; ///< Maximum endpoint packet size
uint8 bInterval; ///< \ref EP_ATTR_INT : Polling interval (in ms)
} USB_ENDPOINT_DESCRIPTOR;
/// USB string descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< Descriptor type = \ref DESC_TYPE_STRING
uint16 pString[1]; ///< Unicode string
} USB_STRING_DESCRIPTOR;
/// USB HID descriptor
typedef struct {
uint8 bLength; ///< Size of this descriptor (in bytes)
uint8 bDescriptorType; ///< HID descriptor type
uint16 bscHID; ///< HID specification release number (in BCD)
uint8 bCountryCode; ///< Hardware target country
uint8 bNumDescriptors; ///< Number of HID class descriptors to follow
uint8 bRDescriptorType; ///< Report descriptor type
uint16 wDescriptorLength; ///< Total length of the associated report descriptor
} USB_HID_DESCRIPTOR;
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// Look-up table entry for non-standard descriptor types (used with \ref usbsrGetDescriptor)
typedef struct {
uint8 valueMsb; ///< LSB of the \ref USB_SETUP_HEADER.value request parameter
uint8 valueLsb; ///< MSB of the \ref USB_SETUP_HEADER.value request parameter
uint8 indexMsb; ///< LSB of the \ref USB_SETUP_HEADER.index request parameter
uint8 indexLsb; ///< MSB of the \ref USB_SETUP_HEADER.index request parameter
uint8 __code *pDescStart; ///< A pointer to the descriptor to be returned for the given index/value
uint16 length; ///< The length of the returned descriptor
} DESC_LUT_INFO;
/// Look-up table for double-buffer settings
typedef struct {
USB_INTERFACE_DESCRIPTOR __code *pInterface; ///< Pointer to an interface descriptor
uint8 inMask; ///< Bitmask for IN endpoints (bit x maps to EPx IN)
uint8 outMask; ///< Bitmask for OUT endpoints (bit x maps to EPx OUT)
} DBLBUF_LUT_INFO;
// From usb_interrupt.h
//-------------------------------------------------------------------------------------------------------
/// USBIRQ internal module data
typedef struct {
uint16 eventMask; ///< Bit mask containing all pending events (see the \c USBIRQ_EVENT definitions)
uint8 inSuspend; ///< Is currently in suspend?
uint16 irqMask; ///< USB interrupts to be enabled
} USBIRQ_DATA;
//-------------------------------------------------------------------------------------------------------
/// USBDP internal module data
typedef struct {
const uint8 __code *pDesc; ///< Pointer to the current descriptor
} USBDP_DATA;
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,213 @@
/***********************************************************************************
Filename: usb_interrupt.h
Description: USB library interrupt initialisation and ISR.
***********************************************************************************/
#ifndef USBINTERRUPT_H
#define USBINTERRUPT_H
/** \addtogroup module_usb_interrupt USB Interrupt (usbirq)
* \brief This module contains the USB interrupt handler, which converts USB interrupts to USBIRQ events.
*
* This module contains two interrupt service routines:
* \li P0 ISR
* \li P2 ISR
* Both these are used by the USB part of the MCU. Hence it is recommended to only use P1 for
* interrupts from any peripherals connected to the MCU. Unless running low on GPIO pins, one should
* generally avoid using the P0 and P2 pins at all.
*
* The MCU contains three interrupt flag registers, USBCIE, USBIIE and USBOIE, which are all cleared
* upon read access. The \ref module_usb_interrupt module encapsulates the USB interrupts, and saves the
* three flag registers in a single 16-bit word. By doing that it becomes possible to process
* high-priority events in the interrupt context, and low-priority events in the main loop.
*
* \section section_usbirq_initialization Initialization
* After initializing the \ref module_usb_framework module, \c main() must call \ref usbirqInit(). The
* \c irqMask parameter of this function shall contain all \c USBIRQ_EVENT bits that will be handled
* either in the interrupt or in \c main(). Note, however, that the event reporting may not always be
* necessary. For instance, there is usually no reason to enable \c USBIRQ_EVENT_EPxIN or
* \c USBIRQ_EVENT_EPxOUT events when handling low-priority transfers in the \c main() loop. In these
* cases it is simpler and more efficient to check the arming condition of the endpoint in question.
*
* The following example enables the setup and reset events (which must always be enabled!), and turns on
* global interrupts:
* \code
* void main(void) {
*
* ... Initialize the crystal oscillator and USB framework first ...
*
* // Initialize the USB Interrupt module
* usbirqInit(USBIRQ_EVENT_RESET | USBIRQ_EVENT_SUSPEND | USBIRQ_EVENT_RESUME | USBIRQ_EVENT_SETUP);
*
* // Turn on interrupts
* INT_GLOBAL_ENABLE();
*
* // Main loop
* while (1) {
* ...
* }
* \endcode
*
* \section section_usbirq_event_processing Event Processing
* Regardless of whether the interrupt event is processed in the interrupt or in the main loop, the code
* piece for doing it is the same (this example illustrates the processing of \ref USBIRQ_EVENT_RESET
* events):
* \code
* // Let the framework handle reset events :)
* if (USBIRQ_GET_EVENT_MASK() & USBIRQ_EVENT_RESET) {
* USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_RESET);
* usbfwResetHandler();
* }
* \endcode
*
* \section Hooks
* The following hook is called from the USB interrupt, and allows for event processing in the interrupt
* context:
* \code
* void usbirqHookProcessEvents(void) {
* // Process high-priority events here, or simply return if there are none
* }
* \endcode
* @{
*/
#include "usb_framework_structs.h"
#ifdef EXTERN
#undef EXTERN
#endif
#ifdef USBINTERRUPT_C
#define EXTERN ///< Definition used only for usb_interrupt.c to declare variable
#else
#define EXTERN extern ///< Definition used in other source files to declare external
#endif
//-------------------------------------------------------------------------------------------------------
/// USBIRQ internal module data
/*typedef struct {
uint16 eventMask; ///< Bit mask containing all pending events (see the \c USBIRQ_EVENT definitions)
BOOL inSuspend; ///< Is currently in suspend?
uint16 irqMask; ///< USB interrupts to be enabled
} USBIRQ_DATA;*/
#ifdef USBIRQ_DATA_ADDR
EXTERN __no_init __data USBIRQ_DATA usbirqData @ USBIRQ_DATA_ADDR; ///< USBIRQ internal module data at fixed address
#else
EXTERN USBIRQ_DATA __data usbirqData; ///< USBIRQ internal module data
#endif
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name USB Interrupt Events
//@{
/// Suspend signaling detected on the USB bus
/// Note that the chip should not enter PM1 while still in the interrupt routine (inside the usbirqHookProcessEvents() function )
#define USBIRQ_EVENT_SUSPEND 0x0001
/// Resume signaling detected on the USB bus
#define USBIRQ_EVENT_RESUME 0x0002
/// Reset signaling detected on the USB bus (call \ref usbfwResetHandler() for processing)
#define USBIRQ_EVENT_RESET 0x0004
/// Start of frame token received (synthesized by hardware when the next SOF token is expected, so that missing or corrupted tokens have no effect)
#define USBIRQ_EVENT_START_OF_FRAME 0x0008
/// Endpoint 0 IN/OUT setup/data transfer complete / stall sent / premature completion (call \ref usbfwSetupHandler() for processing)
#define USBIRQ_EVENT_SETUP 0x0010
/// Endpoint 1 IN data successfully transmitted to host (FIFO disarmed) / FIFO flushed / stall sent
#define USBIRQ_EVENT_EP1IN 0x0020
/// Endpoint 2 IN data successfully transmitted to host (FIFO disarmed) / FIFO flushed / stall sent
#define USBIRQ_EVENT_EP2IN 0x0040
/// Endpoint 3 IN data successfully transmitted to host (FIFO disarmed) / FIFO flushed / stall sent
#define USBIRQ_EVENT_EP3IN 0x0080
/// Endpoint 4 IN data successfully transmitted to host (FIFO disarmed) / FIFO flushed / stall sent
#define USBIRQ_EVENT_EP4IN 0x0100
/// Endpoint 5 IN data successfully transmitted to host (FIFO disarmed) / FIFO flushed / stall sent
#define USBIRQ_EVENT_EP5IN 0x0200
/// Endpoint 1 OUT data received from host (FIFO disarmed) / stall sent
#define USBIRQ_EVENT_EP1OUT 0x0400
/// Endpoint 2 OUT data received from host (FIFO disarmed) / stall sent
#define USBIRQ_EVENT_EP2OUT 0x0800
/// Endpoint 3 OUT data received from host (FIFO disarmed) / stall sent
#define USBIRQ_EVENT_EP3OUT 0x1000
/// Endpoint 4 OUT data received from host (FIFO disarmed) / stall sent
#define USBIRQ_EVENT_EP4OUT 0x2000
/// Endpoint 5 OUT data received from host (FIFO disarmed) / stall sent
#define USBIRQ_EVENT_EP5OUT 0x4000
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Interrupt Mask Access Macros
//@{
/// Clears one or more events (use one or more \c USBIRQ_EVENT bits OR'ed together)
#define USBIRQ_CLEAR_EVENTS(mask) (usbirqData.eventMask &= ~(mask))
/// Get the bit mask containing all pending events
#define USBIRQ_GET_EVENT_MASK() (usbirqData.eventMask)
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Interrupt Event Hooks
//@{
/// Called upon all USB interrupts for high-priority event processing
void usbirqHookProcessEvents(void);
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
// Function prototypes
void usbirqInit(uint16 irqMask);
#if defined HAL_SB_BOOT_CODE
void usbirqHandler(void);
#else
__interrupt void usbirqHandler(void);
#endif
//-------------------------------------------------------------------------------------------------------
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,142 @@
/***********************************************************************************
Filename: usb_reg.h
Description: Register bit defintions for CCxx11 and CC2531.
***********************************************************************************/
#ifndef USBREG_H
#define USBREG_H
// USBADDR
#define USBADDR_UPDATE 0x80
#define USBADDR_USBADDR 0x7F
// USBPOW
#define USBPOW_ISO_WAIT_SOF 0x80
#define USBPOW_RST 0x08
#define USBPOW_RESUME 0x04
#define USBPOW_SUSPEND 0x02
#define USBPOW_SUSPEND_EN 0x01
// USBIIF
#define USBIIF_INEP5IF 0x20
#define USBIIF_INEP4IF 0x10
#define USBIIF_INEP3IF 0x08
#define USBIIF_INEP2IF 0x04
#define USBIIF_INEP1IF 0x02
#define USBIIF_EP0IF 0x01
// USBOIF
#define USBOIF_OUTEP5IF 0x20
#define USBOIF_OUTEP4IF 0x10
#define USBOIF_OUTEP3IF 0x08
#define USBOIF_OUTEP2IF 0x04
#define USBOIF_OUTEP1IF 0x02
// USBCIF
#define USBCIF_SOFIF 0x08
#define USBCIF_RSTIF 0x04
#define USBCIF_RESUMEIF 0x02
#define USBCIF_SUSPENDIF 0x01
// USBIIE
#define USBIIE_INEP5IE 0x20
#define USBIIE_INEP4IE 0x10
#define USBIIE_INEP3IE 0x08
#define USBIIE_INEP2IE 0x04
#define USBIIE_INEP1IE 0x02
#define USBIIE_EP0IE 0x01
// USBOIE
#define USBOIE_OUTEP5IE 0x20
#define USBOIE_OUTEP4IE 0x10
#define USBOIE_OUTEP3IE 0x08
#define USBOIE_OUTEP2IE 0x04
#define USBOIE_OUTEP1IE 0x02
// USBCIE
#define USBCIE_SOFIE 0x08
#define USBCIE_RSTIE 0x04
#define USBCIE_RESUMEIE 0x02
#define USBCIE_SUSPENDIE 0x01
// USBCS0
#define USBCS0_CLR_SETUP_END 0x80
#define USBCS0_CLR_OUTPKT_RDY 0x40
#define USBCS0_SEND_STALL 0x20
#define USBCS0_SETUP_END 0x10
#define USBCS0_DATA_END 0x08
#define USBCS0_SENT_STALL 0x04
#define USBCS0_INPKT_RDY 0x02
#define USBCS0_OUTPKT_RDY 0x01
// USBCSIL
#define USBCSIL_CLR_DATA_TOG 0x40
#define USBCSIL_SENT_STALL 0x20
#define USBCSIL_SEND_STALL 0x10
#define USBCSIL_FLUSH_PACKET 0x08
#define USBCSIL_UNDERRUN 0x04
#define USBCSIL_PKT_PRESENT 0x02
#define USBCSIL_INPKT_RDY 0x01
// USBCSIH
#define USBCSIH_AUTOSET 0x80
#define USBCSIH_ISO 0x40
#define USBCSIH_FORCE_DATA_TOG 0x08
#define USBCSIH_IN_DBL_BUF 0x01
// USBCSOL
#define USBCSOL_CLR_DATA_TOG 0x80
#define USBCSOL_SENT_STALL 0x40
#define USBCSOL_SEND_STALL 0x20
#define USBCSOL_FLUSH_PACKET 0x10
#define USBCSOL_DATA_ERROR 0x08
#define USBCSOL_OVERRUN 0x04
#define USBCSOL_FIFO_FULL 0x02
#define USBCSOL_OUTPKT_RDY 0x01
// USBCSOH
#define USBCSOH_AUTOCLEAR 0x80
#define USBCSOH_ISO 0x40
#define USBCSOH_OUT_DBL_BUF 0x01
#define SLEEP_USB_EN 0x80
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,659 @@
/***********************************************************************************
Filename: usb_standard_request.c
Description: Handle USB standard requests.
***********************************************************************************/
/// \addtogroup module_usb_standard_requests
/// @{
#include "usb_firmware_library_headers.h"
#include "hal_types.h"
#include "hal_board.h"
/** \brief Processes the \ref GET_STATUS request (returns status for the specified recipient)
*
* The recipient bits in \ref USB_SETUP_HEADER.requestType specify the desired recipient. This is either the
* (one and only) device, a specific interface, or a specific endpoint. Some of the status bits can be
* changed with the SET_FEATURE and CLEAR_FEATURE requests.
*
* <b>Parameters</b>:
* - VALUE: Always 0
* - INDEX: Depends upon the recipient:
* - DEVICE: Always 0
* - INTERFACE: Interface number
* - ENDPOINT: Endpoint address
* - LENGTH: Always 2
*
* <b>Data (IN)</b>:
* Depends upon the recipient (the bit field illustrations are MSB first, LSB last):
* - DEVICE: <tt>00000000.000000RS</tt>, where R(1) = DEVICE_REMOTE_WAKEUP and S(0) = SELF_POWERED
* - INTERFACE: <tt>00000000.00000000</tt> (all bits are reserved)
* - ENDPOINT: <tt>00000000.0000000H</tt>, where H(0) = ENDPOINT_HALT
*/
void usbsrGetStatus(void)
{
uint8 endpoint;
static uint16 __xdata status;
// Common sanity check
if (usbSetupHeader.value || HI_UINT16(usbSetupHeader.index) || (usbSetupHeader.length != 2)) {
usbfwData.ep0Status = EP_STALL;
// Return status for device, interface, or endpoint
} else {
switch (usbSetupHeader.requestType) {
// Device status:
// Bit 0: Self powered
// Bit 1: Remote wake-up allowed
case RT_IN_DEVICE:
// Sanity check
if (LO_UINT16(usbSetupHeader.index)) {
usbfwData.ep0Status = EP_STALL;
// Get the bit values from the USBFW_DATA struct
} else {
// Self powered?
status = usbfwData.selfPowered ? 0x0001 : 0x0000;
// Remote wakeup?
if (usbfwData.remoteWakeup) status |= 0x0002;
}
break;
// Interface status:
// All bits are reserved
case RT_IN_INTERFACE:
// Sanity check
if (usbfwData.usbState != DEV_CONFIGURED) {
usbfwData.ep0Status = EP_STALL;
} else {
status = 0x0000;
}
break;
// Endpoint status:
// Bit 0: Endpoint halted
case RT_IN_ENDPOINT:
endpoint = LO_UINT16(usbSetupHeader.index) & 0x7F;
// Sanity check
if ((usbfwData.usbState != DEV_CONFIGURED) || (endpoint > 5)) {
usbfwData.ep0Status = EP_STALL;
// Translate endpoint address to status index and return the status
} else {
// IN
if (LO_UINT16(usbSetupHeader.index) & 0x80) {
status = (usbfwData.pEpInStatus[endpoint - 1] == EP_HALT) ? 0x0001 : 0x0000;
// OUT
} else {
status = (usbfwData.pEpOutStatus[endpoint - 1] == EP_HALT) ? 0x0001 : 0x0000;
}
}
break;
default:
usbfwData.ep0Status = EP_STALL;
break;
}
if (usbfwData.ep0Status != EP_STALL) {
// Send it
usbSetupData.pBuffer = (uint8 __generic *)&status;
usbSetupData.bytesLeft = 2;
usbfwData.ep0Status = EP_TX;
}
}
} // usbsrGetStatus
/** \brief Internal function used for the very similar \ref SET_FEATURE and \ref CLEAR_FEATURE requests
*
* This function either sets or clears the specified feature on the specified recipient.
*
* \param[in] set
* When TRUE, the feature is set. When FALSE, the feature is cleared.
*
* \return
* TRUE if the selected feature is supported by the USB library. FALSE to indicate that
* \ref usbsrHookClearFeature() or \ref usbsrHookSetFeature() must be called.
*/
static uint8 ChangeFeature(uint8 set)
{
uint8 endpoint;
// Sanity check
if (usbSetupHeader.length || (usbfwData.usbState != DEV_CONFIGURED) && (usbSetupHeader.index != 0)) {
usbfwData.ep0Status = EP_STALL;
// Handle based on recipient
} else {
switch (usbSetupHeader.requestType & RT_MASK_RECIP) {
// Device
case RT_RECIP_DEV:
// Sanity check
if (LO_UINT16(usbSetupHeader.value) != DEVICE_REMOTE_WAKEUP) {
return FALSE;
} else {
usbfwData.remoteWakeup = set;
usbsrHookProcessEvent(set ? USBSR_EVENT_REMOTE_WAKEUP_ENABLED : USBSR_EVENT_REMOTE_WAKEUP_DISABLED, 0);
}
break;
// Endpoint
case RT_RECIP_IF:
return FALSE;
// Endpoint
case RT_RECIP_EP:
endpoint = LO_UINT16(usbSetupHeader.index) & 0x7F;
// Sanity check
if (LO_UINT16(usbSetupHeader.value) != ENDPOINT_HALT) {
return FALSE;
} else if (endpoint > 5) {
usbfwData.ep0Status = EP_STALL;
} else {
USBFW_SELECT_ENDPOINT(endpoint);
// IN
if (LO_UINT16(usbSetupHeader.index) & 0x80) {
USBCSIL = set ? USBCSIL_SEND_STALL : USBCSIL_CLR_DATA_TOG;
usbfwData.pEpInStatus[endpoint - 1] = set ? EP_HALT : EP_IDLE;
usbsrHookProcessEvent(set ? USBSR_EVENT_EPIN_STALL_SET : USBSR_EVENT_EPIN_STALL_CLEARED, endpoint);
// OUT
} else {
USBCSOL = set ? USBCSOL_SEND_STALL : USBCSOL_CLR_DATA_TOG;
usbfwData.pEpOutStatus[endpoint - 1] = set ? EP_HALT : EP_IDLE;
usbsrHookProcessEvent(set ? USBSR_EVENT_EPOUT_STALL_SET : USBSR_EVENT_EPOUT_STALL_CLEARED, endpoint);
}
USBFW_SELECT_ENDPOINT(0);
}
break;
default:
usbfwData.ep0Status = EP_STALL;
break;
}
}
return TRUE;
} // ChangeFeature
/** \brief Processes the \ref CLEAR_FEATURE request (clears or disables a specific feature)
*
* The feature selector value must be appropriate to the recipient.
*
* <b>Parameters</b>:
* - VALUE: Feature selector:
* - \c DEVICE_REMOTE_WAKEUP(1): Enable remote wakeup
* - \c ENDPOINT_HALT(0): Clear the halt feature for the specified endpoint (not endpoint 0!)
* - INDEX: Depends upon the recipient:
* - DEVICE: Always 0
* - INTERFACE: Interface number
* - ENDPOINT: Endpoint address
* - LENGTH: Always 0
*/
void usbsrClearFeature()
{
if (!ChangeFeature(FALSE)) {
usbsrHookClearFeature();
}
} // usbsrClearFeature
/** \brief Processes the \ref SET_FEATURE request (sets or enables a specific feature)
*
* The feature selector value must be appropriate to the recipient.
*
* <b>Parameters</b>:
* - VALUE: Feature selector:
* - \c DEVICE_REMOTE_WAKEUP(1): Enable remote wakeup
* - \c ENDPOINT_HALT(0): Set the halt feature for the specified endpoint (not endpoint 0!)
* - INDEX: Depends upon the recipient:
* - DEVICE: Always 0
* - INTERFACE: Interface number
* - ENDPOINT: Endpoint address
* - LENGTH: Always 0
*/
void usbsrSetFeature(void)
{
if (!ChangeFeature(TRUE)) {
usbsrHookSetFeature();
}
} // usbsrSetFeature
/** \brief Processes the \ref SET_ADDRESS request (sets the device address for all future device
* accesses)
*
* If the value is between 1 and 127 and the device is in the default state, it will enter the address
* state. If it already is in the address state, it starts to use the newly-specified address.
*
* If the value is 0 and the device is in the address state, it will enter the default state. If it
* already is in the default state, nothing happens.
*
* <b>Parameters</b>:
* - VALUE: The device address (0-127)
* - INDEX: Always 0
* - LENGTH: Always 0
*/
void usbsrSetAddress(void)
{
// Sanity check
if (usbSetupHeader.index || usbSetupHeader.length || HI_UINT16(usbSetupHeader.value) || (LO_UINT16(usbSetupHeader.value) & 0x80)) {
usbfwData.ep0Status = EP_STALL;
// Update the device address
} else {
USBADDR = LO_UINT16(usbSetupHeader.value);
if (LO_UINT16(usbSetupHeader.value) != 0) {
if (usbfwData.usbState == DEV_DEFAULT) usbfwData.usbState = DEV_ADDRESS;
} else {
if (usbfwData.usbState == DEV_ADDRESS) usbfwData.usbState = DEV_DEFAULT;
}
}
} // usbsrSetAddress
/** \brief Processes the \ref GET_DESCRIPTOR request (returns the specified USB descriptor)
*
* The \ref module_usb_descriptor_parser module is used to locate device, configuration and string
* descriptors. Note that configuration descriptors also include interface, endpoint and other
* "similar" descriptor types (e.g. HID descriptor), with the total descriptor length specified by
* the \ref USB_CONFIGURATION_DESCRIPTOR.wTotalLength field.
*
* Other descriptor types that are not returned with the configuration descriptor, must be defined in
* the usbDescriptorMarker.pUsbDescLut lookup-table. This table specifies the values of the VALUE and INDEX fields, and
* gives a pointer to the descriptor along with it's length.
*
* <b>Parameters</b>:
* - VALUE.MSB: Descriptor type
* - VALUE.LSB: Descriptor index
* - INDEX: 0, or language ID for string descriptors (currently not supported)
* - LENGTH: Descriptor length (either the requested number of bytes, or the length of the descriptor,
* whichever is the smallest)
*
* <b>Data (IN)</b>:
* The descriptor(s)
*/
void usbsrGetDescriptor(void)
{
uint8 n;
// Which descriptor?
switch (HI_UINT16(usbSetupHeader.value)) {
// Device descriptor
case DESC_TYPE_DEVICE:
usbSetupData.pBuffer = (uint8 __code*) usbdpGetDeviceDesc();
usbSetupData.bytesLeft = usbSetupData.pBuffer[DESC_LENGTH_IDX];
break;
// Configuration descriptor
case DESC_TYPE_CONFIG:
usbSetupData.pBuffer = (uint8 __code*) usbdpGetConfigurationDesc(0, LO_UINT16(usbSetupHeader.value));
usbSetupData.bytesLeft = usbSetupData.pBuffer[DESC_CONFIG_LENGTH_LSB_IDX] +
usbSetupData.pBuffer[DESC_CONFIG_LENGTH_MSB_IDX] * 256;
break;
// String descriptor
case DESC_TYPE_STRING:
// TODO: Implement language ID
usbSetupData.pBuffer = (uint8 *)usbdpGetStringDesc(LO_UINT16(usbSetupHeader.value));
usbSetupData.bytesLeft = usbSetupData.pBuffer[DESC_LENGTH_IDX];
break;
// Other descriptor type
default:
// Perform a table search (on index and value)
usbSetupData.pBuffer = NULL;
for (n = 0; n < ((uint16)usbDescriptorMarker.pUsbDescLutEnd - (uint16)usbDescriptorMarker.pUsbDescLut) / sizeof(DESC_LUT_INFO); n++) {
if ((usbDescriptorMarker.pUsbDescLut[n].valueMsb == HI_UINT16(usbSetupHeader.value))
&& (usbDescriptorMarker.pUsbDescLut[n].valueLsb == LO_UINT16(usbSetupHeader.value))
&& (usbDescriptorMarker.pUsbDescLut[n].indexMsb == HI_UINT16(usbSetupHeader.index))
&& (usbDescriptorMarker.pUsbDescLut[n].indexLsb == LO_UINT16(usbSetupHeader.index)) )
{
usbSetupData.pBuffer = usbDescriptorMarker.pUsbDescLut[n].pDescStart;
usbSetupData.bytesLeft = usbDescriptorMarker.pUsbDescLut[n].length;
}
}
}
// Stall EP0 if no descriptor was found
if (usbSetupData.pBuffer == NULL) usbfwData.ep0Status = EP_STALL;
if (usbfwData.ep0Status != EP_STALL) {
// Limit the returned descriptor size (the PC wants to know about sizes before
// polling the complete descriptors)
if (usbSetupData.bytesLeft > usbSetupHeader.length) {
usbSetupData.bytesLeft = usbSetupHeader.length;
}
usbfwData.ep0Status = EP_TX;
}
} // usbsrGetDescriptor
/** \brief Internally used function that configures all endpoints for the specified interface
*
* The new endpoint setup overwrites the old, without any warning. Unused endpoints keep their current
* setup. The user is responsible for ensuring that no endpoint buffers overwrite each other, and that
* interfaces do not cause conflicts. The pUsbDblbufLutInfo table must contain an entry for each
* interface descriptor to define endpoint double-buffering.
*
* \param[in] *pInterface
* A pointer to the interface descriptor
*/
static void ConfigureEndpoints(USB_INTERFACE_DESCRIPTOR __code *pInterface)
{
uint8 n;
uint16 maxpRegValue;
uint8 csRegValue;
uint8 endpoint;
USB_ENDPOINT_DESCRIPTOR __code *pEndpoint;
DBLBUF_LUT_INFO __code *pUsbDblbufLutInfo;
// Locate the double buffer settings
if (pInterface->bNumEndpoints) {
pUsbDblbufLutInfo = (DBLBUF_LUT_INFO __code*) usbDescriptorMarker.pUsbDblbufLut;
while (pUsbDblbufLutInfo->pInterface != pInterface) {
pUsbDblbufLutInfo++;
}
}
// For each endpoint in this interface
for (n = 0; n < pInterface->bNumEndpoints; n++) {
if (pEndpoint = usbdpFindNext(DESC_TYPE_ENDPOINT, 0)) {
// Get the endpoint index
endpoint = pEndpoint->bEndpointAddress & 0x0F;
USBFW_SELECT_ENDPOINT(endpoint);
csRegValue = 0x00;
maxpRegValue = (pEndpoint->wMaxPacketSize + 7) >> 3;
// For IN endpoints...
if (pEndpoint->bEndpointAddress & 0x80) {
// Clear data toggle, and flush twice (due to double buffering)
USBCSIL = USBCSIL_CLR_DATA_TOG | USBCSIL_FLUSH_PACKET;
USBCSIL = USBCSIL_FLUSH_PACKET;
// USBCSIH
if ((pEndpoint->bmAttributes & EP_ATTR_TYPE_BM) == EP_ATTR_ISO) csRegValue |= USBCSIH_ISO; // ISO flag
if (pUsbDblbufLutInfo->inMask & (1 << endpoint)) csRegValue |= USBCSIH_IN_DBL_BUF; // Double buffering
USBCSIH = csRegValue;
// Max transfer size
USBMAXI = maxpRegValue;
// Endpoint status
usbfwData.pEpInStatus[endpoint - 1] = EP_IDLE;
// For OUT endpoints...
} else {
// Clear data toggle, and flush twice (due to double buffering)
USBCSOL = USBCSOL_CLR_DATA_TOG | USBCSOL_FLUSH_PACKET;
USBCSOL = USBCSOL_FLUSH_PACKET;
// USBCSOH
if ((pEndpoint->bmAttributes & EP_ATTR_TYPE_BM) == EP_ATTR_ISO) csRegValue |= USBCSOH_ISO; // ISO flag
if (pUsbDblbufLutInfo->outMask & (1 << endpoint)) csRegValue |= USBCSOH_OUT_DBL_BUF; // Double buffering
USBCSOH = csRegValue;
// Max transfer size
USBMAXO = maxpRegValue;
// Endpoint status
usbfwData.pEpOutStatus[endpoint - 1] = EP_IDLE;
}
USBFW_SELECT_ENDPOINT(0);
}
}
} // ConfigureEndpoints
/** \brief Processes the \ref GET_CONFIGURATION request (returns the current device configuration value)
*
* If the returned value is 0, the device is not configured (not in the configured state)
*
* <b>Parameters</b>:
* - VALUE: Always 0
* - INDEX: Always 0
* - LENGTH: Always 1
*
* <b>Data (IN)</b>:
* The non-zero \ref USB_CONFIGURATION_DESCRIPTOR.bConfigurationValue of the currently selected
* configuration.
*/
void usbsrGetConfiguration(void)
{
// Sanity check
if (usbSetupHeader.value || usbSetupHeader.index || (usbSetupHeader.length != 1)) {
usbfwData.ep0Status = EP_STALL;
// Return the current configuration
} else {
usbSetupData.pBuffer = &usbfwData.configurationValue;
usbSetupData.bytesLeft = 1;
usbfwData.ep0Status = EP_TX;
}
} // usbsrGetConfiguration
/** \brief Processes the \ref SET_CONFIGURATION request (sets the device configuration)
*
* The configuration value must either be 0, in which case the device enters the address state, or it
* must match a configuration value from one of the USB configuration descriptors. If there is a match,
* the device enters the configured state.
*
* This request resets all interfaces to alternate setting 0, and uses the \c ConfigureEndpoints()
* function to automatically setup all endpoint registers.
*
* <b>Parameters</b>:
* - VALUE: The configuration value (0-255)
* - INDEX: Always 0
* - LENGTH: Always 0
*/
void usbsrSetConfiguration(void)
{
uint8 n;
USB_CONFIGURATION_DESCRIPTOR __code *pConfiguration;
USB_INTERFACE_DESCRIPTOR __code *pInterface;
// Sanity check
if ((usbfwData.usbState == DEV_DEFAULT) || usbSetupHeader.index || usbSetupHeader.length || HI_UINT16(usbSetupHeader.value)) {
usbfwData.ep0Status = EP_STALL;
// Default endpoint setup
} else {
usbsrHookProcessEvent(USBSR_EVENT_CONFIGURATION_CHANGING, 0);
// Configure relevant endpoints
if (LO_UINT16(usbSetupHeader.value)) {
// Find the correct configuration descriptor...
pConfiguration = usbdpGetConfigurationDesc(LO_UINT16(usbSetupHeader.value), 0);
// If it exists...
if (pConfiguration) {
usbfwData.usbState = DEV_CONFIGURED;
usbfwData.configurationValue = LO_UINT16(usbSetupHeader.value);
// For each interface...
for (n = 0; n < pConfiguration->bNumInterfaces; n++) {
usbfwData.pAlternateSetting[n] = 0x00;
// Look only for alternate setting 0
do {
pInterface = usbdpFindNext(DESC_TYPE_INTERFACE, 0);
} while (pInterface->bAlternateSetting != usbfwData.pAlternateSetting[n]);
// Configure all endpoints in this interface
ConfigureEndpoints(pInterface);
}
// If not, then stall the endpoint
} else {
usbfwData.ep0Status = EP_STALL;
}
// Unconfigure endpoints
} else {
usbfwData.configurationValue = LO_UINT16(usbSetupHeader.value);
usbfwData.usbState = DEV_ADDRESS;
usbfwSetAllEpStatus(EP_HALT);
}
usbsrHookProcessEvent(USBSR_EVENT_CONFIGURATION_CHANGED, 0);
}
} // usbsrSetConfiguration
/** \brief Processes the \ref GET_INTERFACE request (returns the selected alternate setting for the
* specified interface)
*
* Some USB devices have configurations with mutually exclusive interface settings. This request allows
* the host to determine the currently selected alternate setting.
*
* <b>Parameters</b>:
* - VALUE: Always 0
* - INDEX: Interface number
* - LENGTH: Always 1
*
* <b>Data (IN)</b>:
* The alternate setting for the selected interface
*/
void usbsrGetInterface(void)
{
// Sanity check
if ((usbfwData.usbState != DEV_CONFIGURED) || (usbSetupHeader.requestType != RT_IN_INTERFACE) || usbSetupHeader.value || (usbSetupHeader.length != 1)) {
usbfwData.ep0Status = EP_STALL;
// Return the current alternate setting
} else {
usbSetupData.pBuffer = &usbfwData.pAlternateSetting[usbSetupHeader.index];
usbSetupData.bytesLeft = 1;
usbfwData.ep0Status = EP_TX;
}
} // usbsrGetInterface
/** \brief Processes the \ref SET_INTERFACE request (selects an alternate setting for the specified
* interface)
*
* Some USB devices have configurations with mutually exclusive interface settings. This request allows
* the host to select the desired alternate setting.
*
* This function uses the \c ConfigureEndpoints() to automatically setup the relevant endpoint
* registers.
*
* <b>Parameters</b>:
* - VALUE: Alternate setting
* - INDEX: Interface number
* - LENGTH: Always 0
*/
void usbsrSetInterface(void)
{
USB_INTERFACE_DESCRIPTOR __code *pInterface;
// Sanity check
if ((usbfwData.usbState != DEV_CONFIGURED) || (usbSetupHeader.requestType != RT_OUT_INTERFACE) || usbSetupHeader.length) {
usbfwData.ep0Status = EP_STALL;
// Verify that the desired alternate setting is available, and then make the switch
} else {
if (pInterface = usbdpGetInterfaceDesc(usbfwData.configurationValue, usbSetupHeader.index, usbSetupHeader.value)) {
usbsrHookProcessEvent(USBSR_EVENT_INTERFACE_CHANGING, usbSetupHeader.index);
usbfwData.pAlternateSetting[usbSetupHeader.index] = usbSetupHeader.value;
// Configure all endpoints in this interface
ConfigureEndpoints(pInterface);
usbsrHookProcessEvent(USBSR_EVENT_INTERFACE_CHANGED, usbSetupHeader.index);
// This interface does not exist
} else {
usbfwData.ep0Status = EP_STALL;
}
}
} // usbsrSetInterface
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2010 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/

View File

@@ -0,0 +1,201 @@
/***********************************************************************************
Filename: usb_standard_request.h
Description: Handle USB standard requests.
***********************************************************************************/
#ifndef USBSTANDARDREQUESTS_H
#define USBSTANDARDREQUESTS_H
/** \addtogroup module_usb_standard_requests USB Standard Requests (usbsr)
* \brief This module contains automated functions for processing USB standard requests
*
* The processing functions are based on the \ref module_usb_framework, and access to the user-provided
* USB descriptors through the \ref module_usb_descriptor_parser. All device classes and descriptor
* combinations are supported, with no need to write or modify any source code. However, as described
* below, some standard request must be fully or partially implemented by the user.
*
* \section section_usbsr_hooks Hooks
* Standard requests that are not supported by the USB library or that refer to non-standard features,
* are forwarded to the application via function hooks. This includes:
* \li All \ref SET_DESCRIPTOR requests (see \ref usbsrHookSetDescriptor())
* \li All \ref SYNCH_FRAME requests (see \ref usbsrHookSynchFrame())
* \li \ref CLEAR_FEATURE requests that refer to unknown features (see \ref usbsrHookClearFeature())
* \li \ref SET_FEATURE requests that refer to unknown features (see \ref usbsrHookSetFeature())
*
* These hooks must always be provided, however if the application does not either support the requests,
* it should just stall endpoint 0. The processing uses the same mechanisms as for class and vendor
* requests (refer to the \ref module_usb_framework module for detailed description and examples).
*
* When the \ref GET_STATUS request is received, the \ref usbsrHookModifyGetStatus() hook is always
* called, so that additional status bits may be added.
*
* To have any practical purpose, "OUT data phase" standard requests need to notify the application of
* certain events. This is done by passing the event via yet another function hook,
* \ref usbsrHookProcessEvent(uint8 event, uint8 index). For events related to interfaces and endpoints,
* the \c index parameter refers to an interface number or the least significant nibble of the endpoint
* address. The following events can be generated:
* \li \ref USBSR_EVENT_CONFIGURATION_CHANGING (the device configuration is about to change)
* \li \ref USBSR_EVENT_CONFIGURATION_CHANGED (the device configuration has changed)
* \li \ref USBSR_EVENT_INTERFACE_CHANGING (the alternate setting of the given interface is about to
* change)
* \li \ref USBSR_EVENT_INTERFACE_CHANGED (the alternate setting of the given interface has changed)
* \li \ref USBSR_EVENT_REMOTE_WAKEUP_ENABLED (remote wakeup has been enabled by the host)
* \li \ref USBSR_EVENT_REMOTE_WAKEUP_DISABLED (remote wakeup has been disabled by the host)
* \li \ref USBSR_EVENT_EPIN_STALL_CLEARED (the given IN endpoint's stall condition has been cleared the
* host)
* \li \ref USBSR_EVENT_EPIN_STALL_SET (the given IN endpoint has been stalled by the host)
* \li \ref USBSR_EVENT_EPOUT_STALL_CLEARED (the given OUT endpoint's stall condition has been cleared
* the host)
* \li \ref USBSR_EVENT_EPOUT_STALL_SET (the given OUT endpoint has been stalled by the PC)
* @{
*/
//-------------------------------------------------------------------------------------------------------
/// \name Standard Request Codes
//@{
/// Standard request that returns status for the specified recipient
#define GET_STATUS 0x00
/// Standard request that clears or disables a specific feature
#define CLEAR_FEATURE 0x01
/// Standard request that sets or enables a specific feature
#define SET_FEATURE 0x03
/// Standard request that sets the device address for all future device accesses
#define SET_ADDRESS 0x05
/// Standard request that returns the specified USB descriptor
#define GET_DESCRIPTOR 0x06
/// Standard request that may be used to update exitsting descriptors or new descriptors may be added
#define SET_DESCRIPTOR 0x07
/// Standard request that returns the current device configuration value
#define GET_CONFIGURATION 0x08
/// Standard request that sets the device configuration
#define SET_CONFIGURATION 0x09
/// Standard request that returns the selected alternate setting for the specified interface
#define GET_INTERFACE 0x0A
/// Standard request that selects an alternate setting for the specified interface
#define SET_INTERFACE 0x0B
/// Standard request that is used to set and then report an endpoint's synchronization frame
#define SYNCH_FRAME 0x0C
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Features Indexes
//@{
/// Endpoint feature: Halt
#define ENDPOINT_HALT 0x00
/// Device feature: Remote wakeup
#define DEVICE_REMOTE_WAKEUP 0x01
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Event Types
//@{
/// The device configuration is about to change
#define USBSR_EVENT_CONFIGURATION_CHANGING 0x01
/// The device configuration has changed
#define USBSR_EVENT_CONFIGURATION_CHANGED 0x02
/// The alternate setting of the given interface about to change (index = "interface index")
#define USBSR_EVENT_INTERFACE_CHANGING 0x03
/// The alternate setting of the given interface has changed (index = "interface index")
#define USBSR_EVENT_INTERFACE_CHANGED 0x04
/// Remote wakeup has been enabled by the host
#define USBSR_EVENT_REMOTE_WAKEUP_ENABLED 0x05
/// Remote wakeup has been disabled by the host
#define USBSR_EVENT_REMOTE_WAKEUP_DISABLED 0x06
/// The given IN endpoint has been unstalled by the PC (index = "endpoint address" & 0x0F)
#define USBSR_EVENT_EPIN_STALL_CLEARED 0x07 /* Endpoint index */
/// The given IN endpoint has been stalled by the PC (index = "endpoint address" & 0x0F)
#define USBSR_EVENT_EPIN_STALL_SET 0x08 /* Endpoint index */
/// The given OUT endpoint has been unstalled by the PC (index = "endpoint address" & 0x0F)
#define USBSR_EVENT_EPOUT_STALL_CLEARED 0x09 /* Endpoint index */
/// The given OUT endpoint has been stalled by the PC (index = "endpoint address" & 0x0F)
#define USBSR_EVENT_EPOUT_STALL_SET 0x0A /* Endpoint index */
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Standard Request Hooks
//@{
/// Refer to the \ref section_setup_handler_usage section for a description on how to process standard
/// requests.
/// Hook which is called upon reception of a \ref SET_DESCRIPTOR request
void usbsrHookSetDescriptor(void);
/// Hook which is called upon reception of a \ref SYNCH_FRAME request (unsupported).
void usbsrHookSynchFrame(void);
/// Hook which is called when a \ref CLEAR_FEATURE request refers to a an unsupported featureted.
void usbsrHookClearFeature(void);
/// Hook which is called when a \ref SET_FEATURE request refers to a an unsupported feature.
void usbsrHookSetFeature(void);
/// Hook for modifying a \ref GET_STATUS request before the status value is returned to the PC.
void usbsrHookModifyGetStatus(uint8 recipient, uint8 index, uint16 __xdata *pStatus);
/// Hook which is called upon a standard request generated event (unsupported).
void usbsrHookProcessEvent(uint8 event, uint8 index);
//@}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
/// \name Handled Standard Requests
//@{
void usbsrGetStatus(void);
void usbsrClearFeature(void);
void usbsrSetFeature(void);
void usbsrSetAddress(void);
void usbsrGetDescriptor(void);
void usbsrGetConfiguration(void);
void usbsrSetConfiguration(void);
void usbsrGetInterface(void);
void usbsrSetInterface(void);
//@}
//-------------------------------------------------------------------------------------------------------
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,143 @@
/***********************************************************************************
Filename: usb_suspend.h
Description: Handle the USB suspend state.
***********************************************************************************/
#ifndef USBSUSPEND_H
#define USBSUSPEND_H
/** \addtogroup module_usb_suspend USB Suspend (usbsusp)
* \brief This module contains the functionality for USB suspend, USB resume and USB remote wakeup.
*
* All USB devices must support the suspended state to fully comply with the USB specification. Special
* care must be taken to implement this functionality correctly, so follow the instructions below
* carefully. Refer to the USB specification for detailed information on current consumption in suspend
* mode (how power consumption shall be measured, averaging, peak value etc.).
*
* \section usb_suspend_resume USB Suspend and Resume
* If there is no activity on the USB bus for a period longer than 3 ms, the MCU will generate a
* \ref USBIRQ_EVENT_SUSPEND event. The USB device must then enter suspend mode within 10 ms, where it
* draws no more than:
* \li 500 uA for low-power devices or high-power devices operating at lower-power
* \li 2.5 mA for high-power devices with remote wake-up enabled
*
* The library supports the USB suspend and resume functionality through a simple interface:
* \li Make sure that the 48 MHz XOSC is never turned off anywhere in the application.
* \li In the call to \ref usbirqInit(), add \ref USBIRQ_EVENT_SUSPEND and \ref USBIRQ_EVENT_RESUME
* (optional) to the interrupt mask.
* \li Do NOT process \ref USBIRQ_EVENT_SUSPEND in \ref usbirqHookProcessEvents() or in any other
* interrupt service routine. This may (or in most cases will) prevent the USB device from getting
* out of suspend mode.
*
* \li In the main loop, add the code shown below. Make sure that this code is visited at least every
* 10 ms. If the worst-case path through the main loop uses more than 10 ms, the code block can be
* inserted in multiple places in the loop until the requirement is met.
* \code
* // Process USB suspend events
* if (USBIRQ_GET_EVENT_MASK() & USBIRQ_EVENT_SUSPEND) {
*
* // Clear the suspend event
* USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_SUSPEND);
*
* ... Do what needs to be done before entering power mode 1 here (e.g. turn off the radio, configure
* I/O to minimize power consumption, start the sleep timer etc.) ...
*
* // This function call will take the USB device into power mode 1. It will not return until resume
* // signaling has been detected on the bus, or the remote wake-up function has been used. Other
* // interrupts (for instance from I/O ports or the sleep timer) can be used during this period. When
* // returning from these interrupts, the \ref usbsuspEnter() function (running here) will put the
* // MCU back into power mode 1.
* usbsuspEnter();
*
* // At this point the event handler is up and running again. Clear the resume event.
* USBIRQ_CLEAR_EVENTS(USBIRQ_EVENT_RESUME);
*
* ... If a USBIRQ_EVENT_RESET event will affect the code that follows (before the event is processed
* elsewhere), then make sure to handle it here also ...
*
* ... Do what needs to be done to wake up from suspend mode (e.g. turn on the radio, reactivate I/O
* and peripherals, turn off the sleep timer ...
* }
* \endcode
*
* \li All interrupts that run during suspension mode must start with the following code:
* \code
* while (!XOSC_STABLE);
* \endcode
*
* \section usb_remote_wakeup USB Remote Wakeup:
* Remote wakeup should be used when the USB device desires to initiate the resume process and wake up
* the host. In a radio application this may happen when a particular radio packet is received, for
* instance from a wireless keyboard or mouse.
*
* USB remote wakeup can only be performed if the host has given the device the privilege to do so. The
* privilege to perform remote wakeup is requested by setting bit 5 in the \c bmAttributes field in
* the \ref USB_CONFIGURATION_DESCRIPTOR. The host will then grant or recall the privilege through a
* SET_FEATURE request, which is communicated through a \ref USBSR_EVENT_REMOTE_WAKEUP_ENABLED or
* \ref USBSR_EVENT_REMOTE_WAKEUP_DISABLED event, respectively.
*
* The USB library handles the remote wakeup sequence automatically. Do the following to incorporate it
* into the application:
* \li Implement suspend and resume as described above.
* \li In the USB descriptor, set bit 5 in bmAttributes in the configuration descriptor.
* \li While the USB MCU is in USB suspend mode, remote wakeup can be performed from interrupt context
* (e.g. the sleep timer interrupt) by calling \ref usbsuspDoRemoteWakeup(). This function will
* return TRUE if successful or FALSE if remote wakeup is not permitted (by the host).
* @{
*/
#include "usb_firmware_library_headers.h"
typedef void (*VFPTR)(void);
//-------------------------------------------------------------------------------------------------------
// Suspend enter/exit hooks
extern __xdata VFPTR pFnSuspendEnterHook;
extern __xdata VFPTR pFnSuspendExitHook;
//-------------------------------------------------------------------------------------------------------
// Function prototypes
void usbsuspEnter(void);
uint8 usbsuspDoRemoteWakeup(void);
void usbsuspStopPm1(void);
//-------------------------------------------------------------------------------------------------------
//@}
/*
+------------------------------------------------------------------------------
| Copyright 2004-2007 Texas Instruments Incorporated. All rights reserved.
|
| IMPORTANT: Your use of this Software is limited to those specific rights
| granted under the terms of a software license agreement between the user who
| downloaded the software, his/her employer (which must be your employer) and
| Texas Instruments Incorporated (the "License"). You may not use this Software
| unless you agree to abide by the terms of the License. The License limits
| your use, and you acknowledge, that the Software may not be modified, copied
| or distributed unless embedded on a Texas Instruments microcontroller or used
| solely and exclusively in conjunction with a Texas Instruments radio
| frequency transceiver, which is integrated into your product. Other than for
| the foregoing purpose, you may not use, reproduce, copy, prepare derivative
| works of, modify, distribute, perform, display or sell this Software and/or
| its documentation for any purpose.
|
| YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
| PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
| INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
| NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
| TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
| NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
| LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING
| BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
| CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
| SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
| (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
|
| Should you have any questions regarding your right to use this Software,
| contact Texas Instruments Incorporated at www.TI.com.
|
+------------------------------------------------------------------------------
*/
#endif

View File

@@ -0,0 +1,856 @@
/**************************************************************************************************
Filename: _hal_uart_dma.c
Revised: $Date: 2010-04-01 18:14:33 -0700 (Thu, 01 Apr 2010) $
Revision: $Revision: 22068 $
Description: This file contains the interface to the H/W UART driver by DMA.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_assert.h"
#include "hal_board.h"
#include "hal_defs.h"
#include "hal_dma.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if defined MT_TASK
#include "mt_uart.h"
#endif
#include "osal.h"
#if defined POWER_SAVING
#include "OSAL_PwrMgr.h"
#endif
#include "ZComDef.h"
#include "ZGlobals.h"
#include "ZMac.h"
#include "znp_app.h"
/*********************************************************************
* MACROS
*/
//#define HAL_UART_ASSERT(expr) HAL_ASSERT((expr))
#define HAL_UART_ASSERT(expr)
#if defined HAL_BOARD_CC2430EB || defined HAL_BOARD_CC2430DB || defined HAL_BOARD_CC2430BB
#define HAL_UART_DMA_NEW_RX_BYTE(IDX) (DMA_PAD == LO_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_GET_RX_BYTE(IDX) (HI_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_CLR_RX_BYTE(IDX) (dmaCfg.rxBuf[(IDX)] = BUILD_UINT16((DMA_PAD ^ 0xFF), 0))
#else
#define HAL_UART_DMA_NEW_RX_BYTE(IDX) (DMA_PAD == HI_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_GET_RX_BYTE(IDX) (LO_UINT16(dmaCfg.rxBuf[(IDX)]))
#define HAL_UART_DMA_CLR_RX_BYTE(IDX) (dmaCfg.rxBuf[(IDX)] = BUILD_UINT16(0, (DMA_PAD ^ 0xFF)))
#endif
/*********************************************************************
* CONSTANTS
*/
// UxCSR - USART Control and Status Register.
#define CSR_MODE 0x80
#define CSR_RE 0x40
#define CSR_SLAVE 0x20
#define CSR_FE 0x10
#define CSR_ERR 0x08
#define CSR_RX_BYTE 0x04
#define CSR_TX_BYTE 0x02
#define CSR_ACTIVE 0x01
// UxUCR - USART UART Control Register.
#define UCR_FLUSH 0x80
#define UCR_FLOW 0x40
#define UCR_D9 0x20
#define UCR_BIT9 0x10
#define UCR_PARITY 0x08
#define UCR_SPB 0x04
#define UCR_STOP 0x02
#define UCR_START 0x01
#define UTX0IE 0x04
#define UTX1IE 0x08
#define P2DIR_PRIPO 0xC0
// Incompatible redefinitions result with more than one UART driver sub-module.
#undef PxOUT
#undef PxDIR
#undef PxSEL
#undef UxCSR
#undef UxUCR
#undef UxDBUF
#undef UxBAUD
#undef UxGCR
#undef URXxIE
#undef URXxIF
#undef UTXxIE
#undef UTXxIF
#undef HAL_UART_PERCFG_BIT
#undef HAL_UART_Px_RTS
#undef HAL_UART_Px_CTS
#undef HAL_UART_Px_RX_TX
#if (HAL_UART_DMA == 1)
#define PxOUT P0
#define PxIN P0
#define PxDIR P0DIR
#define PxSEL P0SEL
#define UxCSR U0CSR
#define UxUCR U0UCR
#define UxDBUF U0DBUF
#define UxBAUD U0BAUD
#define UxGCR U0GCR
#define URXxIE URX0IE
#define URXxIF URX0IF
#define UTXxIE UTX0IE
#define UTXxIF UTX0IF
#else
#define PxOUT P1
#define PxIN P1
#define PxDIR P1DIR
#define PxSEL P1SEL
#define UxCSR U1CSR
#define UxUCR U1UCR
#define UxDBUF U1DBUF
#define UxBAUD U1BAUD
#define UxGCR U1GCR
#define URXxIE URX1IE
#define URXxIF URX1IF
#define UTXxIE UTX1IE
#define UTXxIF UTX1IF
#endif
#if (HAL_UART_DMA == 1)
#define HAL_UART_PERCFG_BIT 0x01 // USART0 on P0, Alt-1; so clear this bit.
#define HAL_UART_Px_RX_TX 0x0C // Peripheral I/O Select for Rx/Tx.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#else
#define HAL_UART_PERCFG_BIT 0x02 // USART1 on P1, Alt-2; so set this bit.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#define HAL_UART_Px_RX_TX 0xC0 // Peripheral I/O Select for Rx/Tx.
#endif
// The timeout tick is at 32-kHz, so multiply msecs by 33.
#define HAL_UART_MSECS_TO_TICKS 33
#if defined MT_TASK
#define HAL_UART_DMA_TX_MAX MT_UART_DEFAULT_MAX_TX_BUFF
#define HAL_UART_DMA_RX_MAX MT_UART_DEFAULT_MAX_RX_BUFF
#define HAL_UART_DMA_HIGH MT_UART_DEFAULT_THRESHOLD
#define HAL_UART_DMA_IDLE (MT_UART_DEFAULT_IDLE_TIMEOUT * HAL_UART_MSECS_TO_TICKS)
#else
#if !defined HAL_UART_DMA_RX_MAX
#define HAL_UART_DMA_RX_MAX 256
#endif
#if !defined HAL_UART_DMA_TX_MAX
#define HAL_UART_DMA_TX_MAX HAL_UART_DMA_RX_MAX
#endif
#if !defined HAL_UART_DMA_HIGH
#define HAL_UART_DMA_HIGH (HAL_UART_DMA_RX_MAX / 2 - 16)
#endif
#if !defined HAL_UART_DMA_IDLE
#define HAL_UART_DMA_IDLE (1 * HAL_UART_MSECS_TO_TICKS)
#endif
#endif
#if !defined HAL_UART_DMA_FULL
#define HAL_UART_DMA_FULL (HAL_UART_DMA_RX_MAX - 16)
#endif
#if defined HAL_BOARD_CC2430EB || defined HAL_BOARD_CC2430DB || defined HAL_BOARD_CC2430BB
#define HAL_DMA_U0DBUF 0xDFC1
#define HAL_DMA_U1DBUF 0xDFF9
#else /* CC2530 */
#define HAL_DMA_U0DBUF 0x70C1
#define HAL_DMA_U1DBUF 0x70F9
#endif
#if (HAL_UART_DMA == 1)
#define DMATRIG_RX HAL_DMA_TRIG_URX0
#define DMATRIG_TX HAL_DMA_TRIG_UTX0
#define DMA_UDBUF HAL_DMA_U0DBUF
#define DMA_PAD U0BAUD
#else
#define DMATRIG_RX HAL_DMA_TRIG_URX1
#define DMATRIG_TX HAL_DMA_TRIG_UTX1
#define DMA_UDBUF HAL_DMA_U1DBUF
#define DMA_PAD U1BAUD
#endif
/*********************************************************************
* TYPEDEFS
*/
#if HAL_UART_DMA_RX_MAX <= 256
typedef uint8 rxIdx_t;
#else
typedef uint16 rxIdx_t;
#endif
#if HAL_UART_DMA_TX_MAX <= 256
typedef uint8 txIdx_t;
#else
typedef uint16 txIdx_t;
#endif
typedef struct
{
uint16 rxBuf[HAL_UART_DMA_RX_MAX];
rxIdx_t rxHead;
rxIdx_t rxTail;
uint8 rxTick;
uint8 rxShdw;
uint8 txBuf[2][HAL_UART_DMA_TX_MAX];
txIdx_t txIdx[2];
volatile uint8 txSel;
uint8 txMT;
uint8 txTick; // 1-character time in 32kHz ticks according to baud rate,
// to be used in calculating time lapse since DMA ISR
// to allow delay margin before start firing DMA, so that
// DMA does not overwrite UART DBUF of previous packet
volatile uint8 txShdw; // Sleep Timer LSB shadow.
volatile uint8 txShdwValid; // TX shadow value is valid
uint8 txDMAPending; // UART TX DMA is pending
halUARTCBack_t uartCB;
} uartDMACfg_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
void HalUARTIsrDMA(void);
/*********************************************************************
* LOCAL VARIABLES
*/
static uartDMACfg_t dmaCfg;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static rxIdx_t findTail(void);
// Invoked by functions in hal_uart.c when this file is included.
static void HalUARTInitDMA(void);
static void HalUARTOpenDMA(halUARTCfg_t *config);
static uint16 HalUARTReadDMA(uint8 *buf, uint16 len);
static uint16 HalUARTWriteDMA(uint8 *buf, uint16 len);
static void HalUARTPollDMA(void);
static uint16 HalUARTRxAvailDMA(void);
static void HalUARTSuspendDMA(void);
static void HalUARTResumeDMA(void);
/*****************************************************************************
* @fn findTail
*
* @brief Find the rxBuf index where the DMA RX engine is working.
*
* @param None.
*
* @return Index of tail of rxBuf.
*****************************************************************************/
static rxIdx_t findTail(void)
{
rxIdx_t idx = dmaCfg.rxHead;
do
{
if (!HAL_UART_DMA_NEW_RX_BYTE(idx))
{
break;
}
#if HAL_UART_DMA_RX_MAX == 256
idx++;
#else
if (++idx >= HAL_UART_DMA_RX_MAX)
{
idx = 0;
}
#endif
} while (idx != dmaCfg.rxHead);
return idx;
}
/******************************************************************************
* @fn HalUARTInitDMA
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTInitDMA(void)
{
halDMADesc_t *ch;
P2DIR &= ~P2DIR_PRIPO;
P2DIR |= HAL_UART_PRIPO;
#if (HAL_UART_DMA == 1)
PERCFG &= ~HAL_UART_PERCFG_BIT; // Set UART0 I/O to Alt. 1 location on P0.
#else
PERCFG |= HAL_UART_PERCFG_BIT; // Set UART1 I/O to Alt. 2 location on P1.
#endif
PxSEL |= HAL_UART_Px_RX_TX; // Enable Tx and Rx on P1.
ADCCFG &= ~HAL_UART_Px_RX_TX; // Make sure ADC doesnt use this.
UxCSR = CSR_MODE; // Mode is UART Mode.
UxUCR = UCR_FLUSH; // Flush it.
// Setup Tx by DMA.
ch = HAL_DMA_GET_DESC1234( HAL_DMA_CH_TX );
// The start address of the destination.
HAL_DMA_SET_DEST( ch, DMA_UDBUF );
// Using the length field to determine how many bytes to transfer.
HAL_DMA_SET_VLEN( ch, HAL_DMA_VLEN_USE_LEN );
// One byte is transferred each time.
HAL_DMA_SET_WORD_SIZE( ch, HAL_DMA_WORDSIZE_BYTE );
// The bytes are transferred 1-by-1 on Tx Complete trigger.
HAL_DMA_SET_TRIG_MODE( ch, HAL_DMA_TMODE_SINGLE );
HAL_DMA_SET_TRIG_SRC( ch, DMATRIG_TX );
// The source address is incremented by 1 byte after each transfer.
HAL_DMA_SET_SRC_INC( ch, HAL_DMA_SRCINC_1 );
// The destination address is constant - the Tx Data Buffer.
HAL_DMA_SET_DST_INC( ch, HAL_DMA_DSTINC_0 );
// The DMA Tx done is serviced by ISR in order to maintain full thruput.
HAL_DMA_SET_IRQ( ch, HAL_DMA_IRQMASK_ENABLE );
// Xfer all 8 bits of a byte xfer.
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS );
// DMA has highest priority for memory access.
HAL_DMA_SET_PRIORITY( ch, HAL_DMA_PRI_HIGH );
// Setup Rx by DMA.
ch = HAL_DMA_GET_DESC1234( HAL_DMA_CH_RX );
// The start address of the source.
HAL_DMA_SET_SOURCE( ch, DMA_UDBUF );
// Using the length field to determine how many bytes to transfer.
HAL_DMA_SET_VLEN( ch, HAL_DMA_VLEN_USE_LEN );
/* The trick is to cfg DMA to xfer 2 bytes for every 1 byte of Rx.
* The byte after the Rx Data Buffer is the Baud Cfg Register,
* which always has a known value. So init Rx buffer to inverse of that
* known value. DMA word xfer will flip the bytes, so every valid Rx byte
* in the Rx buffer will be preceded by a DMA_PAD char equal to the
* Baud Cfg Register value.
*/
HAL_DMA_SET_WORD_SIZE( ch, HAL_DMA_WORDSIZE_WORD );
// The bytes are transferred 1-by-1 on Rx Complete trigger.
HAL_DMA_SET_TRIG_MODE( ch, HAL_DMA_TMODE_SINGLE_REPEATED );
HAL_DMA_SET_TRIG_SRC( ch, DMATRIG_RX );
// The source address is constant - the Rx Data Buffer.
HAL_DMA_SET_SRC_INC( ch, HAL_DMA_SRCINC_0 );
// The destination address is incremented by 1 word after each transfer.
HAL_DMA_SET_DST_INC( ch, HAL_DMA_DSTINC_1 );
HAL_DMA_SET_DEST( ch, dmaCfg.rxBuf );
HAL_DMA_SET_LEN( ch, HAL_UART_DMA_RX_MAX );
// The DMA is to be polled and shall not issue an IRQ upon completion.
HAL_DMA_SET_IRQ( ch, HAL_DMA_IRQMASK_DISABLE );
// Xfer all 8 bits of a byte xfer.
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS );
// DMA has highest priority for memory access.
HAL_DMA_SET_PRIORITY( ch, HAL_DMA_PRI_HIGH );
}
/******************************************************************************
* @fn HalUARTOpenDMA
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param config - contains configuration information
*
* @return none
*****************************************************************************/
static void HalUARTOpenDMA(halUARTCfg_t *config)
{
dmaCfg.uartCB = config->callBackFunc;
// Only supporting subset of baudrate for code size - other is possible.
HAL_UART_ASSERT((config->baudRate == HAL_UART_BR_9600) ||
(config->baudRate == HAL_UART_BR_19200) ||
(config->baudRate == HAL_UART_BR_38400) ||
(config->baudRate == HAL_UART_BR_57600) ||
(config->baudRate == HAL_UART_BR_115200));
if (config->baudRate == HAL_UART_BR_57600 ||
config->baudRate == HAL_UART_BR_115200)
{
UxBAUD = 216;
}
else
{
UxBAUD = 59;
}
switch (config->baudRate)
{
case HAL_UART_BR_9600:
UxGCR = 8;
dmaCfg.txTick = 35; // (32768Hz / (9600bps / 10 bits))
// 10 bits include start and stop bits.
break;
case HAL_UART_BR_19200:
UxGCR = 9;
dmaCfg.txTick = 18;
break;
case HAL_UART_BR_38400:
UxGCR = 10;
dmaCfg.txTick = 9;
break;
case HAL_UART_BR_57600:
UxGCR = 10;
dmaCfg.txTick = 6;
break;
default:
// HAL_UART_BR_115200
UxGCR = 11;
dmaCfg.txTick = 3;
break;
}
// 8 bits/char; no parity; 1 stop bit; stop bit hi.
if (config->flowControl)
{
UxUCR = UCR_FLOW | UCR_STOP;
PxSEL |= HAL_UART_Px_CTS;
// DMA Rx is always on (self-resetting). So flow must be controlled by the S/W polling the Rx
// buffer level. Start by allowing flow.
PxOUT &= ~HAL_UART_Px_RTS;
PxDIR |= HAL_UART_Px_RTS;
// Trigger an interrupt on CTS input (enabled in HalUARTSuspendDMA).
P0IFG &= ~HAL_UART_Px_CTS;
P0IEN &= ~HAL_UART_Px_CTS;
P0IE = 1;
}
else
{
UxUCR = UCR_STOP;
}
dmaCfg.rxBuf[0] = *(volatile uint8 *)DMA_UDBUF; // Clear the DMA Rx trigger.
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_RX);
HAL_DMA_ARM_CH(HAL_DMA_CH_RX);
osal_memset(dmaCfg.rxBuf, (DMA_PAD ^ 0xFF), HAL_UART_DMA_RX_MAX*2);
UxCSR |= CSR_RE;
// Initialize that TX DMA is not pending
dmaCfg.txDMAPending = FALSE;
dmaCfg.txShdwValid = FALSE;
}
/*****************************************************************************
* @fn HalUARTReadDMA
*
* @brief Read a buffer from the UART
*
* @param buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
static uint16 HalUARTReadDMA(uint8 *buf, uint16 len)
{
uint16 cnt;
for (cnt = 0; cnt < len; cnt++)
{
if (!HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
break;
}
*buf++ = HAL_UART_DMA_GET_RX_BYTE(dmaCfg.rxHead);
HAL_UART_DMA_CLR_RX_BYTE(dmaCfg.rxHead);
#if HAL_UART_DMA_RX_MAX == 256
(dmaCfg.rxHead)++;
#else
if (++(dmaCfg.rxHead) >= HAL_UART_DMA_RX_MAX)
{
dmaCfg.rxHead = 0;
}
#endif
}
PxOUT &= ~HAL_UART_Px_RTS; // Re-enable the flow on any read.
return cnt;
}
/******************************************************************************
* @fn HalUARTWriteDMA
*
* @brief Write a buffer to the UART.
*
* @param buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
static uint16 HalUARTWriteDMA(uint8 *buf, uint16 len)
{
uint16 cnt;
halIntState_t his;
uint8 txSel;
txIdx_t txIdx;
// Enforce all or none.
if ((len + dmaCfg.txIdx[dmaCfg.txSel]) > HAL_UART_DMA_TX_MAX)
{
return 0;
}
HAL_ENTER_CRITICAL_SECTION(his);
txSel = dmaCfg.txSel;
txIdx = dmaCfg.txIdx[txSel];
HAL_EXIT_CRITICAL_SECTION(his);
for (cnt = 0; cnt < len; cnt++)
{
dmaCfg.txBuf[txSel][txIdx++] = buf[cnt];
}
HAL_ENTER_CRITICAL_SECTION(his);
if (txSel != dmaCfg.txSel)
{
HAL_EXIT_CRITICAL_SECTION(his);
txSel = dmaCfg.txSel;
txIdx = dmaCfg.txIdx[txSel];
for (cnt = 0; cnt < len; cnt++)
{
dmaCfg.txBuf[txSel][txIdx++] = buf[cnt];
}
HAL_ENTER_CRITICAL_SECTION(his);
}
dmaCfg.txIdx[txSel] = txIdx;
if (dmaCfg.txIdx[(txSel ^ 1)] == 0)
{
// TX DMA is expected to be fired
dmaCfg.txDMAPending = TRUE;
}
HAL_EXIT_CRITICAL_SECTION(his);
return cnt;
}
/******************************************************************************
* @fn HalUARTPollDMA
*
* @brief Poll a USART module implemented by DMA.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTPollDMA(void)
{
uint16 cnt = 0;
uint8 evt = 0;
if (HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
rxIdx_t tail = findTail();
// If the DMA has transferred in more Rx bytes, reset the Rx idle timer.
if (dmaCfg.rxTail != tail)
{
dmaCfg.rxTail = tail;
// Re-sync the shadow on any 1st byte(s) received.
if (dmaCfg.rxTick == 0)
{
dmaCfg.rxShdw = ST0;
}
dmaCfg.rxTick = HAL_UART_DMA_IDLE;
}
else if (dmaCfg.rxTick)
{
// Use the LSB of the sleep timer (ST0 must be read first anyway).
uint8 decr = ST0 - dmaCfg.rxShdw;
if (dmaCfg.rxTick > decr)
{
dmaCfg.rxTick -= decr;
dmaCfg.rxShdw = ST0;
}
else
{
dmaCfg.rxTick = 0;
}
}
cnt = HalUARTRxAvailDMA();
}
else
{
dmaCfg.rxTick = 0;
}
if (cnt >= HAL_UART_DMA_FULL)
{
evt = HAL_UART_RX_FULL;
}
else if (cnt >= HAL_UART_DMA_HIGH)
{
evt = HAL_UART_RX_ABOUT_FULL;
PxOUT |= HAL_UART_Px_RTS; // Disable Rx flow.
}
else if (cnt && !dmaCfg.rxTick)
{
evt = HAL_UART_RX_TIMEOUT;
}
if (dmaCfg.txMT)
{
dmaCfg.txMT = FALSE;
evt |= HAL_UART_TX_EMPTY;
}
if (dmaCfg.txShdwValid)
{
uint8 decr = ST0;
decr -= dmaCfg.txShdw;
if (decr > dmaCfg.txTick)
{
// No protection for txShdwValid is required
// because while the shadow was valid, DMA ISR cannot be triggered
// to cause concurrent access to this variable.
dmaCfg.txShdwValid = FALSE;
}
}
if (dmaCfg.txDMAPending && !dmaCfg.txShdwValid)
{
// UART TX DMA is expected to be fired and enough time has lapsed since last DMA ISR
// to know that DBUF can be overwritten
halDMADesc_t *ch = HAL_DMA_GET_DESC1234(HAL_DMA_CH_TX);
halIntState_t intState;
// Clear the DMA pending flag
dmaCfg.txDMAPending = FALSE;
HAL_DMA_SET_SOURCE(ch, dmaCfg.txBuf[dmaCfg.txSel]);
HAL_DMA_SET_LEN(ch, dmaCfg.txIdx[dmaCfg.txSel]);
dmaCfg.txSel ^= 1;
HAL_ENTER_CRITICAL_SECTION(intState);
HAL_DMA_ARM_CH(HAL_DMA_CH_TX);
do
{
asm("NOP");
} while (!HAL_DMA_CH_ARMED(HAL_DMA_CH_TX));
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_TX);
HAL_DMA_MAN_TRIGGER(HAL_DMA_CH_TX);
HAL_EXIT_CRITICAL_SECTION(intState);
}
else
{
halIntState_t his;
HAL_ENTER_CRITICAL_SECTION(his);
if ((dmaCfg.txIdx[dmaCfg.txSel] != 0) && !HAL_DMA_CH_ARMED(HAL_DMA_CH_TX)
&& !HAL_DMA_CHECK_IRQ(HAL_DMA_CH_TX))
{
HAL_EXIT_CRITICAL_SECTION(his);
HalUARTIsrDMA();
}
else
{
HAL_EXIT_CRITICAL_SECTION(his);
}
}
if (evt && (dmaCfg.uartCB != NULL))
{
dmaCfg.uartCB(HAL_UART_DMA-1, evt);
}
#if defined POWER_SAVING
/* A simple ZAP application sending a unicast at 2-Hz was seen to bog down to < 1-Hz OTA unicast
* when the ZNP was configured to be a ZED (i.e. POWER_SAVING was enabled). So adding this delay
* of only 10 msecs before re-enabling CONSERVE showed that the problem was fixed while still
* allowing the ZNP to enter sleep.
*/
static uint8 znpUartActiveShdw;
// If a ZED and no ongoing Rx/Tx and the UART master is not asserting CTS.
if (ZG_DEVICE_ENDDEVICE_TYPE && !(UxCSR & CSR_ACTIVE) && (PxIN & HAL_UART_Px_CTS))
{
if (znpUartActiveShdw)
{
uint8 rxOnIdle;
(void)ZMacGetReq(ZMacRxOnIdle, &rxOnIdle);
if (!rxOnIdle)
{
znpUartActiveShdw = FALSE;
if (ZSuccess != osal_start_timerEx(znpTaskId, ZNP_PWRMGR_CONSERVE_EVENT,
ZNP_PWRMGR_CONSERVE_DELAY))
{
(void)osal_set_event(znpTaskId, ZNP_PWRMGR_CONSERVE_EVENT);
}
}
}
}
else if (!znpUartActiveShdw)
{
znpUartActiveShdw = TRUE;
(void)osal_stop_timerEx(znpTaskId, ZNP_PWRMGR_CONSERVE_EVENT);
(void)osal_clear_event(znpTaskId, ZNP_PWRMGR_CONSERVE_EVENT);
(void)osal_pwrmgr_task_state(znpTaskId, PWRMGR_HOLD);
}
#endif
}
/**************************************************************************************************
* @fn HalUARTRxAvailDMA()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param none
*
* @return length of current Rx Buffer
**************************************************************************************************/
static uint16 HalUARTRxAvailDMA(void)
{
uint16 cnt = 0;
if (HAL_UART_DMA_NEW_RX_BYTE(dmaCfg.rxHead))
{
uint16 idx;
for (idx = 0; idx < HAL_UART_DMA_RX_MAX; idx++)
{
if (HAL_UART_DMA_NEW_RX_BYTE(idx))
{
cnt++;
}
}
}
return cnt;
}
/******************************************************************************
* @fn HalUARTSuspendDMA
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTSuspendDMA( void )
{
PxOUT |= HAL_UART_Px_RTS; // Disable Rx flow.
UxCSR &= ~CSR_RE;
P0IEN |= HAL_UART_Px_CTS; // Enable the CTS ISR.
}
/******************************************************************************
* @fn HalUARTResumeDMA
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTResumeDMA( void )
{
P0IEN &= ~HAL_UART_Px_CTS; // Disable the CTS ISR.
UxUCR |= UCR_FLUSH;
UxCSR |= CSR_RE;
PxOUT &= ~HAL_UART_Px_RTS; // Re-enable Rx flow.
}
/******************************************************************************
* @fn HalUARTIsrDMA
*
* @brief Handle the Tx done DMA ISR.
*
* @param none
*
* @return none
*****************************************************************************/
void HalUARTIsrDMA(void);
void HalUARTIsrDMA(void)
{
HAL_DMA_CLEAR_IRQ(HAL_DMA_CH_TX);
// Indicate that the other buffer is free now.
dmaCfg.txIdx[(dmaCfg.txSel ^ 1)] = 0;
dmaCfg.txMT = TRUE;
// Set TX shadow
dmaCfg.txShdw = ST0;
dmaCfg.txShdwValid = TRUE;
// If there is more Tx data ready to go, re-start the DMA immediately on it.
if (dmaCfg.txIdx[dmaCfg.txSel])
{
// UART TX DMA is expected to be fired
dmaCfg.txDMAPending = TRUE;
}
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,587 @@
/**************************************************************************************************
Filename: _hal_uart_isr.c
Revised: $Date: 2010-03-10 20:36:55 -0800 (Wed, 10 Mar 2010) $
Revision: $Revision: 21890 $
Description: This file contains the interface to the H/W UART driver by ISR.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_assert.h"
#include "hal_board.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if defined MT_TASK
#include "MT_UART.h"
#endif
/*********************************************************************
* MACROS
*/
//#define HAL_UART_ASSERT(expr) HAL_ASSERT((expr))
#define HAL_UART_ASSERT(expr)
#define HAL_UART_ISR_RX_AVAIL() \
(isrCfg.rxTail >= isrCfg.rxHead) ? \
(isrCfg.rxTail - isrCfg.rxHead) : \
(HAL_UART_ISR_RX_MAX - isrCfg.rxHead + isrCfg.rxTail)
#define HAL_UART_ISR_TX_AVAIL() \
(isrCfg.txHead > isrCfg.txTail) ? \
(isrCfg.txHead - isrCfg.txTail - 1) : \
(HAL_UART_ISR_TX_MAX - isrCfg.txTail + isrCfg.txHead - 1)
/*********************************************************************
* CONSTANTS
*/
// UxCSR - USART Control and Status Register.
#define CSR_MODE 0x80
#define CSR_RE 0x40
#define CSR_SLAVE 0x20
#define CSR_FE 0x10
#define CSR_ERR 0x08
#define CSR_RX_BYTE 0x04
#define CSR_TX_BYTE 0x02
#define CSR_ACTIVE 0x01
// UxUCR - USART UART Control Register.
#define UCR_FLUSH 0x80
#define UCR_FLOW 0x40
#define UCR_D9 0x20
#define UCR_BIT9 0x10
#define UCR_PARITY 0x08
#define UCR_SPB 0x04
#define UCR_STOP 0x02
#define UCR_START 0x01
#define UTX0IE 0x04
#define UTX1IE 0x08
#define P2DIR_PRIPO 0xC0
// Incompatible redefinitions result with more than one UART driver sub-module.
#undef PxOUT
#undef PxDIR
#undef PxSEL
#undef UxCSR
#undef UxUCR
#undef UxDBUF
#undef UxBAUD
#undef UxGCR
#undef URXxIE
#undef URXxIF
#undef UTXxIE
#undef UTXxIF
#undef HAL_UART_PERCFG_BIT
#undef HAL_UART_Px_RTS
#undef HAL_UART_Px_CTS
#undef HAL_UART_Px_RX_TX
#if (HAL_UART_ISR == 1)
#define PxOUT P0
#define PxDIR P0DIR
#define PxSEL P0SEL
#define UxCSR U0CSR
#define UxUCR U0UCR
#define UxDBUF U0DBUF
#define UxBAUD U0BAUD
#define UxGCR U0GCR
#define URXxIE URX0IE
#define URXxIF URX0IF
#define UTXxIE UTX0IE
#define UTXxIF UTX0IF
#else
#define PxOUT P1
#define PxDIR P1DIR
#define PxSEL P1SEL
#define UxCSR U1CSR
#define UxUCR U1UCR
#define UxDBUF U1DBUF
#define UxBAUD U1BAUD
#define UxGCR U1GCR
#define URXxIE URX1IE
#define URXxIF URX1IF
#define UTXxIE UTX1IE
#define UTXxIF UTX1IF
#endif
#if (HAL_UART_ISR == 1)
#define HAL_UART_PERCFG_BIT 0x01 // USART0 on P0, Alt-1; so clear this bit.
#define HAL_UART_Px_RX_TX 0x0C // Peripheral I/O Select for Rx/Tx.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#else
#define HAL_UART_PERCFG_BIT 0x02 // USART1 on P1, Alt-2; so set this bit.
#define HAL_UART_Px_RTS 0x20 // Peripheral I/O Select for RTS.
#define HAL_UART_Px_CTS 0x10 // Peripheral I/O Select for CTS.
#define HAL_UART_Px_RX_TX 0xC0 // Peripheral I/O Select for Rx/Tx.
#endif
// The timeout tick is at 32-kHz, so multiply msecs by 33.
#define HAL_UART_MSECS_TO_TICKS 33
#if defined MT_TASK
#define HAL_UART_ISR_TX_MAX MT_UART_DEFAULT_MAX_TX_BUFF
#define HAL_UART_ISR_RX_MAX MT_UART_DEFAULT_MAX_RX_BUFF
#define HAL_UART_ISR_HIGH MT_UART_DEFAULT_THRESHOLD
#define HAL_UART_ISR_IDLE (MT_UART_DEFAULT_IDLE_TIMEOUT * HAL_UART_MSECS_TO_TICKS)
#else
#if !defined HAL_UART_ISR_RX_MAX
#define HAL_UART_ISR_RX_MAX 128
#endif
#if !defined HAL_UART_ISR_TX_MAX
#define HAL_UART_ISR_TX_MAX HAL_UART_ISR_RX_MAX
#endif
#if !defined HAL_UART_ISR_HIGH
#define HAL_UART_ISR_HIGH (HAL_UART_ISR_RX_MAX / 2 - 16)
#endif
#if !defined HAL_UART_ISR_IDLE
#define HAL_UART_ISR_IDLE (6 * HAL_UART_MSECS_TO_TICKS)
#endif
#endif
/*********************************************************************
* TYPEDEFS
*/
typedef struct
{
uint8 rxBuf[HAL_UART_ISR_RX_MAX];
#if HAL_UART_ISR_RX_MAX < 256
uint8 rxHead;
volatile uint8 rxTail;
#else
uint16 rxHead;
volatile uint16 rxTail;
#endif
uint8 rxTick;
uint8 rxShdw;
uint8 txBuf[HAL_UART_ISR_TX_MAX];
#if HAL_UART_ISR_TX_MAX < 256
volatile uint8 txHead;
uint8 txTail;
#else
volatile uint16 txHead;
uint16 txTail;
#endif
uint8 txMT;
halUARTCBack_t uartCB;
} uartISRCfg_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
static uartISRCfg_t isrCfg;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void HalUARTInitISR(void);
static void HalUARTOpenISR(halUARTCfg_t *config);
uint16 HalUARTReadISR(uint8 *buf, uint16 len);
uint16 HalUARTWriteISR(uint8 *buf, uint16 len);
static void HalUARTPollISR(void);
static uint16 HalUARTRxAvailISR(void);
static void HalUARTSuspendISR(void);
static void HalUARTResumeISR(void);
/******************************************************************************
* @fn HalUARTInitISR
*
* @brief Initialize the UART
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTInitISR(void)
{
// Set P2 priority - USART0 over USART1 if both are defined.
P2DIR &= ~P2DIR_PRIPO;
P2DIR |= HAL_UART_PRIPO;
#if (HAL_UART_ISR == 1)
PERCFG &= ~HAL_UART_PERCFG_BIT; // Set UART0 I/O location to P0.
#else
PERCFG |= HAL_UART_PERCFG_BIT; // Set UART1 I/O location to P1.
#endif
PxSEL |= HAL_UART_Px_RX_TX; // Enable Tx and Rx on P1.
ADCCFG &= ~HAL_UART_Px_RX_TX; // Make sure ADC doesnt use this.
UxCSR = CSR_MODE; // Mode is UART Mode.
UxUCR = UCR_FLUSH; // Flush it.
}
/******************************************************************************
* @fn HalUARTUnInitISR
*
* @brief UnInitialize the UART.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTUnInitISR(void)
{
UxCSR = 0;
URXxIE = 0;
URXxIF = 0;
IEN2 &= ~UTXxIE;
UTXxIF = 0;
}
/******************************************************************************
* @fn HalUARTOpenISR
*
* @brief Open a port according tp the configuration specified by parameter.
*
* @param config - contains configuration information
*
* @return none
*****************************************************************************/
static void HalUARTOpenISR(halUARTCfg_t *config)
{
isrCfg.uartCB = config->callBackFunc;
// Only supporting subset of baudrate for code size - other is possible.
HAL_UART_ASSERT((config->baudRate == HAL_UART_BR_9600) ||
(config->baudRate == HAL_UART_BR_19200) ||
(config->baudRate == HAL_UART_BR_38400) ||
(config->baudRate == HAL_UART_BR_57600) ||
(config->baudRate == HAL_UART_BR_115200));
if (config->baudRate == HAL_UART_BR_57600 ||
config->baudRate == HAL_UART_BR_115200)
{
UxBAUD = 216;
}
else
{
UxBAUD = 59;
}
switch (config->baudRate)
{
case HAL_UART_BR_9600:
UxGCR = 8;
break;
case HAL_UART_BR_19200:
UxGCR = 9;
break;
case HAL_UART_BR_38400:
case HAL_UART_BR_57600:
UxGCR = 10;
break;
default:
UxGCR = 11;
break;
}
// 8 bits/char; no parity; 1 stop bit; stop bit hi.
if (config->flowControl)
{
UxUCR = UCR_FLOW | UCR_STOP;
PxSEL |= HAL_UART_Px_RTS | HAL_UART_Px_CTS;
}
else
{
UxUCR = UCR_STOP;
}
UxCSR |= CSR_RE;
URXxIE = 1;
UTXxIF = 1; // Prime the ISR pump.
}
/*****************************************************************************
* @fn HalUARTReadISR
*
* @brief Read a buffer from the UART
*
* @param buf - valid data buffer at least 'len' bytes in size
* len - max length number of bytes to copy to 'buf'
*
* @return length of buffer that was read
*****************************************************************************/
uint16 HalUARTReadISR(uint8 *buf, uint16 len)
{
uint16 cnt = 0;
while ((isrCfg.rxHead != isrCfg.rxTail) && (cnt < len))
{
*buf++ = isrCfg.rxBuf[isrCfg.rxHead++];
if (isrCfg.rxHead >= HAL_UART_ISR_RX_MAX)
{
isrCfg.rxHead = 0;
}
cnt++;
}
return cnt;
}
/******************************************************************************
* @fn HalUARTWriteISR
*
* @brief Write a buffer to the UART.
*
* @param buf - pointer to the buffer that will be written, not freed
* len - length of
*
* @return length of the buffer that was sent
*****************************************************************************/
uint16 HalUARTWriteISR(uint8 *buf, uint16 len)
{
uint16 cnt;
// Enforce all or none.
if (HAL_UART_ISR_TX_AVAIL() < len)
{
return 0;
}
for (cnt = 0; cnt < len; cnt++)
{
isrCfg.txBuf[isrCfg.txTail] = *buf++;
isrCfg.txMT = 0;
if (isrCfg.txTail >= HAL_UART_ISR_TX_MAX-1)
{
isrCfg.txTail = 0;
}
else
{
isrCfg.txTail++;
}
// Keep re-enabling ISR as it might be keeping up with this loop due to other ints.
IEN2 |= UTXxIE;
}
return cnt;
}
/******************************************************************************
* @fn HalUARTPollISR
*
* @brief Poll a USART module implemented by ISR.
*
* @param none
*
* @return none
*****************************************************************************/
static void HalUARTPollISR(void)
{
if (isrCfg.uartCB != NULL)
{
uint16 cnt = HAL_UART_ISR_RX_AVAIL();
uint8 evt = 0;
if (isrCfg.rxTick)
{
// Use the LSB of the sleep timer (ST0 must be read first anyway).
uint8 decr = ST0 - isrCfg.rxShdw;
if (isrCfg.rxTick > decr)
{
isrCfg.rxTick -= decr;
}
else
{
isrCfg.rxTick = 0;
}
}
isrCfg.rxShdw = ST0;
if (cnt >= HAL_UART_ISR_RX_MAX-1)
{
evt = HAL_UART_RX_FULL;
}
else if (cnt >= HAL_UART_ISR_HIGH)
{
evt = HAL_UART_RX_ABOUT_FULL;
}
else if (cnt && !isrCfg.rxTick)
{
evt = HAL_UART_RX_TIMEOUT;
}
if (isrCfg.txMT)
{
isrCfg.txMT = 0;
evt |= HAL_UART_TX_EMPTY;
}
if (evt)
{
isrCfg.uartCB(HAL_UART_ISR-1, evt);
}
}
}
/**************************************************************************************************
* @fn HalUARTRxAvailISR()
*
* @brief Calculate Rx Buffer length - the number of bytes in the buffer.
*
* @param none
*
* @return length of current Rx Buffer
**************************************************************************************************/
static uint16 HalUARTRxAvailISR(void)
{
return HAL_UART_ISR_RX_AVAIL();
}
/******************************************************************************
* @fn HalUARTSuspendISR
*
* @brief Suspend UART hardware before entering PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTSuspendISR( void )
{
UxCSR &= ~CSR_RE;
}
/******************************************************************************
* @fn HalUARTResumeISR
*
* @brief Resume UART hardware after exiting PM mode 1, 2 or 3.
*
* @param None
*
* @return None
*****************************************************************************/
static void HalUARTResumeISR( void )
{
UxUCR |= UCR_FLUSH;
UxCSR |= CSR_RE;
}
/***************************************************************************************************
* @fn halUartRxIsr
*
* @brief UART Receive Interrupt
*
* @param None
*
* @return None
***************************************************************************************************/
#if defined HAL_SB_BOOT_CODE
static void halUartRxIsr(void);
static void halUartRxIsr(void)
#else
#if (HAL_UART_ISR == 1)
HAL_ISR_FUNCTION( halUart0RxIsr, URX0_VECTOR )
#else
HAL_ISR_FUNCTION( halUart1RxIsr, URX1_VECTOR )
#endif
#endif
{
uint8 tmp = UxDBUF;
isrCfg.rxBuf[isrCfg.rxTail] = tmp;
// Re-sync the shadow on any 1st byte received.
if (isrCfg.rxHead == isrCfg.rxTail)
{
isrCfg.rxShdw = ST0;
}
if (++isrCfg.rxTail >= HAL_UART_ISR_RX_MAX)
{
isrCfg.rxTail = 0;
}
isrCfg.rxTick = HAL_UART_ISR_IDLE;
}
/***************************************************************************************************
* @fn halUartTxIsr
*
* @brief UART Transmit Interrupt
*
* @param None
*
* @return None
***************************************************************************************************/
#if defined HAL_SB_BOOT_CODE
static void halUartTxIsr(void);
static void halUartTxIsr(void)
#else
#if (HAL_UART_ISR == 1)
HAL_ISR_FUNCTION( halUart0TxIsr, UTX0_VECTOR )
#else
HAL_ISR_FUNCTION( halUart1TxIsr, UTX1_VECTOR )
#endif
#endif
{
if (isrCfg.txHead == isrCfg.txTail)
{
IEN2 &= ~UTXxIE;
isrCfg.txMT = 1;
}
else
{
UTXxIF = 0;
UxDBUF = isrCfg.txBuf[isrCfg.txHead++];
if (isrCfg.txHead >= HAL_UART_ISR_TX_MAX)
{
isrCfg.txHead = 0;
}
}
}
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,240 @@
/**************************************************************************************************
Filename: hal_adc.c
Revised: $Date: 2010-03-12 16:10:36 -0800 (Fri, 12 Mar 2010) $
Revision: $Revision: 21910 $
Description: This file contains the interface to the HAL ADC.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_adc.h"
#include "hal_defs.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_ADC_EOC 0x80 /* End of Conversion bit */
#define HAL_ADC_START 0x40 /* Starts Conversion */
#define HAL_ADC_STSEL_EXT 0x00 /* External Trigger */
#define HAL_ADC_STSEL_FULL 0x10 /* Full Speed, No Trigger */
#define HAL_ADC_STSEL_T1C0 0x20 /* Timer1, Channel 0 Compare Event Trigger */
#define HAL_ADC_STSEL_ST 0x30 /* ADCCON1.ST =1 Trigger */
#define HAL_ADC_RAND_NORM 0x00 /* Normal Operation */
#define HAL_ADC_RAND_LFSR 0x04 /* Clock LFSR */
#define HAL_ADC_RAND_SEED 0x08 /* Seed Modulator */
#define HAL_ADC_RAND_STOP 0x0c /* Stop Random Generator */
#define HAL_ADC_RAND_BITS 0x0c /* Bits [3:2] */
#define HAL_ADC_DEC_064 0x00 /* Decimate by 64 : 8-bit resolution */
#define HAL_ADC_DEC_128 0x10 /* Decimate by 128 : 10-bit resolution */
#define HAL_ADC_DEC_256 0x20 /* Decimate by 256 : 12-bit resolution */
#define HAL_ADC_DEC_512 0x30 /* Decimate by 512 : 14-bit resolution */
#define HAL_ADC_DEC_BITS 0x30 /* Bits [5:4] */
#define HAL_ADC_STSEL HAL_ADC_STSEL_ST
#define HAL_ADC_RAND_GEN HAL_ADC_RAND_STOP
#define HAL_ADC_REF_VOLT HAL_ADC_REF_AVDD
#define HAL_ADC_DEC_RATE HAL_ADC_DEC_064
#define HAL_ADC_SCHN HAL_ADC_CHN_VDD3
#define HAL_ADC_ECHN HAL_ADC_CHN_GND
/* ------------------------------------------------------------------------------------------------
* Local Variables
* ------------------------------------------------------------------------------------------------
*/
#if (HAL_ADC == TRUE)
static uint8 adcRef;
#endif
/**************************************************************************************************
* @fn HalAdcInit
*
* @brief Initialize ADC Service
*
* @param None
*
* @return None
**************************************************************************************************/
void HalAdcInit (void)
{
#if (HAL_ADC == TRUE)
adcRef = HAL_ADC_REF_VOLT;
#endif
}
/**************************************************************************************************
* @fn HalAdcRead
*
* @brief Read the ADC based on given channel and resolution
*
* @param channel - channel where ADC will be read
* @param resolution - the resolution of the value
*
* @return 16 bit value of the ADC in offset binary format.
*
* Note that the ADC is "bipolar", which means the GND (0V) level is mid-scale.
* Note2: This function assumes that ADCCON3 contains the voltage reference.
**************************************************************************************************/
uint16 HalAdcRead (uint8 channel, uint8 resolution)
{
int16 reading = 0;
#if (HAL_ADC == TRUE)
uint8 i, resbits;
uint8 adcChannel = 1;
/*
* If Analog input channel is AIN0..AIN7, make sure corresponing P0 I/O pin is enabled. The code
* does NOT disable the pin at the end of this function. I think it is better to leave the pin
* enabled because the results will be more accurate. Because of the inherent capacitance on the
* pin, it takes time for the voltage on the pin to charge up to its steady-state level. If
* HalAdcRead() has to turn on the pin for every conversion, the results may show a lower voltage
* than actuality because the pin did not have time to fully charge.
*/
if (channel < 8)
{
for (i=0; i < channel; i++)
{
adcChannel <<= 1;
}
}
/* Enable channel */
ADCCFG |= adcChannel;
/* Convert resolution to decimation rate */
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
resbits = HAL_ADC_DEC_064;
break;
case HAL_ADC_RESOLUTION_10:
resbits = HAL_ADC_DEC_128;
break;
case HAL_ADC_RESOLUTION_12:
resbits = HAL_ADC_DEC_256;
break;
case HAL_ADC_RESOLUTION_14:
default:
resbits = HAL_ADC_DEC_512;
break;
}
/* writing to this register starts the extra conversion */
ADCCON3 = channel | resbits | adcRef;
/* Wait for the conversion to be done */
while (!(ADCCON1 & HAL_ADC_EOC));
/* Disable channel after done conversion */
ADCCFG &= (adcChannel ^ 0xFF);
/* Read the result */
reading = (int16) (ADCL);
reading |= (int16) (ADCH << 8);
/* Treat small negative as 0 */
if (reading < 0)
reading = 0;
switch (resolution)
{
case HAL_ADC_RESOLUTION_8:
reading >>= 8;
break;
case HAL_ADC_RESOLUTION_10:
reading >>= 6;
break;
case HAL_ADC_RESOLUTION_12:
reading >>= 4;
break;
case HAL_ADC_RESOLUTION_14:
default:
reading >>= 2;
break;
}
#else
// unused arguments
(void) channel;
(void) resolution;
#endif
return ((uint16)reading);
}
/**************************************************************************************************
* @fn HalAdcSetReference
*
* @brief Sets the reference voltage for the ADC and initializes the service
*
* @param reference - the reference voltage to be used by the ADC
*
* @return none
*
**************************************************************************************************/
void HalAdcSetReference ( uint8 reference )
{
#if (HAL_ADC == TRUE)
adcRef = reference;
#endif
}
/*********************************************************************
* @fn HalAdcCheckVdd
*
* @brief Check for minimum Vdd specified.
*
* @param vdd - The board-specific Vdd reading to check for.
*
* @return TRUE if the Vdd measured is greater than the 'vdd' minimum parameter;
* FALSE if not.
*
*********************************************************************/
bool HalAdcCheckVdd(uint8 vdd)
{
ADCCON3 = 0x0F;
while (!(ADCCON1 & 0x80));
return (ADCH > vdd);
}
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,124 @@
/**************************************************************************************************
Filename: hal_aes.h
Revised: $Date: 2010-01-11 14:10:07 -0800 (Mon, 11 Jan 2010) $
Revision: $Revision: 21476 $
Description: Support for HW/SW AES encryption.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_AES_H_
#define HAL_AES_H_
#include "ZComDef.h"
#define STATE_BLENGTH 16 // Number of bytes in State
#define KEY_BLENGTH 16 // Number of bytes in Key
#define KEY_EXP_LENGTH 176 // Nb * (Nr+1) * 4
/* AES Engine is default to hardware AES. To turn on software AES, #define one of the followings:
* #define SOFTWARE_AES TRUE, uses software aes ( slowest setting )
* #define SW_AES_AND_KEY_EXP TRUE, enables software aes with key expansion ( improves speed at the cost of 176 bytes of data (RAM) )
*/
#if ((defined SOFTWARE_AES) && (SOFTWARE_AES == TRUE)) && ((defined SW_AES_AND_KEY_EXP) && (SW_AES_AND_KEY_EXP == TRUE))
#error "SOFTWARE_AES and SW_AES_AND_KEY_EXP cannot be both defined."
#endif
extern void HalAesInit( void );
extern void AesLoadBlock( uint8 * );
extern void AesStartBlock( uint8 *, uint8 * );
extern void AesStartShortBlock( uint8 *, uint8 * );
extern void AesLoadIV(uint8 *);
extern void AesDmaSetup( uint8 *, uint16, uint8 *, uint16 );
extern void AesLoadKey( uint8 * );
extern void (*pSspAesEncrypt)( uint8 *, uint8 * );
extern void ssp_HW_KeyInit (uint8 *);
extern void sspKeyExpansion (uint8 *, uint8 *);
extern void sspAesEncryptHW (uint8 *, uint8 *);
extern void sspAesEncryptKeyExp (uint8 *, uint8 *);
extern void sspAesEncryptBasic (uint8 *, uint8 *);
extern void sspAesEncrypt( uint8 *key, uint8 *buf );
#define AES_BUSY 0x08
#define ENCRYPT 0x00
#define DECRYPT 0x01
// Macro for setting the mode of the AES operation
#define AES_SETMODE(mode) do { ENCCS &= ~0x70; ENCCS |= mode; } while (0)
// _mode_ is one of
#define CBC 0x00
#define CFB 0x10
#define OFB 0x20
#define CTR 0x30
#define ECB 0x40
#define CBC_MAC 0x50
// Macro for starting or stopping encryption or decryption
#define AES_SET_ENCR_DECR_KEY_IV(mode) \
do { \
ENCCS = (ENCCS & ~0x07) | mode \
} while(0)
// Where _mode_ is one of
#define AES_ENCRYPT 0x00;
#define AES_DECRYPT 0x02;
#define AES_LOAD_KEY 0x04;
#define AES_LOAD_IV 0x06;
// Macro for starting the AES module for either encryption, decryption,
// key or initialisation vector loading.
#define AES_START() ENCCS |= 0x01
/* Used by DMA macros to shift 1 to create a mask for DMA registers. */
#define HAL_DMA_AES_IN 1
#define HAL_DMA_AES_OUT 2
/* AES registers */
#define HAL_AES_IN_ADDR 0x70B1
#define HAL_AES_OUT_ADDR 0x70B2
#if !defined (HAL_AES_DMA) || (HAL_AES_DMA == FALSE)
#define HAL_AES_DELAY() \
do { \
uint8 delay = 15; \
while(delay--); \
} while(0)
#endif
// End of CC2530 hardware AES engine definitions
#endif // HAL_AES_H_

View File

@@ -0,0 +1,573 @@
/**************************************************************************************************
Filename: hal_board_cfg.h
Revised: $Date: 2010-07-28 18:42:54 -0700 (Wed, 28 Jul 2010) $
Revision: $Revision: 23203 $
Description: Declarations for the CC2530EM used as a ZNP replacement for the CC2520 on
MSP platforms (and possibly others.)
Copyright 2009-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_BOARD_CFG_H
#define HAL_BOARD_CFG_H
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
/* ------------------------------------------------------------------------------------------------
* CC2590/CC2591 support
*
* Define HAL_PA_LNA_CC2590 if CC2530+CC2590EM is used
* Define HAL_PA_LNA if CC2530+CC2591EM is used
* Note that only one of them can be defined
* ------------------------------------------------------------------------------------------------
*/
#define xHAL_PA_LNA
#define xHAL_PA_LNA_CC2590
/* ------------------------------------------------------------------------------------------------
* Board Indentifier
*
* Define the Board Identifier to HAL_BOARD_CC2530EB_REV13 for SmartRF05 EB 1.3 board
* ------------------------------------------------------------------------------------------------
*/
#if !defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_BOARD_CC2530EB_REV13)
#define HAL_BOARD_CC2530EB_REV17
#endif
/* ------------------------------------------------------------------------------------------------
* Clock Speed
* ------------------------------------------------------------------------------------------------
*/
#define HAL_CPU_CLOCK_MHZ 32
/* This flag should be defined if the SoC uses the 32MHz crystal
* as the main clock source (instead of DCO).
*/
#define HAL_CLOCK_CRYSTAL
// Values based on powerup h/w config as input with pull-up - not using dynamic cfg of transport.
#define ZNP_CFG0_32K_XTAL 1 /* 32kHz crystal installed and used */
#define ZNP_CFG0_32K_OSC 0 /* 32kHz crystal not installed; internal osc. used */
#define ZNP_CFG1_SPI 1 /* use SPI transport */
#define ZNP_CFG1_UART 0 /* use UART transport */
extern unsigned char znpCfg1;
extern unsigned char znpCfg0;
/* ------------------------------------------------------------------------------------------------
* LED Configuration
* ------------------------------------------------------------------------------------------------
*/
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_NUM_LEDS 3
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_NUM_LEDS 1
#else
#error Unknown Board Indentifier
#endif
#define HAL_LED_BLINK_DELAY() st( { volatile uint32 i; for (i=0; i<0x5800; i++) { }; } )
/* 1 - Green */
#define LED1_BV BV(0)
#define LED1_SBIT P1_0
#define LED1_DDR P1DIR
#define LED1_POLARITY ACTIVE_HIGH
#if defined (HAL_BOARD_CC2530EB_REV17)
/* 2 - Red */
#define LED2_BV BV(1)
#define LED2_SBIT P1_1
#define LED2_DDR P1DIR
#define LED2_POLARITY ACTIVE_HIGH
/* 3 - Yellow */
#define LED3_BV BV(4)
#define LED3_SBIT P1_4
#define LED3_DDR P1DIR
#define LED3_POLARITY ACTIVE_HIGH
#endif
/* ------------------------------------------------------------------------------------------------
* GPIO Configuration
* ------------------------------------------------------------------------------------------------
*/
#ifndef HAL_GPIO
#define HAL_GPIO TRUE
#endif
#if defined CC2530_MK
#define GPIO_0_PORT 0
#define GPIO_0_PIN 6
#define GPIO_1_PORT 0
#define GPIO_1_PIN 7
#define GPIO_2_PORT 1
#define GPIO_2_PIN 6
#define GPIO_3_PORT 1
#define GPIO_3_PIN 7
#else
#define GPIO_0_PORT 0
#define GPIO_0_PIN 0
#define GPIO_1_PORT 0
#define GPIO_1_PIN 1
#define GPIO_2_PORT 0
#define GPIO_2_PIN 6
#define GPIO_3_PORT 1
#define GPIO_3_PIN 0
#endif
#define GPIO_DIR_IN(IDX) MCU_IO_DIR_INPUT(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_DIR_OUT(IDX) MCU_IO_DIR_OUTPUT(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_TRI(IDX) MCU_IO_INPUT(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN, MCU_IO_TRISTATE)
#define GPIO_PULL_UP(IDX) MCU_IO_INPUT(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN, MCU_IO_PULLUP)
#define GPIO_PULL_DN(IDX) MCU_IO_INPUT(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN, MCU_IO_PULLDOWN)
#define GPIO_SET(IDX) MCU_IO_SET_HIGH(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_CLR(IDX) MCU_IO_SET_LOW(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_TOG(IDX) MCU_IO_TGL(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_GET(IDX) MCU_IO_GET(GPIO_##IDX##_PORT, GPIO_##IDX##_PIN)
#define GPIO_HiD_SET() (PICTL |= BV(7)) /* PADSC */
#define GPIO_HiD_CLR() (PICTL &= ~BV(7)) /* PADSC */
// Used as "func" for the macros below
#define MCU_IO_TRISTATE 1
#define MCU_IO_PULLUP 2
#define MCU_IO_PULLDOWN 3
//-----------------------------------------------------------------------------
// Macros for simple configuration of IO pins on TI LPW SoCs
//-----------------------------------------------------------------------------
#define MCU_IO_PERIPHERAL(port, pin) MCU_IO_PERIPHERAL_PREP(port, pin)
#define MCU_IO_INPUT(port, pin, func) MCU_IO_INPUT_PREP(port, pin, func)
#define MCU_IO_OUTPUT(port, pin, val) MCU_IO_OUTPUT_PREP(port, pin, val)
#define MCU_IO_SET(port, pin, val) MCU_IO_SET_PREP(port, pin, val)
#define MCU_IO_SET_HIGH(port, pin) MCU_IO_SET_HIGH_PREP(port, pin)
#define MCU_IO_SET_LOW(port, pin) MCU_IO_SET_LOW_PREP(port, pin)
#define MCU_IO_TGL(port, pin) MCU_IO_TGL_PREP(port, pin)
#define MCU_IO_GET(port, pin) MCU_IO_GET_PREP(port, pin)
#define MCU_IO_DIR_INPUT(port, pin) MCU_IO_DIR_INPUT_PREP(port, pin)
#define MCU_IO_DIR_OUTPUT(port, pin) MCU_IO_DIR_OUTPUT_PREP(port, pin)
//----------------------------------------------------------------------------------
// Macros for internal use (the macros above need a new round in the preprocessor)
//----------------------------------------------------------------------------------
#define MCU_IO_PERIPHERAL_PREP(port, pin) st( P##port##SEL |= BV(pin); )
#define MCU_IO_INPUT_PREP(port, pin, func) st( P##port##SEL &= ~BV(pin); \
P##port##DIR &= ~BV(pin); \
switch (func) { \
case MCU_IO_PULLUP: \
P##port##INP &= ~BV(pin); \
P2INP &= ~BV(port + 5); \
break; \
case MCU_IO_PULLDOWN: \
P##port##INP &= ~BV(pin); \
P2INP |= BV(port + 5); \
break; \
default: \
P##port##INP |= BV(pin); \
break; } )
#define MCU_IO_OUTPUT_PREP(port, pin, val) st( P##port##SEL &= ~BV(pin); \
P##port##_##pin## = val; \
P##port##DIR |= BV(pin); )
#define MCU_IO_SET_HIGH_PREP(port, pin) st( P##port##_##pin## = 1; )
#define MCU_IO_SET_LOW_PREP(port, pin) st( P##port##_##pin## = 0; )
#define MCU_IO_SET_PREP(port, pin, val) st( P##port##_##pin## = val; )
#define MCU_IO_TGL_PREP(port, pin) st( P##port##_##pin## ^= 1; )
#define MCU_IO_GET_PREP(port, pin) (P##port## & BV(pin))
#define MCU_IO_DIR_INPUT_PREP(port, pin) st( P##port##DIR &= ~BV(pin); )
#define MCU_IO_DIR_OUTPUT_PREP(port, pin) st( P##port##DIR |= BV(pin); )
/* ------------------------------------------------------------------------------------------------
* Push Button Configuration
* ------------------------------------------------------------------------------------------------
*/
#define ACTIVE_LOW !
#define ACTIVE_HIGH !! /* double negation forces result to be '1' */
/* S1 */
#define PUSH1_BV BV(1)
#define PUSH1_SBIT P0_1
#if defined (HAL_BOARD_CC2530EB_REV17)
#define PUSH1_POLARITY ACTIVE_HIGH
#elif defined (HAL_BOARD_CC2530EB_REV13)
#define PUSH1_POLARITY ACTIVE_LOW
#else
#error Unknown Board Indentifier
#endif
/* Joystick Center Press */
#define PUSH2_BV BV(0)
#define PUSH2_SBIT P2_0
#define PUSH2_POLARITY ACTIVE_HIGH
/* ------------------------------------------------------------------------------------------------
* OSAL NV implemented by internal flash pages.
* ------------------------------------------------------------------------------------------------
*/
// Flash is partitioned into 8 banks of 32 KB or 16 pages.
#define HAL_FLASH_PAGE_PER_BANK 16
// Flash is constructed of 128 pages of 2 KB.
#define HAL_FLASH_PAGE_SIZE 2048
#define HAL_FLASH_WORD_SIZE 4
// CODE banks get mapped into the XDATA range 8000-FFFF.
#define HAL_FLASH_PAGE_MAP 0x8000
// The last 16 bytes of the last available page are reserved for flash lock bits.
// NV page definitions must coincide with segment declaration in project *.xcl file.
#if defined NON_BANKED
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 30
#define HAL_NV_PAGE_CNT 2
#else
#define HAL_FLASH_LOCK_BITS 16
#define HAL_NV_PAGE_END 126
#define HAL_NV_PAGE_CNT 6
#endif
// Re-defining Z_EXTADDR_LEN here so as not to include a Z-Stack .h file.
#define HAL_FLASH_IEEE_SIZE 8
#define HAL_FLASH_IEEE_PAGE (HAL_NV_PAGE_END+1)
#define HAL_FLASH_IEEE_OSET (HAL_FLASH_PAGE_SIZE - HAL_FLASH_LOCK_BITS - HAL_FLASH_IEEE_SIZE)
#define HAL_INFOP_IEEE_OSET 0xC
#define HAL_FLASH_DEV_PRIVATE_KEY_OSET 0x7D2
#define HAL_FLASH_CA_PUBLIC_KEY_OSET 0x7BC
#define HAL_FLASH_IMPLICIT_CERT_OSET 0x78C
#define HAL_NV_PAGE_BEG (HAL_NV_PAGE_END-HAL_NV_PAGE_CNT+1)
// Used by DMA macros to shift 1 to create a mask for DMA registers.
#define HAL_NV_DMA_CH 0
#define HAL_DMA_CH_RX 3
#define HAL_DMA_CH_TX 4
#define HAL_NV_DMA_GET_DESC() HAL_DMA_GET_DESC0()
#define HAL_NV_DMA_SET_ADDR(a) HAL_DMA_SET_ADDR_DESC0((a))
/* ------------------------------------------------------------------------------------------------
* Serial Boot Loader: reserving the first 4 pages of flash and other memory in cc2530-sb.xcl.
* ------------------------------------------------------------------------------------------------
*/
#define HAL_SB_IMG_ADDR 0x2000
#define HAL_SB_CRC_ADDR 0x2090
// Size of internal flash less 4 pages for boot loader, 6 pages for NV, & 1 page for lock bits.
#define HAL_SB_IMG_SIZE (0x40000 - 0x2000 - 0x3000 - 0x0800)
/* ------------------------------------------------------------------------------------------------
* Macros
* ------------------------------------------------------------------------------------------------
*/
/* ----------- RF-frontend Connection Initialization ---------- */
#if defined HAL_PA_LNA || defined HAL_PA_LNA_CC2590
extern void MAC_RfFrontendSetup(void);
#define HAL_BOARD_RF_FRONTEND_SETUP() MAC_RfFrontendSetup()
#else
#define HAL_BOARD_RF_FRONTEND_SETUP()
#endif
/* ----------- Cache Prefetch control ---------- */
#define PREFETCH_ENABLE() st( FCTL = 0x08; )
#define PREFETCH_DISABLE() st( FCTL = 0x04; )
/* Default powerup with P1_2 as input with pullup. P1_2 is read into znpCfg0 is in "init_board()".
* 1->0x00 external 32 kHz xosc & 0->0x80 for internal.
*/
#define HAL_CLOCK_STABLE() st( uint8 OSC_32KHZ = ((znpCfg0 == ZNP_CFG0_32K_XTAL) ? 0x00 : 0x80); \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); )
#if defined CC2530_MK
#define OSC_32KHZ_VALUE 0x80
#else
/* Default powerup with P1_2 as input with pullup, so 1->0x00 external 32 kHz xosc & 0->0x80 for internal */\
#define OSC_32KHZ_VALUE ((P1_2 == ZNP_CFG0_32K_XTAL) ? 0x00 : 0x80)
#endif
/* ----------- Board Initialization ---------- */
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_BOARD_INIT() st \
( \
uint8 OSC_32KHZ = OSC_32KHZ_VALUE; \
uint16 i; \
\
SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \
while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \
asm("NOP"); /* chip bug workaround */ \
for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \
CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \
SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \
\
/* Turn on cache prefetch mode */ \
PREFETCH_ENABLE(); \
)
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_BOARD_INIT() st \
( \
uint8 OSC_32KHZ = OSC_32KHZ_VALUE; \
uint16 i; \
\
SLEEPCMD &= ~OSC_PD; /* turn on 16MHz RC and 32MHz XOSC */ \
while (!(SLEEPSTA & XOSC_STB)); /* wait for 32MHz XOSC stable */ \
asm("NOP"); /* chip bug workaround */ \
for (i=0; i<504; i++) asm("NOP"); /* Require 63us delay for all revs */ \
CLKCONCMD = (CLKCONCMD_32MHZ | OSC_32KHZ); /* Select 32MHz XOSC and the source for 32K clock */ \
while (CLKCONSTA != (CLKCONCMD_32MHZ | OSC_32KHZ)); /* Wait for the change to be effective */ \
SLEEPCMD |= OSC_PD; /* turn off 16MHz RC */ \
\
/* Turn on cache prefetch mode */ \
PREFETCH_ENABLE(); \
\
/* set direction for GPIO outputs */ \
LED1_DDR |= LED1_BV; \
\
/* Set PA/LNA HGM control P0_7 */ \
P0DIR |= BV(7); \
\
/* configure tristates */ \
P0INP |= PUSH2_BV; \
\
/* setup RF frontend if necessary */ \
HAL_BOARD_RF_FRONTEND_SETUP(); \
)
#endif
/* ----------- Debounce ---------- */
#define HAL_DEBOUNCE(expr) { int i; for (i=0; i<500; i++) { if (!(expr)) i = 0; } }
/* ----------- Push Buttons ---------- */
#define HAL_PUSH_BUTTON1() (PUSH1_POLARITY (PUSH1_SBIT))
#define HAL_PUSH_BUTTON2() (PUSH2_POLARITY (PUSH2_SBIT))
#define HAL_PUSH_BUTTON3() (0)
#define HAL_PUSH_BUTTON4() (0)
#define HAL_PUSH_BUTTON5() (0)
#define HAL_PUSH_BUTTON6() (0)
/* ----------- LED's ---------- */
#if defined (HAL_BOARD_CC2530EB_REV17) && !defined (HAL_PA_LNA) && !defined (HAL_PA_LNA_CC2590)
#define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); )
#define HAL_TURN_OFF_LED2() st( LED2_SBIT = LED2_POLARITY (0); )
#define HAL_TURN_OFF_LED3() st( LED3_SBIT = LED3_POLARITY (0); )
#define HAL_TURN_OFF_LED4() HAL_TURN_OFF_LED1()
#define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); )
#define HAL_TURN_ON_LED2() st( LED2_SBIT = LED2_POLARITY (1); )
#define HAL_TURN_ON_LED3() st( LED3_SBIT = LED3_POLARITY (1); )
#define HAL_TURN_ON_LED4() HAL_TURN_ON_LED1()
#define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} )
#define HAL_TOGGLE_LED2() st( if (LED2_SBIT) { LED2_SBIT = 0; } else { LED2_SBIT = 1;} )
#define HAL_TOGGLE_LED3() st( if (LED3_SBIT) { LED3_SBIT = 0; } else { LED3_SBIT = 1;} )
#define HAL_TOGGLE_LED4() HAL_TOGGLE_LED1()
#define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT))
#define HAL_STATE_LED2() (LED2_POLARITY (LED2_SBIT))
#define HAL_STATE_LED3() (LED3_POLARITY (LED3_SBIT))
#define HAL_STATE_LED4() HAL_STATE_LED1()
#elif defined (HAL_BOARD_CC2530EB_REV13) || defined (HAL_PA_LNA) || defined (HAL_PA_LNA_CC2590)
#define HAL_TURN_OFF_LED1() st( LED1_SBIT = LED1_POLARITY (0); )
#define HAL_TURN_OFF_LED2() HAL_TURN_OFF_LED1()
#define HAL_TURN_OFF_LED3() HAL_TURN_OFF_LED1()
#define HAL_TURN_OFF_LED4() HAL_TURN_OFF_LED1()
#define HAL_TURN_ON_LED1() st( LED1_SBIT = LED1_POLARITY (1); )
#define HAL_TURN_ON_LED2() HAL_TURN_ON_LED1()
#define HAL_TURN_ON_LED3() HAL_TURN_ON_LED1()
#define HAL_TURN_ON_LED4() HAL_TURN_ON_LED1()
#define HAL_TOGGLE_LED1() st( if (LED1_SBIT) { LED1_SBIT = 0; } else { LED1_SBIT = 1;} )
#define HAL_TOGGLE_LED2() HAL_TOGGLE_LED1()
#define HAL_TOGGLE_LED3() HAL_TOGGLE_LED1()
#define HAL_TOGGLE_LED4() HAL_TOGGLE_LED1()
#define HAL_STATE_LED1() (LED1_POLARITY (LED1_SBIT))
#define HAL_STATE_LED2() HAL_STATE_LED1()
#define HAL_STATE_LED3() HAL_STATE_LED1()
#define HAL_STATE_LED4() HAL_STATE_LED1()
#endif
/* ----------- XNV ---------- */
#define XNV_SPI_BEGIN() st(P1_3 = 0;)
#define XNV_SPI_TX(x) st(U1CSR &= ~0x02; U1DBUF = (x);)
#define XNV_SPI_RX() U1DBUF
#define XNV_SPI_WAIT_RXRDY() st(while (!(U1CSR & 0x02));)
#define XNV_SPI_END() st(P1_3 = 1;)
// The TI reference design uses UART1 Alt. 2 in SPI mode.
#define XNV_SPI_INIT() \
st( \
/* Mode select UART1 SPI Mode as master. */\
U1CSR = 0; \
\
/* Setup for 115200 baud. */\
U1GCR = 11; \
U1BAUD = 216; \
\
/* Set bit order to MSB */\
U1GCR |= BV(5); \
\
/* Set UART1 I/O to alternate 2 location on P1 pins. */\
PERCFG |= 0x02; /* U1CFG */\
\
/* Select peripheral function on I/O pins but SS is left as GPIO for separate control. */\
P1SEL |= 0xE0; /* SELP1_[7:4] */\
/* P1.1,2,3: reset, LCD CS, XNV CS. */\
P1SEL &= ~0x0E; \
P1 |= 0x0E; \
P1_1 = 0; \
P1DIR |= 0x0E; \
\
/* Give UART1 priority over Timer3. */\
P2SEL &= ~0x20; /* PRI2P1 */\
\
/* When SPI config is complete, enable it. */\
U1CSR |= 0x40; \
/* Release XNV reset. */\
P1_1 = 1; \
)
/* ----------- Minimum safe bus voltage ---------- */
// Vdd/3 / Internal Reference X ENOB --> (Vdd / 3) / 1.15 X 127
#define VDD_2_0 74 // 2.0 V required to safely read/write internal flash.
#define VDD_2_7 100 // 2.7 V required for the Numonyx device.
#define VDD_MIN_RUN VDD_2_0
#define VDD_MIN_NV (VDD_2_0+4) // 5% margin over minimum to survive a page erase and compaction.
#define VDD_MIN_XNV (VDD_2_7+5) // 5% margin over minimum to survive a page erase and compaction.
/* ------------------------------------------------------------------------------------------------
* Driver Configuration
* ------------------------------------------------------------------------------------------------
*/
/* Set to TRUE enable H/W TIMER usage, FALSE disable it */
#ifndef HAL_TIMER
#define HAL_TIMER FALSE
#endif
/* Set to TRUE enable ADC usage, FALSE disable it */
#ifndef HAL_ADC
#define HAL_ADC TRUE
#endif
/* Set to TRUE enable DMA usage, FALSE disable it */
#ifndef HAL_DMA
#define HAL_DMA TRUE
#endif
/* Set to TRUE enable Flash access, FALSE disable it */
#ifndef HAL_FLASH
#define HAL_FLASH TRUE
#endif
/* Set to TRUE enable AES usage, FALSE disable it */
#ifndef HAL_AES
#define HAL_AES TRUE
#endif
#ifndef HAL_AES_DMA
#define HAL_AES_DMA TRUE
#endif
/* Set to TRUE enable LCD usage, FALSE disable it */
#ifndef HAL_LCD
#define HAL_LCD FALSE
#endif
/* Set to TRUE enable LED usage, FALSE disable it */
#ifndef HAL_LED
#define HAL_LED FALSE
#endif
#if (!defined BLINK_LEDS) && (HAL_LED == TRUE)
#define BLINK_LEDS
#endif
/* Set to TRUE enable KEY usage, FALSE disable it */
#ifndef HAL_KEY
#define HAL_KEY FALSE
#endif
#define HAL_SPI TRUE
#define HAL_UART TRUE
#if defined HAL_SB_BOOT_CODE
#define HAL_UART_DMA 0
#define HAL_UART_ISR 1
#else
#define HAL_UART_DMA 1
#define HAL_UART_ISR 0
#endif
#define HAL_UART_USB 0
// Used to set P2 priority - USART0 over USART1 if both are defined.
#if ((HAL_UART_DMA == 1) || (HAL_UART_ISR == 1))
#define HAL_UART_PRIPO 0x00
#else
#define HAL_UART_PRIPO 0x40
#endif
#endif
/*******************************************************************************************************
*/

View File

@@ -0,0 +1,150 @@
/**************************************************************************************************
Filename: hal_dma.c
Revised: $Date: 2010-05-11 15:33:22 -0700 (Tue, 11 May 2010) $
Revision: $Revision: 22450 $
Description: This file contains the interface to the DMA.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "hal_types.h"
#include "hal_defs.h"
#include "hal_dma.h"
#include "hal_mcu.h"
#include "hal_uart.h"
#if (defined HAL_IRGEN) && (HAL_IRGEN == TRUE)
#include "hal_irgen.h"
#endif
#if (defined HAL_SPI) && (HAL_SPI == TRUE)
#include "hal_spi.h"
#endif
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
halDMADesc_t dmaCh0;
halDMADesc_t dmaCh1234[4];
/*********************************************************************
* GLOBAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
/*********************************************************************
* LOCAL FUNCTIONS
*/
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
void HalDmaInit( void )
{
HAL_DMA_SET_ADDR_DESC0( &dmaCh0 );
HAL_DMA_SET_ADDR_DESC1234( dmaCh1234 );
DMAIE = 1;
}
/******************************************************************************
* @fn HalDMAInit
*
* @brief DMA Interrupt Service Routine
*
* @param None
*
* @return None
*****************************************************************************/
HAL_ISR_FUNCTION( halDmaIsr, DMA_VECTOR )
{
HAL_ENTER_ISR();
DMAIF = 0;
if (ZNP_CFG1_UART == znpCfg1)
{
if (HAL_DMA_CHECK_IRQ(HAL_DMA_CH_TX))
{
extern void HalUARTIsrDMA(void);
HalUARTIsrDMA();
}
}
else
{
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_RX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_RX );
HalSpiRxIsr();
}
if ( HAL_DMA_CHECK_IRQ( HAL_DMA_CH_TX ) )
{
HAL_DMA_CLEAR_IRQ( HAL_DMA_CH_TX );
HalSpiTxIsr();
}
}
HAL_EXIT_ISR();
}
#endif // #if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,302 @@
/**************************************************************************************************
Filename: hal_dma.h
Revised: $Date: 2011-05-31 11:57:28 -0700 (Tue, 31 May 2011) $
Revision: $Revision: 26163 $
Description: This file contains the interface to the DMA Service.
Copyright 2007-2011 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_DMA_H
#define HAL_DMA_H
#ifdef __cplusplus
extern "C"
{
#endif
/*********************************************************************
* INCLUDES
*/
#include "hal_board.h"
#include "hal_types.h"
#if ((defined HAL_DMA) && (HAL_DMA == TRUE))
/*********************************************************************
* MACROS
*/
#define HAL_DMA_SET_ADDR_DESC0( a ) \
st( \
DMA0CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA0CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_SET_ADDR_DESC1234( a ) \
st( \
DMA1CFGH = (uint8)( (uint16)(a) >> 8 ); \
DMA1CFGL = (uint8)( (uint16)(a) & 0xFF ); \
)
#define HAL_DMA_GET_DESC0() &dmaCh0
#define HAL_DMA_GET_DESC1234( a ) (dmaCh1234+((a)-1))
#define HAL_DMA_ARM_CH( ch ) DMAARM = (0x01 << (ch))
#define HAL_DMA_CH_ARMED( ch ) (DMAARM & (0x01 << (ch)))
#define HAL_DMA_ABORT_CH( ch ) DMAARM = (0x80 | (0x01 << (ch)))
#define HAL_DMA_MAN_TRIGGER( ch ) DMAREQ = (0x01 << (ch))
#define HAL_DMA_START_CH( ch ) HAL_DMA_MAN_TRIGGER( (ch) )
#define HAL_DMA_CLEAR_IRQ( ch ) DMAIRQ = ~( 1 << (ch) )
#define HAL_DMA_CHECK_IRQ( ch ) (DMAIRQ & ( 1 << (ch) ))
// Macro for quickly setting the source address of a DMA structure.
#define HAL_DMA_SET_SOURCE( pDesc, src ) \
st( \
pDesc->srcAddrH = (uint8)((uint16)(src) >> 8); \
pDesc->srcAddrL = (uint8)( (uint16)(src) & 0xFF ); \
)
// Macro for quickly setting the destination address of a DMA structure.
#define HAL_DMA_SET_DEST( pDesc, dst ) \
st( \
pDesc->dstAddrH = (uint8)((uint16)(dst) >> 8); \
pDesc->dstAddrL = (uint8)( (uint16)(dst) & 0xFF ); \
)
// Macro for quickly setting the number of bytes to be transferred by the DMA,
// max length is 0x1FFF.
#define HAL_DMA_SET_LEN( pDesc, len ) \
st( \
pDesc->xferLenL = (uint8)( (uint16)(len) & 0xFF); \
pDesc->xferLenV &= ~HAL_DMA_LEN_H; \
pDesc->xferLenV |= (uint8)((uint16)(len) >> 8); \
)
#define HAL_DMA_GET_LEN( pDesc ) \
(((uint16)(pDesc->xferLenV & HAL_DMA_LEN_H) << 8) | pDesc->xferLenL)
#define HAL_DMA_SET_VLEN( pDesc, vMode ) \
st( \
pDesc->xferLenV &= ~HAL_DMA_LEN_V; \
pDesc->xferLenV |= (vMode << 5); \
)
#define HAL_DMA_SET_WORD_SIZE( pDesc, xSz ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_WORD_SIZE; \
pDesc->ctrlA |= (xSz << 7); \
)
#define HAL_DMA_SET_TRIG_MODE( pDesc, tMode ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_MODE; \
pDesc->ctrlA |= (tMode << 5); \
)
#define HAL_DMA_GET_TRIG_MODE( pDesc ) ((pDesc->ctrlA >> 5) & 0x3)
#define HAL_DMA_SET_TRIG_SRC( pDesc, tSrc ) \
st( \
pDesc->ctrlA &= ~HAL_DMA_TRIG_SRC; \
pDesc->ctrlA |= tSrc; \
)
#define HAL_DMA_SET_SRC_INC( pDesc, srcInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_SRC_INC; \
pDesc->ctrlB |= (srcInc << 6); \
)
#define HAL_DMA_SET_DST_INC( pDesc, dstInc ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_DST_INC; \
pDesc->ctrlB |= (dstInc << 4); \
)
#define HAL_DMA_SET_IRQ( pDesc, enable ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_IRQ_MASK; \
pDesc->ctrlB |= (enable << 3); \
)
#define HAL_DMA_SET_M8( pDesc, m8 ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_M8; \
pDesc->ctrlB |= (m8 << 2); \
)
#define HAL_DMA_SET_PRIORITY( pDesc, pri ) \
st( \
pDesc->ctrlB &= ~HAL_DMA_PRIORITY; \
pDesc->ctrlB |= pri; \
)
/*********************************************************************
* CONSTANTS
*/
// Use LEN for transfer count
#define HAL_DMA_VLEN_USE_LEN 0x00
// Transfer the first byte + the number of bytes indicated by the first byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST 0x01
// Transfer the number of bytes indicated by the first byte (starting with the first byte)
#define HAL_DMA_VLEN_VALOFFIRST 0x02
// Transfer the first byte + the number of bytes indicated by the first byte + 1 more byte
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_1 0x03
// Transfer the first byte + the number of bytes indicated by the first byte + 2 more bytes
#define HAL_DMA_VLEN_1_P_VALOFFIRST_P_2 0x04
#define HAL_DMA_WORDSIZE_BYTE 0x00 /* Transfer a byte at a time. */
#define HAL_DMA_WORDSIZE_WORD 0x01 /* Transfer a 16-bit word at a time. */
#define HAL_DMA_TMODE_SINGLE 0x00 /* Transfer a single byte/word after each DMA trigger. */
#define HAL_DMA_TMODE_BLOCK 0x01 /* Transfer block of data (length len) after each DMA trigger. */
#define HAL_DMA_TMODE_SINGLE_REPEATED 0x02 /* Transfer single byte/word (after len transfers, rearm DMA). */
#define HAL_DMA_TMODE_BLOCK_REPEATED 0x03 /* Transfer block of data (after len transfers, rearm DMA). */
#define HAL_DMA_TRIG_NONE 0 /* No trigger, setting DMAREQ.DMAREQx bit starts transfer. */
#define HAL_DMA_TRIG_PREV 1 /* DMA channel is triggered by completion of previous channel. */
#define HAL_DMA_TRIG_T1_CH0 2 /* Timer 1, compare, channel 0. */
#define HAL_DMA_TRIG_T1_CH1 3 /* Timer 1, compare, channel 1. */
#define HAL_DMA_TRIG_T1_CH2 4 /* Timer 1, compare, channel 2. */
#define HAL_DMA_TRIG_T2_COMP 5 /* Timer 2, compare. */
#define HAL_DMA_TRIG_T2_OVFL 6 /* Timer 2, overflow. */
#define HAL_DMA_TRIG_T3_CH0 7 /* Timer 3, compare, channel 0. */
#define HAL_DMA_TRIG_T3_CH1 8 /* Timer 3, compare, channel 1. */
#define HAL_DMA_TRIG_T4_CH0 9 /* Timer 4, compare, channel 0. */
#define HAL_DMA_TRIG_T4_CH1 10 /* Timer 4, compare, channel 1. */
#define HAL_DMA_TRIG_ST 11 /* Sleep Timer compare. */
#define HAL_DMA_TRIG_IOC_0 12 /* Port 0 I/O pin input transition. */
#define HAL_DMA_TRIG_IOC_1 13 /* Port 1 I/O pin input transition. */
#define HAL_DMA_TRIG_URX0 14 /* USART0 RX complete. */
#define HAL_DMA_TRIG_UTX0 15 /* USART0 TX complete. */
#define HAL_DMA_TRIG_URX1 16 /* USART1 RX complete. */
#define HAL_DMA_TRIG_UTX1 17 /* USART1 TX complete. */
#define HAL_DMA_TRIG_FLASH 18 /* Flash data write complete. */
#define HAL_DMA_TRIG_RADIO 19 /* RF packet byte received/transmit. */
#define HAL_DMA_TRIG_ADC_CHALL 20 /* ADC end of a conversion in a sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH0 21 /* ADC end of conversion channel 0 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH1 22 /* ADC end of conversion channel 1 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH2 23 /* ADC end of conversion channel 2 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH3 24 /* ADC end of conversion channel 3 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH4 25 /* ADC end of conversion channel 4 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH5 26 /* ADC end of conversion channel 5 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH6 27 /* ADC end of conversion channel 6 in sequence, sample ready. */
#define HAL_DMA_TRIG_ADC_CH7 28 /* ADC end of conversion channel 7 in sequence, sample ready. */
#define HAL_DMA_TRIG_ENC_DW 29 /* AES encryption processor requests download input data. */
#define HAL_DMA_TRIG_ENC_UP 30 /* AES encryption processor requests upload output data. */
#define HAL_DMA_SRCINC_0 0x00 /* Increment source pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_1 0x01 /* Increment source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_2 0x02 /* Increment source pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_SRCINC_M1 0x03 /* Decrement source pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_0 0x00 /* Increment destination pointer by 0 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_1 0x01 /* Increment destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_2 0x02 /* Increment destination pointer by 2 bytes/words after each transfer. */
#define HAL_DMA_DSTINC_M1 0x03 /* Decrement destination pointer by 1 bytes/words after each transfer. */
#define HAL_DMA_IRQMASK_DISABLE 0x00 /* Disable interrupt generation. */
#define HAL_DMA_IRQMASK_ENABLE 0x01 /* Enable interrupt generation upon DMA channel done. */
#define HAL_DMA_M8_USE_8_BITS 0x00 /* Use all 8 bits for transfer count. */
#define HAL_DMA_M8_USE_7_BITS 0x01 /* Use 7 LSB for transfer count. */
#define HAL_DMA_PRI_LOW 0x00 /* Low, CPU has priority. */
#define HAL_DMA_PRI_GUARANTEED 0x01 /* Guaranteed, DMA at least every second try. */
#define HAL_DMA_PRI_HIGH 0x02 /* High, DMA has priority. */
#define HAL_DMA_PRI_ABSOLUTE 0x03 /* Highest, DMA has priority. Reserved for DMA port access.. */
#define HAL_DMA_MAX_ARM_CLOCKS 45 // Maximum number of clocks required if arming all 5 at once.
/*********************************************************************
* TYPEDEFS
*/
// Bit fields of the 'lenModeH'
#define HAL_DMA_LEN_V 0xE0
#define HAL_DMA_LEN_H 0x1F
// Bit fields of the 'ctrlA'
#define HAL_DMA_WORD_SIZE 0x80
#define HAL_DMA_TRIG_MODE 0x60
#define HAL_DMA_TRIG_SRC 0x1F
// Bit fields of the 'ctrlB'
#define HAL_DMA_SRC_INC 0xC0
#define HAL_DMA_DST_INC 0x30
#define HAL_DMA_IRQ_MASK 0x08
#define HAL_DMA_M8 0x04
#define HAL_DMA_PRIORITY 0x03
typedef struct {
uint8 srcAddrH;
uint8 srcAddrL;
uint8 dstAddrH;
uint8 dstAddrL;
uint8 xferLenV;
uint8 xferLenL;
uint8 ctrlA;
uint8 ctrlB;
} halDMADesc_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
extern halDMADesc_t dmaCh0;
extern halDMADesc_t dmaCh1234[4];
/*********************************************************************
* FUNCTIONS - API
*/
void HalDmaInit( void );
#endif // #if (defined HAL_DMA) && (HAL_DMA == TRUE)
#ifdef __cplusplus
}
#endif
#endif // #ifndef HAL_DMA_H
/******************************************************************************
******************************************************************************/

View File

@@ -0,0 +1,171 @@
/**************************************************************************************************
Filename: hal_flash.c
Revised: $Date: 2010-10-07 02:19:52 -0700 (Thu, 07 Oct 2010) $
Revision: $Revision: 24049 $
Description: This file contains the interface to the H/W Flash driver.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/* ------------------------------------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------------------------------------
*/
#include "hal_board_cfg.h"
#include "hal_dma.h"
#include "hal_flash.h"
#include "hal_mcu.h"
#include "hal_types.h"
/**************************************************************************************************
* @fn HalFlashRead
*
* @brief This function reads 'cnt' bytes from the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number.
* @param offset - A valid offset into the page.
* @param buf - A valid buffer space at least as big as the 'cnt' parameter.
* @param cnt - A valid number of bytes to read.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashRead(uint8 pg, uint16 offset, uint8 *buf, uint16 cnt)
{
// Calculate the offset into the containing flash bank as it gets mapped into XDATA.
uint8 *pData = (uint8 *)(offset + HAL_FLASH_PAGE_MAP) +
((pg % HAL_FLASH_PAGE_PER_BANK) * HAL_FLASH_PAGE_SIZE);
uint8 memctr = MEMCTR; // Save to restore.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
halIntState_t is;
#endif
pg /= HAL_FLASH_PAGE_PER_BANK; // Calculate the flash bank from the flash page.
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_ENTER_CRITICAL_SECTION(is);
#endif
// Calculate and map the containing flash bank into XDATA.
MEMCTR = (MEMCTR & 0xF8) | pg;
while (cnt--)
{
*buf++ = *pData++;
}
MEMCTR = memctr;
#if (!defined HAL_OAD_BOOT_CODE) && (!defined HAL_OTA_BOOT_CODE)
HAL_EXIT_CRITICAL_SECTION(is);
#endif
}
/**************************************************************************************************
* @fn HalFlashWrite
*
* @brief This function writes 'cnt' bytes to the internal flash.
*
* input parameters
*
* @param addr - Valid HAL flash write address: actual addr / 4 and quad-aligned.
* @param buf - Valid buffer space at least as big as 'cnt' X 4.
* @param cnt - Number of 4-byte blocks to write.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashWrite(uint16 addr, uint8 *buf, uint16 cnt)
{
#if (defined HAL_DMA) && (HAL_DMA == TRUE)
halDMADesc_t *ch = HAL_NV_DMA_GET_DESC();
HAL_DMA_SET_SOURCE(ch, buf);
HAL_DMA_SET_DEST(ch, &FWDATA);
HAL_DMA_SET_VLEN(ch, HAL_DMA_VLEN_USE_LEN);
HAL_DMA_SET_LEN(ch, (cnt * HAL_FLASH_WORD_SIZE));
HAL_DMA_SET_WORD_SIZE(ch, HAL_DMA_WORDSIZE_BYTE);
HAL_DMA_SET_TRIG_MODE(ch, HAL_DMA_TMODE_SINGLE);
HAL_DMA_SET_TRIG_SRC(ch, HAL_DMA_TRIG_FLASH);
HAL_DMA_SET_SRC_INC(ch, HAL_DMA_SRCINC_1);
HAL_DMA_SET_DST_INC(ch, HAL_DMA_DSTINC_0);
// The DMA is to be polled and shall not issue an IRQ upon completion.
HAL_DMA_SET_IRQ(ch, HAL_DMA_IRQMASK_DISABLE);
HAL_DMA_SET_M8( ch, HAL_DMA_M8_USE_8_BITS);
HAL_DMA_SET_PRIORITY(ch, HAL_DMA_PRI_HIGH);
HAL_DMA_CLEAR_IRQ(HAL_NV_DMA_CH);
HAL_DMA_ARM_CH(HAL_NV_DMA_CH);
FADDRL = (uint8)addr;
FADDRH = (uint8)(addr >> 8);
FCTL |= 0x02; // Trigger the DMA writes.
while (FCTL & 0x80); // Wait until writing is done.
#endif
}
/**************************************************************************************************
* @fn HalFlashErase
*
* @brief This function erases the specified page of the internal flash.
*
* input parameters
*
* @param pg - A valid flash page number to erase.
*
* output parameters
*
* None.
*
* @return None.
**************************************************************************************************
*/
void HalFlashErase(uint8 pg)
{
FADDRH = pg * (HAL_FLASH_PAGE_SIZE / HAL_FLASH_WORD_SIZE / 256);
FCTL |= 0x01;
}
/**************************************************************************************************
*/

View File

@@ -0,0 +1,553 @@
/**************************************************************************************************
Filename: hal_key.c
Revised: $Date: 2010-09-15 19:02:45 -0700 (Wed, 15 Sep 2010) $
Revision: $Revision: 23815 $
Description: This file contains the interface to the HAL KEY Service.
Copyright 2006-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
NOTE: If polling is used, the hal_driver task schedules the KeyRead()
to occur every 100ms. This should be long enough to naturally
debounce the keys. The KeyRead() function remembers the key
state of the previous poll and will only return a non-zero
value if the key state changes.
NOTE: If interrupts are used, the KeyRead() function is scheduled
25ms after the interrupt occurs by the ISR. This delay is used
for key debouncing. The ISR disables any further Key interrupt
until KeyRead() is executed. KeyRead() will re-enable Key
interrupts after executing. Unlike polling, when interrupts
are enabled, the previous key state is not remembered. This
means that KeyRead() will return the current state of the keys
(not a change in state of the keys).
NOTE: If interrupts are used, the KeyRead() fucntion is scheduled by
the ISR. Therefore, the joystick movements will only be detected
during a pushbutton interrupt caused by S1 or the center joystick
pushbutton.
NOTE: When a switch like S1 is pushed, the S1 signal goes from a normally
high state to a low state. This transition is typically clean. The
duration of the low state is around 200ms. When the signal returns
to the high state, there is a high likelihood of signal bounce, which
causes a unwanted interrupts. Normally, we would set the interrupt
edge to falling edge to generate an interrupt when S1 is pushed, but
because of the signal bounce, it is better to set the edge to rising
edge to generate an interrupt when S1 is released. The debounce logic
can then filter out the signal bounce. The result is that we typically
get only 1 interrupt per button push. This mechanism is not totally
foolproof because occasionally, signal bound occurs during the falling
edge as well. A similar mechanism is used to handle the joystick
pushbutton on the DB. For the EB, we do not have independent control
of the interrupt edge for the S1 and center joystick pushbutton. As
a result, only one or the other pushbuttons work reasonably well with
interrupts. The default is the make the S1 switch on the EB work more
reliably.
*********************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_board.h"
#include "hal_drivers.h"
#include "hal_adc.h"
#include "hal_key.h"
#include "osal.h"
#if (defined HAL_KEY) && (HAL_KEY == TRUE)
/**************************************************************************************************
* MACROS
**************************************************************************************************/
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
#define HAL_KEY_RISING_EDGE 0
#define HAL_KEY_FALLING_EDGE 1
#define HAL_KEY_DEBOUNCE_VALUE 25
/* CPU port interrupt */
#define HAL_KEY_CPU_PORT_0_IF P0IF
#define HAL_KEY_CPU_PORT_2_IF P2IF
/* SW_6 is at P0.1 */
#define HAL_KEY_SW_6_PORT P0
#define HAL_KEY_SW_6_BIT BV(1)
#define HAL_KEY_SW_6_SEL P0SEL
#define HAL_KEY_SW_6_DIR P0DIR
/* edge interrupt */
#define HAL_KEY_SW_6_EDGEBIT BV(0)
#define HAL_KEY_SW_6_EDGE HAL_KEY_FALLING_EDGE
/* SW_6 interrupts */
#define HAL_KEY_SW_6_IEN IEN1 /* CPU interrupt mask register */
#define HAL_KEY_SW_6_IENBIT BV(5) /* Mask bit for all of Port_0 */
#define HAL_KEY_SW_6_ICTL P0IEN /* Port Interrupt Control register */
#define HAL_KEY_SW_6_ICTLBIT BV(1) /* P0IEN - P0.1 enable/disable bit */
#define HAL_KEY_SW_6_PXIFG P0IFG /* Interrupt flag at source */
/* Joy stick move at P2.0 */
#define HAL_KEY_JOY_MOVE_PORT P2
#define HAL_KEY_JOY_MOVE_BIT BV(0)
#define HAL_KEY_JOY_MOVE_SEL P2SEL
#define HAL_KEY_JOY_MOVE_DIR P2DIR
/* edge interrupt */
#define HAL_KEY_JOY_MOVE_EDGEBIT BV(3)
#define HAL_KEY_JOY_MOVE_EDGE HAL_KEY_FALLING_EDGE
/* Joy move interrupts */
#define HAL_KEY_JOY_MOVE_IEN IEN2 /* CPU interrupt mask register */
#define HAL_KEY_JOY_MOVE_IENBIT BV(1) /* Mask bit for all of Port_2 */
#define HAL_KEY_JOY_MOVE_ICTL P2IEN /* Port Interrupt Control register */
#define HAL_KEY_JOY_MOVE_ICTLBIT BV(0) /* P2IENL - P2.0<->P2.3 enable/disable bit */
#define HAL_KEY_JOY_MOVE_PXIFG P2IFG /* Interrupt flag at source */
#define HAL_KEY_JOY_CHN HAL_ADC_CHANNEL_6
/**************************************************************************************************
* TYPEDEFS
**************************************************************************************************/
/**************************************************************************************************
* GLOBAL VARIABLES
**************************************************************************************************/
static uint8 halKeySavedKeys; /* used to store previous key state in polling mode */
static halKeyCBack_t pHalKeyProcessFunction;
static uint8 HalKeyConfigured;
bool Hal_KeyIntEnable; /* interrupt enable/disable flag */
/**************************************************************************************************
* FUNCTIONS - Local
**************************************************************************************************/
void halProcessKeyInterrupt(void);
uint8 halGetJoyKeyInput(void);
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
/**************************************************************************************************
* @fn HalKeyInit
*
* @brief Initilize Key Service
*
* @param none
*
* @return None
**************************************************************************************************/
void HalKeyInit( void )
{
/* Initialize previous key to 0 */
halKeySavedKeys = 0;
HAL_KEY_SW_6_SEL &= ~(HAL_KEY_SW_6_BIT); /* Set pin function to GPIO */
HAL_KEY_SW_6_DIR &= ~(HAL_KEY_SW_6_BIT); /* Set pin direction to Input */
HAL_KEY_JOY_MOVE_SEL &= ~(HAL_KEY_JOY_MOVE_BIT); /* Set pin function to GPIO */
HAL_KEY_JOY_MOVE_DIR &= ~(HAL_KEY_JOY_MOVE_BIT); /* Set pin direction to Input */
/* Initialize callback function */
pHalKeyProcessFunction = NULL;
/* Start with key is not configured */
HalKeyConfigured = FALSE;
}
/**************************************************************************************************
* @fn HalKeyConfig
*
* @brief Configure the Key serivce
*
* @param interruptEnable - TRUE/FALSE, enable/disable interrupt
* cback - pointer to the CallBack function
*
* @return None
**************************************************************************************************/
void HalKeyConfig (bool interruptEnable, halKeyCBack_t cback)
{
/* Enable/Disable Interrupt or */
Hal_KeyIntEnable = interruptEnable;
/* Register the callback fucntion */
pHalKeyProcessFunction = cback;
/* Determine if interrupt is enable or not */
if (Hal_KeyIntEnable)
{
/* Rising/Falling edge configuratinn */
PICTL &= ~(HAL_KEY_SW_6_EDGEBIT); /* Clear the edge bit */
/* For falling edge, the bit must be set. */
#if (HAL_KEY_SW_6_EDGE == HAL_KEY_FALLING_EDGE)
PICTL |= HAL_KEY_SW_6_EDGEBIT;
#endif
/* Interrupt configuration:
* - Enable interrupt generation at the port
* - Enable CPU interrupt
* - Clear any pending interrupt
*/
HAL_KEY_SW_6_ICTL |= HAL_KEY_SW_6_ICTLBIT;
HAL_KEY_SW_6_IEN |= HAL_KEY_SW_6_IENBIT;
HAL_KEY_SW_6_PXIFG = ~(HAL_KEY_SW_6_BIT);
/* Rising/Falling edge configuratinn */
HAL_KEY_JOY_MOVE_ICTL &= ~(HAL_KEY_JOY_MOVE_EDGEBIT); /* Clear the edge bit */
/* For falling edge, the bit must be set. */
#if (HAL_KEY_JOY_MOVE_EDGE == HAL_KEY_FALLING_EDGE)
HAL_KEY_JOY_MOVE_ICTL |= HAL_KEY_JOY_MOVE_EDGEBIT;
#endif
/* Interrupt configuration:
* - Enable interrupt generation at the port
* - Enable CPU interrupt
* - Clear any pending interrupt
*/
HAL_KEY_JOY_MOVE_ICTL |= HAL_KEY_JOY_MOVE_ICTLBIT;
HAL_KEY_JOY_MOVE_IEN |= HAL_KEY_JOY_MOVE_IENBIT;
HAL_KEY_JOY_MOVE_PXIFG = ~(HAL_KEY_JOY_MOVE_BIT);
/* Do this only after the hal_key is configured - to work with sleep stuff */
if (HalKeyConfigured == TRUE)
{
osal_stop_timerEx(Hal_TaskID, HAL_KEY_EVENT); /* Cancel polling if active */
}
}
else /* Interrupts NOT enabled */
{
HAL_KEY_SW_6_ICTL &= ~(HAL_KEY_SW_6_ICTLBIT); /* don't generate interrupt */
HAL_KEY_SW_6_IEN &= ~(HAL_KEY_SW_6_IENBIT); /* Clear interrupt enable bit */
osal_set_event(Hal_TaskID, HAL_KEY_EVENT);
}
/* Key now is configured */
HalKeyConfigured = TRUE;
}
/**************************************************************************************************
* @fn HalKeyRead
*
* @brief Read the current value of a key
*
* @param None
*
* @return keys - current keys status
**************************************************************************************************/
uint8 HalKeyRead ( void )
{
uint8 keys = 0;
if (HAL_PUSH_BUTTON1())
{
keys |= HAL_KEY_SW_6;
}
if ((HAL_KEY_JOY_MOVE_PORT & HAL_KEY_JOY_MOVE_BIT)) /* Key is active low */
{
keys |= halGetJoyKeyInput();
}
return keys;
}
/**************************************************************************************************
* @fn HalKeyPoll
*
* @brief Called by hal_driver to poll the keys
*
* @param None
*
* @return None
**************************************************************************************************/
void HalKeyPoll (void)
{
uint8 keys = 0;
if ((HAL_KEY_JOY_MOVE_PORT & HAL_KEY_JOY_MOVE_BIT)) /* Key is active HIGH */
{
keys = halGetJoyKeyInput();
}
/* If interrupts are not enabled, previous key status and current key status
* are compared to find out if a key has changed status.
*/
if (!Hal_KeyIntEnable)
{
if (keys == halKeySavedKeys)
{
/* Exit - since no keys have changed */
return;
}
/* Store the current keys for comparation next time */
halKeySavedKeys = keys;
}
else
{
/* Key interrupt handled here */
}
if (HAL_PUSH_BUTTON1())
{
keys |= HAL_KEY_SW_6;
}
/* Invoke Callback if new keys were depressed */
if (keys && (pHalKeyProcessFunction))
{
(pHalKeyProcessFunction) (keys, HAL_KEY_STATE_NORMAL);
}
}
/**************************************************************************************************
* @fn halGetJoyKeyInput
*
* @brief Map the ADC value to its corresponding key.
*
* @param None
*
* @return keys - current joy key status
**************************************************************************************************/
uint8 halGetJoyKeyInput(void)
{
/* The joystick control is encoded as an analog voltage.
* Read the JOY_LEVEL analog value and map it to joy movement.
*/
uint8 adc;
uint8 ksave0 = 0;
uint8 ksave1;
/* Keep on reading the ADC until two consecutive key decisions are the same. */
do
{
ksave1 = ksave0; /* save previouse key reading */
adc = HalAdcRead (HAL_KEY_JOY_CHN, HAL_ADC_RESOLUTION_8);
if ((adc >= 2) && (adc <= 38))
{
ksave0 |= HAL_KEY_UP;
}
else if ((adc >= 74) && (adc <= 88))
{
ksave0 |= HAL_KEY_RIGHT;
}
else if ((adc >= 60) && (adc <= 73))
{
ksave0 |= HAL_KEY_LEFT;
}
else if ((adc >= 39) && (adc <= 59))
{
ksave0 |= HAL_KEY_DOWN;
}
else if ((adc >= 89) && (adc <= 100))
{
ksave0 |= HAL_KEY_CENTER;
}
} while (ksave0 != ksave1);
return ksave0;
}
/**************************************************************************************************
* @fn halProcessKeyInterrupt
*
* @brief Checks to see if it's a valid key interrupt, saves interrupt driven key states for
* processing by HalKeyRead(), and debounces keys by scheduling HalKeyRead() 25ms later.
*
* @param
*
* @return
**************************************************************************************************/
void halProcessKeyInterrupt (void)
{
bool valid=FALSE;
if (HAL_KEY_SW_6_PXIFG & HAL_KEY_SW_6_BIT) /* Interrupt Flag has been set */
{
HAL_KEY_SW_6_PXIFG = ~(HAL_KEY_SW_6_BIT); /* Clear Interrupt Flag */
valid = TRUE;
}
if (HAL_KEY_JOY_MOVE_PXIFG & HAL_KEY_JOY_MOVE_BIT) /* Interrupt Flag has been set */
{
HAL_KEY_JOY_MOVE_PXIFG = ~(HAL_KEY_JOY_MOVE_BIT); /* Clear Interrupt Flag */
valid = TRUE;
}
if (valid)
{
osal_start_timerEx (Hal_TaskID, HAL_KEY_EVENT, HAL_KEY_DEBOUNCE_VALUE);
}
}
/**************************************************************************************************
* @fn HalKeyEnterSleep
*
* @brief - Get called to enter sleep mode
*
* @param
*
* @return
**************************************************************************************************/
void HalKeyEnterSleep ( void )
{
}
/**************************************************************************************************
* @fn HalKeyExitSleep
*
* @brief - Get called when sleep is over
*
* @param
*
* @return - return saved keys
**************************************************************************************************/
uint8 HalKeyExitSleep ( void )
{
/* Wake up and read keys */
return ( HalKeyRead () );
}
/***************************************************************************************************
* INTERRUPT SERVICE ROUTINE
***************************************************************************************************/
/**************************************************************************************************
* @fn halKeyPort0Isr
*
* @brief Port0 ISR
*
* @param
*
* @return
**************************************************************************************************/
HAL_ISR_FUNCTION( halKeyPort0Isr, P0INT_VECTOR )
{
HAL_ENTER_ISR();
if (HAL_KEY_SW_6_PXIFG & HAL_KEY_SW_6_BIT)
{
halProcessKeyInterrupt();
}
/*
Clear the CPU interrupt flag for Port_0
PxIFG has to be cleared before PxIF
*/
HAL_KEY_SW_6_PXIFG = 0;
HAL_KEY_CPU_PORT_0_IF = 0;
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
/**************************************************************************************************
* @fn halKeyPort2Isr
*
* @brief Port2 ISR
*
* @param
*
* @return
**************************************************************************************************/
HAL_ISR_FUNCTION( halKeyPort2Isr, P2INT_VECTOR )
{
HAL_ENTER_ISR();
if (HAL_KEY_JOY_MOVE_PXIFG & HAL_KEY_JOY_MOVE_BIT)
{
halProcessKeyInterrupt();
}
/*
Clear the CPU interrupt flag for Port_2
PxIFG has to be cleared before PxIF
Notes: P2_1 and P2_2 are debug lines.
*/
HAL_KEY_JOY_MOVE_PXIFG = 0;
HAL_KEY_CPU_PORT_2_IF = 0;
CLEAR_SLEEP_MODE();
HAL_EXIT_ISR();
}
#else
void HalKeyInit(void){}
void HalKeyConfig(bool interruptEnable, halKeyCBack_t cback){}
uint8 HalKeyRead(void){ return 0;}
void HalKeyPoll(void){}
#endif /* HAL_KEY */
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,763 @@
/**************************************************************************************************
Filename: hal_lcd.c
Revised: $Date: 2010-08-10 19:12:51 -0700 (Tue, 10 Aug 2010) $
Revision: $Revision: 23375 $
Description: This file contains the interface to the HAL LCD Service.
Copyright 2007-2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/**************************************************************************************************
* INCLUDES
**************************************************************************************************/
#include "hal_types.h"
#include "hal_lcd.h"
#include "OSAL.h"
#include "OnBoard.h"
#include "hal_assert.h"
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#include "DebugTrace.h"
#endif
/**************************************************************************************************
* CONSTANTS
**************************************************************************************************/
/*
LCD pins
//control
P0.0 - LCD_MODE
P1.1 - LCD_FLASH_RESET
P1.2 - LCD_CS
//spi
P1.5 - CLK
P1.6 - MOSI
P1.7 - MISO
*/
/* LCD Control lines */
#define HAL_LCD_MODE_PORT 0
#define HAL_LCD_MODE_PIN 0
#define HAL_LCD_RESET_PORT 1
#define HAL_LCD_RESET_PIN 1
#define HAL_LCD_CS_PORT 1
#define HAL_LCD_CS_PIN 2
/* LCD SPI lines */
#define HAL_LCD_CLK_PORT 1
#define HAL_LCD_CLK_PIN 5
#define HAL_LCD_MOSI_PORT 1
#define HAL_LCD_MOSI_PIN 6
#define HAL_LCD_MISO_PORT 1
#define HAL_LCD_MISO_PIN 7
/* SPI settings */
#define HAL_SPI_CLOCK_POL_LO 0x00
#define HAL_SPI_CLOCK_PHA_0 0x00
#define HAL_SPI_TRANSFER_MSB_FIRST 0x20
/* LCD lines */
#define LCD_MAX_LINE_COUNT 3
#define LCD_MAX_LINE_LENGTH 16
#define LCD_MAX_BUF 25
/* Defines for HW LCD */
/* Set power save mode */
#define OSC_OFF 0x00
#define OSC_ON 0x01
#define POWER_SAVE_OFF 0x00
#define POWER_SAVE_ON 0x02
#define SET_POWER_SAVE_MODE(options) HalLcd_HW_Control(0x0C | (options))
/* Function Set */
#define CGROM 0x00
#define CGRAM 0x01
#define COM_FORWARD 0x00
#define COM_BACKWARD 0x02
#define TWO_LINE 0x00
#define THREE_LINE 0x04
#define FUNCTION_SET(options) HalLcd_HW_Control(0x10 | (options))
/* Set Display Start Line */
#define LINE1 0x00
#define LINE2 0x01
#define LINE3 0x02
#define LINE4 0x03
#define SET_DISPLAY_START_LINE(line) HalLcd_HW_Control(0x18 | (line))
/* Bias control */
#define BIAS_1_5 0x00
#define BIAS_1_4 0x01
#define SET_BIAS_CTRL(bias) HalLcd_HW_Control(0x1C | (bias))
/* Power control */
#define VOLTAGE_DIVIDER_OFF 0x00
#define VOLTAGE_DIVIDER_ON 0x01
#define CONVERTER_AND_REG_OFF 0x00
#define CONVERTER_AND_REG_ON 0x04
#define SET_POWER_CTRL(options) HalLcd_HW_Control(0x20 | (options))
// Set display control
#define DISPLAY_CTRL_ON 0x01
#define DISPLAY_CTRL_OFF 0x00
#define DISPLAY_CTRL_BLINK_ON 0x02
#define DISPLAY_CTRL_BLINK_OFF 0x00
#define DISPLAY_CTRL_CURSOR_ON 0x04
#define DISPLAY_CTRL_CURSOR_OFF 0x00
#define SET_DISPLAY_CTRL(options) HalLcd_HW_Control(0x28 | (options))
/* Set DD/ CGRAM address */
#define SET_DDRAM_ADDR(charIndex) HalLcd_HW_Control(0x80 | (charIndex))
#define SET_GCRAM_CHAR(specIndex) HalLcd_HW_Control(0xC0 | (specIndex))
/* Set ICONRAM address */
#define CONTRAST_CTRL_REGISTER 0x10
#define SET_ICONRAM_ADDR(addr) HalLcd_HW_Control(0x40 | (addr))
/* Set double height */
#define LINE_1_AND_2 0x01
#define LINE_2_AND_3 0x02
#define NORMAL_DISPLAY 0x00
#define SET_DOUBLE_HEIGHT(options) HalLcd_HW_Control(0x08 | (options))
/**************************************************************************************************
* MACROS
**************************************************************************************************/
#define HAL_IO_SET(port, pin, val) HAL_IO_SET_PREP(port, pin, val)
#define HAL_IO_SET_PREP(port, pin, val) st( P##port##_##pin## = val; )
#define HAL_CONFIG_IO_OUTPUT(port, pin, val) HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val)
#define HAL_CONFIG_IO_OUTPUT_PREP(port, pin, val) st( P##port##SEL &= ~BV(pin); \
P##port##_##pin## = val; \
P##port##DIR |= BV(pin); )
#define HAL_CONFIG_IO_PERIPHERAL(port, pin) HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin)
#define HAL_CONFIG_IO_PERIPHERAL_PREP(port, pin) st( P##port##SEL |= BV(pin); )
/* SPI interface control */
#define LCD_SPI_BEGIN() HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 0); /* chip select */
#define LCD_SPI_END() \
{ \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
asm("NOP"); \
HAL_IO_SET(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1); /* chip select */ \
}
/* clear the received and transmit byte status, write tx data to buffer, wait till transmit done */
#define LCD_SPI_TX(x) { U1CSR &= ~(BV(2) | BV(1)); U1DBUF = x; while( !(U1CSR & BV(1)) ); }
#define LCD_SPI_WAIT_RXRDY() { while(!(U1CSR & BV(1))); }
/* Control macros */
#define LCD_DO_WRITE() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
#define LCD_DO_CONTROL() HAL_IO_SET(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 0);
#define LCD_ACTIVATE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 0);
#define LCD_RELEASE_RESET() HAL_IO_SET(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* LOCAL VARIABLES
**************************************************************************************************/
static uint8 *Lcd_Line1;
/**************************************************************************************************
* FUNCTIONS - API
**************************************************************************************************/
void HalLcd_HW_Init(void);
void HalLcd_HW_WaitUs(uint16 i);
void HalLcd_HW_Clear(void);
void HalLcd_HW_ClearAllSpecChars(void);
void HalLcd_HW_Control(uint8 cmd);
void HalLcd_HW_Write(uint8 data);
void HalLcd_HW_SetContrast(uint8 value);
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text);
void HalLcd_HW_WriteLine(uint8 line, const char *pText);
#endif //LCD
/**************************************************************************************************
* @fn HalLcdInit
*
* @brief Initilize LCD Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
**************************************************************************************************/
void HalLcdInit(void)
{
#if (HAL_LCD == TRUE)
Lcd_Line1 = NULL;
HalLcd_HW_Init();
#endif
}
/*************************************************************************************************
* LCD EMULATION FUNCTIONS
*
* Some evaluation boards are equipped with Liquid Crystal Displays
* (LCD) which may be used to display diagnostic information. These
* functions provide LCD emulation, sending the diagnostic strings
* to Z-Tool via the RS232 serial port. These functions are enabled
* when the "LCD_SUPPORTED" compiler flag is placed in the makefile.
*
* Most applications update both lines (1 and 2) of the LCD whenever
* text is posted to the device. This emulator assumes that line 1 is
* updated first (saved locally) and the formatting and send operation
* is triggered by receipt of line 2. Nothing will be transmitted if
* only line 1 is updated.
*
*************************************************************************************************/
/**************************************************************************************************
* @fn HalLcdWriteString
*
* @brief Write a string to the LCD
*
* @param str - pointer to the string that will be displayed
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteString ( char *str, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 strLen = 0;
uint8 totalLen = 0;
uint8 *buf;
uint8 tmpLen;
if ( Lcd_Line1 == NULL )
{
Lcd_Line1 = osal_mem_alloc( HAL_LCD_MAX_CHARS+1 );
HalLcdWriteString( "TexasInstruments", 1 );
}
strLen = (uint8)osal_strlen( (char*)str );
/* Check boundries */
if ( strLen > HAL_LCD_MAX_CHARS )
strLen = HAL_LCD_MAX_CHARS;
if ( option == HAL_LCD_LINE_1 )
{
/* Line 1 gets saved for later */
osal_memcpy( Lcd_Line1, str, strLen );
Lcd_Line1[strLen] = '\0';
}
else
{
/* Line 2 triggers action */
tmpLen = (uint8)osal_strlen( (char*)Lcd_Line1 );
totalLen = tmpLen + 1 + strLen + 1;
buf = osal_mem_alloc( totalLen );
if ( buf != NULL )
{
/* Concatenate strings */
osal_memcpy( buf, Lcd_Line1, tmpLen );
buf[tmpLen++] = ' ';
osal_memcpy( &buf[tmpLen], str, strLen );
buf[tmpLen+strLen] = '\0';
/* Send it out */
#if defined (ZTOOL_P1) || defined (ZTOOL_P2)
#if defined(SERIAL_DEBUG_SUPPORTED)
debug_str( (uint8*)buf );
#endif //LCD_SUPPORTED
#endif //ZTOOL_P1
/* Free mem */
osal_mem_free( buf );
}
}
/* Display the string */
HalLcd_HW_WriteLine (option, str);
#endif //HAL_LCD
}
/**************************************************************************************************
* @fn HalLcdWriteValue
*
* @brief Write a value to the LCD
*
* @param value - value that will be displayed
* radix - 8, 10, 16
* option - display options
*
* @return None
**************************************************************************************************/
void HalLcdWriteValue ( uint32 value, const uint8 radix, uint8 option)
{
#if (HAL_LCD == TRUE)
uint8 buf[LCD_MAX_BUF];
_ltoa( value, &buf[0], radix );
HalLcdWriteString( (char*)buf, option );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteScreen
*
* @brief Write a value to the LCD
*
* @param line1 - string that will be displayed on line 1
* line2 - string that will be displayed on line 2
*
* @return None
**************************************************************************************************/
void HalLcdWriteScreen( char *line1, char *line2 )
{
#if (HAL_LCD == TRUE)
HalLcdWriteString( line1, 1 );
HalLcdWriteString( line2, 2 );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value - value
* format - redix
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValue( char *title, uint16 value, uint8 format, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
osal_memcpy( buf, title, tmpLen );
buf[tmpLen] = ' ';
err = (uint32)(value);
_ltoa( err, &buf[tmpLen+1], format );
HalLcdWriteString( (char*)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdWriteStringValue
*
* @brief Write a string followed by a value to the LCD
*
* @param title - Title that will be displayed before the value
* value1 - value #1
* format1 - redix of value #1
* value2 - value #2
* format2 - redix of value #2
* line - line number
*
* @return None
**************************************************************************************************/
void HalLcdWriteStringValueValue( char *title, uint16 value1, uint8 format1,
uint16 value2, uint8 format2, uint8 line )
{
#if (HAL_LCD == TRUE)
uint8 tmpLen;
uint8 buf[LCD_MAX_BUF];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
if ( tmpLen )
{
osal_memcpy( buf, title, tmpLen );
buf[tmpLen++] = ' ';
}
err = (uint32)(value1);
_ltoa( err, &buf[tmpLen], format1 );
tmpLen = (uint8)osal_strlen( (char*)buf );
buf[tmpLen++] = ',';
buf[tmpLen++] = ' ';
err = (uint32)(value2);
_ltoa( err, &buf[tmpLen], format2 );
HalLcdWriteString( (char *)buf, line );
#endif
}
/**************************************************************************************************
* @fn HalLcdDisplayPercentBar
*
* @brief Display percentage bar on the LCD
*
* @param title -
* value -
*
* @return None
**************************************************************************************************/
void HalLcdDisplayPercentBar( char *title, uint8 value )
{
#if (HAL_LCD == TRUE)
uint8 percent;
uint8 leftOver;
uint8 buf[17];
uint32 err;
uint8 x;
/* Write the title: */
HalLcdWriteString( title, HAL_LCD_LINE_1 );
if ( value > 100 )
value = 100;
/* convert to blocks */
percent = (uint8)(value / 10);
leftOver = (uint8)(value % 10);
/* Make window */
osal_memcpy( buf, "[ ] ", 15 );
for ( x = 0; x < percent; x ++ )
{
buf[1+x] = '>';
}
if ( leftOver >= 5 )
buf[1+x] = '+';
err = (uint32)value;
_ltoa( err, (uint8*)&buf[13], 10 );
HalLcdWriteString( (char*)buf, HAL_LCD_LINE_2 );
#endif
}
#if (HAL_LCD == TRUE)
/**************************************************************************************************
* HARDWARE LCD
**************************************************************************************************/
/**************************************************************************************************
* @fn halLcd_ConfigIO
*
* @brief Configure IO lines needed for LCD control.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigIO(void)
{
/* GPIO configuration */
HAL_CONFIG_IO_OUTPUT(HAL_LCD_MODE_PORT, HAL_LCD_MODE_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_RESET_PORT, HAL_LCD_RESET_PIN, 1);
HAL_CONFIG_IO_OUTPUT(HAL_LCD_CS_PORT, HAL_LCD_CS_PIN, 1);
}
/**************************************************************************************************
* @fn halLcd_ConfigSPI
*
* @brief Configure SPI lines needed for talking to LCD.
*
* @param None
*
* @return None
**************************************************************************************************/
static void halLcd_ConfigSPI(void)
{
/* UART/SPI Peripheral configuration */
uint8 baud_exponent;
uint8 baud_mantissa;
/* Set SPI on UART 1 alternative 2 */
PERCFG |= 0x02;
/* Configure clk, master out and master in lines */
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_CLK_PORT, HAL_LCD_CLK_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MOSI_PORT, HAL_LCD_MOSI_PIN);
HAL_CONFIG_IO_PERIPHERAL(HAL_LCD_MISO_PORT, HAL_LCD_MISO_PIN);
/* Set SPI speed to 1 MHz (the values assume system clk of 32MHz)
* Confirm on board that this results in 1MHz spi clk.
*/
baud_exponent = 15;
baud_mantissa = 0;
/* Configure SPI */
U1UCR = 0x80; /* Flush and goto IDLE state. 8-N-1. */
U1CSR = 0x00; /* SPI mode, master. */
U1GCR = HAL_SPI_TRANSFER_MSB_FIRST | HAL_SPI_CLOCK_PHA_0 | HAL_SPI_CLOCK_POL_LO | baud_exponent;
U1BAUD = baud_mantissa;
}
/**************************************************************************************************
* @fn HalLcd_HW_Init
*
* @brief Initilize HW LCD Driver.
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Init(void)
{
/* Initialize LCD IO lines */
halLcd_ConfigIO();
/* Initialize SPI */
halLcd_ConfigSPI();
/* Perform reset */
LCD_ACTIVATE_RESET();
HalLcd_HW_WaitUs(15000); // 15 ms
LCD_RELEASE_RESET();
HalLcd_HW_WaitUs(15); // 15 us
/* Perform the initialization sequence */
FUNCTION_SET(CGRAM | COM_FORWARD | THREE_LINE);
/* Set contrast */
HalLcd_HW_SetContrast(15);
/* Set power */
SET_POWER_SAVE_MODE(OSC_OFF | POWER_SAVE_ON);
SET_POWER_CTRL(VOLTAGE_DIVIDER_ON | CONVERTER_AND_REG_ON);
SET_BIAS_CTRL(BIAS_1_5);
HalLcd_HW_WaitUs(21000);// 21 ms
/* Clear the display */
HalLcd_HW_Clear();
HalLcd_HW_ClearAllSpecChars();
SET_DISPLAY_CTRL(DISPLAY_CTRL_ON | DISPLAY_CTRL_BLINK_OFF | DISPLAY_CTRL_CURSOR_OFF);
}
/**************************************************************************************************
* @fn HalLcd_HW_Control
*
* @brief Write 1 command to the LCD
*
* @param uint8 cmd - command to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Control(uint8 cmd)
{
LCD_SPI_BEGIN();
LCD_DO_CONTROL();
LCD_SPI_TX(cmd);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_Write
*
* @brief Write 1 byte to the LCD
*
* @param uint8 data - data to be written to the LCD
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Write(uint8 data)
{
LCD_SPI_BEGIN();
LCD_DO_WRITE();
LCD_SPI_TX(data);
LCD_SPI_WAIT_RXRDY();
LCD_SPI_END();
}
/**************************************************************************************************
* @fn HalLcd_HW_SetContrast
*
* @brief Set display contrast
*
* @param uint8 value - contrast value
*
* @return none
**************************************************************************************************/
void HalLcd_HW_SetContrast(uint8 value)
{
SET_ICONRAM_ADDR(CONTRAST_CTRL_REGISTER);
HalLcd_HW_Write(value);
}
/**************************************************************************************************
* @fn HalLcd_HW_Clear
*
* @brief Clear the HW LCD
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_Clear(void)
{
uint8 n;
SET_DDRAM_ADDR(0x00);
for (n = 0; n < (LCD_MAX_LINE_COUNT * LCD_MAX_LINE_LENGTH); n++)
{
HalLcd_HW_Write(' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_ClearAllSpecChars
*
* @brief Clear all special chars
*
* @param None
*
* @return None
**************************************************************************************************/
void HalLcd_HW_ClearAllSpecChars(void)
{
uint8 n = 0;
SET_GCRAM_CHAR(0);
for (n = 0; n < (8 * 8); n++)
{
HalLcd_HW_Write(0x00);
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WriteChar
*
* @brief Write one char to the display
*
* @param uint8 line - line number that the char will be displayed
* uint8 col - colum where the char will be displayed
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WriteChar(uint8 line, uint8 col, char text)
{
if (col < LCD_MAX_LINE_LENGTH)
{
SET_DDRAM_ADDR((line - 1) * LCD_MAX_LINE_LENGTH + col);
HalLcd_HW_Write(text);
}
else
{
return;
}
}
/**************************************************************************************************
* @fn halLcdWriteLine
*
* @brief Write one line on display
*
* @param uint8 line - display line
* char *pText - text buffer to write
*
* @return none
**************************************************************************************************/
void HalLcd_HW_WriteLine(uint8 line, const char *pText)
{
uint8 count;
uint8 totalLength = (uint8)osal_strlen( (char *)pText );
/* Write the content first */
for (count=0; count<totalLength; count++)
{
HalLcd_HW_WriteChar(line, count, (*(pText++)));
}
/* Write blank spaces to rest of the line */
for(count=totalLength; count<LCD_MAX_LINE_LENGTH;count++)
{
HalLcd_HW_WriteChar(line, count, ' ');
}
}
/**************************************************************************************************
* @fn HalLcd_HW_WaitUs
*
* @brief wait for x us. @ 32MHz MCU clock it takes 32 "nop"s for 1 us delay.
*
* @param x us. range[0-65536]
*
* @return None
**************************************************************************************************/
void HalLcd_HW_WaitUs(uint16 microSecs)
{
while(microSecs--)
{
/* 32 NOPs == 1 usecs */
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop");
asm("nop"); asm("nop");
}
}
#endif
/**************************************************************************************************
**************************************************************************************************/

View File

@@ -0,0 +1,517 @@
/**************************************************************************************************
Filename: hal_led.c
Revised: $Date: 2011-04-15 10:47:58 -0700 (Fri, 15 Apr 2011) $
Revision: $Revision: 25723 $
Description: This file contains the interface to the HAL LED Service.
Copyright 2006-2007 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/***************************************************************************************************
* INCLUDES
***************************************************************************************************/
#include "hal_mcu.h"
#include "hal_defs.h"
#include "hal_types.h"
#include "hal_drivers.h"
#include "hal_led.h"
#include "osal.h"
#include "hal_board.h"
/***************************************************************************************************
* CONSTANTS
***************************************************************************************************/
/***************************************************************************************************
* MACROS
***************************************************************************************************/
/***************************************************************************************************
* TYPEDEFS
***************************************************************************************************/
/* LED control structure */
typedef struct {
uint8 mode; /* Operation mode */
uint8 todo; /* Blink cycles left */
uint8 onPct; /* On cycle percentage */
uint16 time; /* On/off cycle time (msec) */
uint32 next; /* Time for next change */
} HalLedControl_t;
typedef struct
{
HalLedControl_t HalLedControlTable[HAL_LED_DEFAULT_MAX_LEDS];
uint8 sleepActive;
} HalLedStatus_t;
/***************************************************************************************************
* GLOBAL VARIABLES
***************************************************************************************************/
static uint8 HalLedState; // LED state at last set/clr/blink update
#if HAL_LED == TRUE
static uint8 HalSleepLedState; // LED state at last set/clr/blink update
static uint8 preBlinkState; // Original State before going to blink mode
// bit 0, 1, 2, 3 represent led 0, 1, 2, 3
#endif
#ifdef BLINK_LEDS
static HalLedStatus_t HalLedStatusControl;
#endif
/***************************************************************************************************
* LOCAL FUNCTION
***************************************************************************************************/
#if (HAL_LED == TRUE)
void HalLedUpdate (void);
void HalLedOnOff (uint8 leds, uint8 mode);
#endif /* HAL_LED */
/***************************************************************************************************
* FUNCTIONS - API
***************************************************************************************************/
/***************************************************************************************************
* @fn HalLedInit
*
* @brief Initialize LED Service
*
* @param init - pointer to void that contains the initialized value
*
* @return None
***************************************************************************************************/
void HalLedInit (void)
{
#if (HAL_LED == TRUE)
/* Initialize all LEDs to OFF */
HalLedSet (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Initialize sleepActive to FALSE */
HalLedStatusControl.sleepActive = FALSE;
#endif
}
/***************************************************************************************************
* @fn HalLedSet
*
* @brief Tun ON/OFF/TOGGLE given LEDs
*
* @param led - bit mask value of leds to be turned ON/OFF/TOGGLE
* mode - BLINK, FLASH, TOGGLE, ON, OFF
* @return None
***************************************************************************************************/
uint8 HalLedSet (uint8 leds, uint8 mode)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
switch (mode)
{
case HAL_LED_MODE_BLINK:
/* Default blink, 1 time, D% duty cycle */
HalLedBlink (leds, 1, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_FLASH:
/* Default flash, N times, D% duty cycle */
HalLedBlink (leds, HAL_LED_DEFAULT_FLASH_COUNT, HAL_LED_DEFAULT_DUTY_CYCLE, HAL_LED_DEFAULT_FLASH_TIME);
break;
case HAL_LED_MODE_ON:
case HAL_LED_MODE_OFF:
case HAL_LED_MODE_TOGGLE:
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
if (mode != HAL_LED_MODE_TOGGLE)
{
sts->mode = mode; /* ON or OFF */
}
else
{
sts->mode ^= HAL_LED_MODE_ON; /* Toggle */
}
HalLedOnOff (led, sts->mode);
leds ^= led;
}
led <<= 1;
sts++;
}
break;
default:
break;
}
#elif (HAL_LED == TRUE)
LedOnOff(leds, mode);
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) mode;
#endif /* BLINK_LEDS && HAL_LED */
return ( HalLedState );
}
/***************************************************************************************************
* @fn HalLedBlink
*
* @brief Blink the leds
*
* @param leds - bit mask value of leds to be blinked
* numBlinks - number of blinks
* percent - the percentage in each period where the led
* will be on
* period - length of each cycle in milliseconds
*
* @return None
***************************************************************************************************/
void HalLedBlink (uint8 leds, uint8 numBlinks, uint8 percent, uint16 period)
{
#if (defined (BLINK_LEDS)) && (HAL_LED == TRUE)
uint8 led;
HalLedControl_t *sts;
if (leds && percent && period)
{
if (percent < 100)
{
led = HAL_LED_1;
leds &= HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
while (leds)
{
if (leds & led)
{
/* Store the current state of the led before going to blinking if not already blinking */
if(sts->mode < HAL_LED_MODE_BLINK )
preBlinkState |= (led & HalLedState);
sts->mode = HAL_LED_MODE_OFF; /* Stop previous blink */
sts->time = period; /* Time for one on/off cycle */
sts->onPct = percent; /* % of cycle LED is on */
sts->todo = numBlinks; /* Number of blink cycles */
if (!numBlinks) sts->mode |= HAL_LED_MODE_FLASH; /* Continuous */
sts->next = osal_GetSystemClock(); /* Start now */
sts->mode |= HAL_LED_MODE_BLINK; /* Enable blinking */
leds ^= led;
}
led <<= 1;
sts++;
}
osal_set_event (Hal_TaskID, HAL_LED_BLINK_EVENT);
}
else
{
HalLedSet (leds, HAL_LED_MODE_ON); /* >= 100%, turn on */
}
}
else
{
HalLedSet (leds, HAL_LED_MODE_OFF); /* No on time, turn off */
}
#elif (HAL_LED == TRUE)
percent = (leds & HalLedState) ? HAL_LED_MODE_OFF : HAL_LED_MODE_ON;
HalLedOnOff (leds, percent); /* Toggle */
#else
// HAL LED is disabled, suppress unused argument warnings
(void) leds;
(void) numBlinks;
(void) percent;
(void) period;
#endif /* BLINK_LEDS && HAL_LED */
}
#if (HAL_LED == TRUE)
/***************************************************************************************************
* @fn HalLedUpdate
*
* @brief Update leds to work with blink
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedUpdate (void)
{
uint8 led;
uint8 pct;
uint8 leds;
HalLedControl_t *sts;
uint32 time;
uint16 next;
uint16 wait;
next = 0;
led = HAL_LED_1;
leds = HAL_LED_ALL;
sts = HalLedStatusControl.HalLedControlTable;
/* Check if sleep is active or not */
if (!HalLedStatusControl.sleepActive)
{
while (leds)
{
if (leds & led)
{
if (sts->mode & HAL_LED_MODE_BLINK)
{
time = osal_GetSystemClock();
if (time >= sts->next)
{
if (sts->mode & HAL_LED_MODE_ON)
{
pct = 100 - sts->onPct; /* Percentage of cycle for off */
sts->mode &= ~HAL_LED_MODE_ON; /* Say it's not on */
HalLedOnOff (led, HAL_LED_MODE_OFF); /* Turn it off */
if (!(sts->mode & HAL_LED_MODE_FLASH))
{
sts->todo--; /* Not continuous, reduce count */
if (!sts->todo)
{
sts->mode ^= HAL_LED_MODE_BLINK; /* No more blinks */
}
}
}
else
{
pct = sts->onPct; /* Percentage of cycle for on */
sts->mode |= HAL_LED_MODE_ON; /* Say it's on */
HalLedOnOff (led, HAL_LED_MODE_ON); /* Turn it on */
}
if (sts->mode & HAL_LED_MODE_BLINK)
{
wait = (((uint32)pct * (uint32)sts->time) / 100);
sts->next = time + wait;
}
else
{
/* no more blink, no more wait */
wait = 0;
/* After blinking, set the LED back to the state before it blinks */
HalLedSet (led, ((preBlinkState & led)!=0)?HAL_LED_MODE_ON:HAL_LED_MODE_OFF);
/* Clear the saved bit */
preBlinkState &= (led ^ 0xFF);
}
}
else
{
wait = sts->next - time; /* Time left */
}
if (!next || ( wait && (wait < next) ))
{
next = wait;
}
}
leds ^= led;
}
led <<= 1;
sts++;
}
if (next)
{
osal_start_timerEx(Hal_TaskID, HAL_LED_BLINK_EVENT, next); /* Schedule event */
}
}
}
/***************************************************************************************************
* @fn HalLedOnOff
*
* @brief Turns specified LED ON or OFF
*
* @param leds - LED bit mask
* mode - LED_ON,LED_OFF,
*
* @return none
***************************************************************************************************/
void HalLedOnOff (uint8 leds, uint8 mode)
{
if (leds & HAL_LED_1)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED1();
}
else
{
HAL_TURN_OFF_LED1();
}
}
if (leds & HAL_LED_2)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED2();
}
else
{
HAL_TURN_OFF_LED2();
}
}
if (leds & HAL_LED_3)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED3();
}
else
{
HAL_TURN_OFF_LED3();
}
}
if (leds & HAL_LED_4)
{
if (mode == HAL_LED_MODE_ON)
{
HAL_TURN_ON_LED4();
}
else
{
HAL_TURN_OFF_LED4();
}
}
/* Remember current state */
if (mode)
{
HalLedState |= leds;
}
else
{
HalLedState &= (leds ^ 0xFF);
}
}
#endif /* HAL_LED */
/***************************************************************************************************
* @fn HalGetLedState
*
* @brief Dim LED2 - Dim (set level) of LED2
*
* @param none
*
* @return led state
***************************************************************************************************/
uint8 HalLedGetState ()
{
#if (HAL_LED == TRUE)
return HalLedState;
#else
return 0;
#endif
}
/***************************************************************************************************
* @fn HalLedEnterSleep
*
* @brief Store current LEDs state before sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedEnterSleep( void )
{
#ifdef BLINK_LEDS
/* Sleep ON */
HalLedStatusControl.sleepActive = TRUE;
#endif /* BLINK_LEDS */
#if (HAL_LED == TRUE)
/* Save the state of each led */
HalSleepLedState = 0;
HalSleepLedState |= HAL_STATE_LED1();
HalSleepLedState |= HAL_STATE_LED2() << 1;
HalSleepLedState |= HAL_STATE_LED3() << 2;
HalSleepLedState |= HAL_STATE_LED4() << 3;
/* TURN OFF all LEDs to save power */
HalLedOnOff (HAL_LED_ALL, HAL_LED_MODE_OFF);
#endif /* HAL_LED */
}
/***************************************************************************************************
* @fn HalLedExitSleep
*
* @brief Restore current LEDs state after sleep
*
* @param none
*
* @return none
***************************************************************************************************/
void HalLedExitSleep( void )
{
#if (HAL_LED == TRUE)
/* Load back the saved state */
HalLedOnOff(HalSleepLedState, HAL_LED_MODE_ON);
/* Restart - This takes care BLINKING LEDS */
HalLedUpdate();
#endif /* HAL_LED */
#ifdef BLINK_LEDS
/* Sleep OFF */
HalLedStatusControl.sleepActive = FALSE;
#endif /* BLINK_LEDS */
}
/***************************************************************************************************
***************************************************************************************************/

View File

@@ -0,0 +1,71 @@
/**************************************************************************************************
Filename: hal_mac_cfg.h
Revised: $Date: 2010-08-10 19:12:51 -0700 (Tue, 10 Aug 2010) $
Revision: $Revision: 23375 $
Description: Describe the purpose and contents of the file.
Copyright 2007-2009 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
#ifndef HAL_MAC_CFG_H
#define HAL_MAC_CFG_H
/*
* Board Configuration File for low-level MAC
* --------------------------------------------
* Manufacturer : Texas Instruments
* Part Number : CC2530EB
* Processor : Texas Instruments CC2530
*
*/
/* ------------------------------------------------------------------------------------------------
* Board Specific Configuration
* ------------------------------------------------------------------------------------------------
*/
#define HAL_MAC_RSSI_OFFSET -73 /* no units */
#if defined (HAL_PA_LNA)
/* CC22591 RSSI offset */
#define HAL_MAC_RSSI_LNA_HGM_OFFSET -9
#define HAL_MAC_RSSI_LNA_LGM_OFFSET 4
#elif defined (HAL_PA_LNA_CC2590)
/* CC22590 RSSI offset */
#define HAL_MAC_RSSI_LNA_HGM_OFFSET -10 /* TBD: place holder */
#define HAL_MAC_RSSI_LNA_LGM_OFFSET 0 /* TBD: place holder */
#endif
/**************************************************************************************************
*/
#endif

Some files were not shown because too many files have changed in this diff Show More