This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Compiler/CC2541: CC2541

Part Number: CC2541

Tool/software: TI C/C++ Compiler

Hi All,

I have a Buzzer connected with CC2541 on P0_4 PIN and I want it to be turn ON after every 0.5 seconds using PWM. I managed the PWM.c and PWM.h and the buzzer is running continuously.

Regards,

Yatin Baluja  

  • I am afraid you need to give us some more details if we shall be able to help you.

    What hardware are you running on and what SW are you using?

    Is the problem that you are not able to get P0_4 to toggle every 500 ms or that your buzzer is not working as expected?

    Siri

  • Hi Siri,

    I'm using CC2541 with BLE Stack 1.5.1.1, I have a PWM pin P0_4 and the buzzer is connected to that pin. I Have led connected to pin P0_3 and the push button on P0_1 pin. 

    If I press push button, buzzer will turn on like ti_pwm_init(1000,50) and led will turn ON whereas buzzer will turn off after that but what's happening now is the buzzer remains ON always.

    Plus I want a minute gap, like buzzer will turn ON automatically after 1 minute then after 2 minutes and lastly after 3 minutes. After 3 minutes device will turn OFF automatically. 

    LED part is working fine but not the buzzer one. I have PWM.c and PWM.h file which I'm attaching here with simpleBLEPeripheral.c file

    Regards,

    Yatin Baluja 

    #include "pwm.h"
    #include "simpleBLEPeripheral.h"
    #include "hal_types.h"
    #include "hal_adc.h"
    #include "hal_led.h"
    #include "hal_key.h"
    #include "hal_lcd.h"
    
    bool device_start;
    uint16 count=0;            // For timer counting
    char flag=NONE;
    static uint16 scale =0;       
    static uint16 freq_period = 0;
    /***************************************************************
    UART_handle
    ****************************************************************/
    void ti_pwm_init(uint16 freq, uint8 Duty)
    {
        float j;
        T1IE = 0;
        P0DIR|= BV(4);  
        P0SEL|= BV(4);  
    
        PERCFG |= BV(4);     
        T1CTL  = 0x0e;      
        freq_period = 32000000L / 128 / freq;
        T1CC0H = freq_period/0xFF;
        T1CC0L = freq_period%0xFF;
      
        if(Duty>=1&&Duty<=99)
         {
          j=(float)freq_period/100*Duty;
          scale=(uint16)j;
          T1CC2H = scale/0xFF;
          T1CC2L = scale%0xFF;
          T1CCTL2 = 0x6c;     
         }
        else
        {
          P0SEL &=~BV(4);
          P0DIR |=BV(4);
          if(Duty==0)P0_4=1;
          else       P0_4=0;
        }
        
        T1CCTL0 = 0x4C;    
        TIMIF &= ~(1<<6);  
        T1IE = 1;          
        EA = 1;            
    }
    
    #pragma vector = T1_VECTOR
    __interrupt void t1_isr(void)
    {
      
    }
    
    8203.pwm.h
    /******************************************************************************
    
     @file  simpleBLEPeripheral.c
    
     @brief This file contains the Simple BLE Peripheral sample application for use
            with the CC2540 Bluetooth Low Energy Protocol Stack.
    
     Group: WCS, BTS
     Target Device: CC2540, CC2541
    
     ******************************************************************************
     
     Copyright (c) 2010-2016, 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.
    
     ******************************************************************************
     Release Name: ble_sdk_1.4.2.2
     Release Date: 2016-06-09 06:57:10
     *****************************************************************************/
    
    /*********************************************************************
     * INCLUDES
     */
    #include "string.h"
    #include "bcomdef.h"
    #include "OSAL.h"
    #include "OSAL_PwrMgr.h"
    #include "OnBoard.h"
    #include "hal_adc.h"
    #include "hal_led.h"
    #include "hal_key.h"
    #include "hal_lcd.h"
    #include "gatt.h"
    #include "hci.h"
    #include "gapgattserver.h"
    #include "gattservapp.h"
    #include "devinfoservice.h"
    #include "simpleGATTprofile.h"
    
    #if defined( CC2540_MINIDK )
      #include "simplekeys.h"
    #endif
    
    #include "peripheral.h"
    
    #include "gapbondmgr.h"
    
    #include "simpleBLEPeripheral.h"
    
    #if defined FEATURE_OAD
      #include "oad.h"
      #include "oad_target.h"
    #endif
       
    #include "Handle.h"
    /*********************************************************************
     * MACROS
     */
    
    /*********************************************************************
     * CONSTANTS
     */
    
    // How often to perform periodic event
    #define SBP_KEY_EVT_PERIOD                        500
    #define SBP_PERIODIC_EVT_PERIOD                   1000
    #define SBP_BLINK_EVT_PERIOD                      250
    
    // What is the advertising interval when device is discoverable (units of 625us, 160=100ms)
    #define DEFAULT_ADVERTISING_INTERVAL          4600
    
    // Limited discoverable mode advertises for 30.72s, and then stops
    // General discoverable mode advertises indefinitely
    
    #if defined ( CC2540_MINIDK )
    #define DEFAULT_DISCOVERABLE_MODE             GAP_ADTYPE_FLAGS_LIMITED
    #else
    #define DEFAULT_DISCOVERABLE_MODE             GAP_ADTYPE_FLAGS_GENERAL
    #endif  // defined ( CC2540_MINIDK )
    
    // Minimum connection interval (units of 1.25ms, 80=100ms) if automatic parameter update request is enabled
    #define DEFAULT_DESIRED_MIN_CONN_INTERVAL     400//80
    
    // Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic parameter update request is enabled
    #define DEFAULT_DESIRED_MAX_CONN_INTERVAL     4000//800
    
    // Slave latency to use if automatic parameter update request is enabled
    #define DEFAULT_DESIRED_SLAVE_LATENCY         0
    
    // Supervision timeout value (units of 10ms, 1000=10s) if automatic parameter update request is enabled
    #define DEFAULT_DESIRED_CONN_TIMEOUT          1000
    
    // Whether to enable automatic parameter update request when a connection is formed
    #define DEFAULT_ENABLE_UPDATE_REQUEST         TRUE
    
    // Connection Pause Peripheral time value (in seconds)
    #define DEFAULT_CONN_PAUSE_PERIPHERAL         6
    // buzzer_state values
    #define BUZZER_OFF                            0
    #define BUZZER_ON                             1
    // Company Identifier: Texas Instruments Inc. (13)
    #define TI_COMPANY_ID                         0x000D
    
    #define INVALID_CONNHANDLE                    0xFFFF
    
    // Length of bd addr as a string
    #define B_ADDR_STR_LEN                        15
    
    /*********************************************************************
     * TYPEDEFS
     */
    
    /*********************************************************************
     * GLOBAL VARIABLES
     */
    
    /*********************************************************************
     * EXTERNAL VARIABLES
     */
    
    /*********************************************************************
     * EXTERNAL FUNCTIONS
     */
    
    /*********************************************************************
     * LOCAL VARIABLES
     */
    //static uint8 simpleBLEPeripheral_TaskID;   // Task ID for internal task/event processing
    uint8 simpleBLEPeripheral_TaskID;   // Task ID for internal task/event processing
    
    static gaprole_States_t gapProfileState = GAPROLE_INIT;
    
    // GAP - SCAN RSP data (max size = 31 bytes)
    static uint8 scanRspData[] =
    {
      // complete name
      0x08,   // length of this data
      GAP_ADTYPE_LOCAL_NAME_COMPLETE,
      'P',   
      'O',  
      'W',   
      ' ',   
      'L',   
      'E',   
      'D',   
    
      // connection interval range
      0x05,   // length of this data
      GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE,
      LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),   // 100ms
      HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),
      LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),   // 1s
      HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),
    
      // Tx power level
      0x02,   // length of this data
      GAP_ADTYPE_POWER_LEVEL,
      0       // 0dBm
    };
    
    // GAP - Advertisement data (max size = 31 bytes, though this is
    // best kept short to conserve power while advertisting)
    static uint8 advertData[] =
    {
      // Flags; this sets the device to use limited discoverable
      // mode (advertises for 30 seconds at a time) instead of general
      // discoverable mode (advertises indefinitely)
      0x02,   // length of this data
      GAP_ADTYPE_FLAGS,
      DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED,
    
      // service UUID, to notify central devices what services are included
      // in this peripheral
      0x03,   // length of this data
      GAP_ADTYPE_16BIT_MORE,      // some of the UUID's, but not all
      LO_UINT16( SIMPLEPROFILE_SERV_UUID ),
      HI_UINT16( SIMPLEPROFILE_SERV_UUID ),
    
    };
    
    // GAP GATT Attributes
    static uint8 attDeviceName[GAP_DEVICE_NAME_LEN] = "POP LED";
    // Buzzer state
    static uint8 buzzer_state = BUZZER_OFF;
    static uint8 buzzer_beep_count = 0;
    
    /*********************************************************************
     * LOCAL FUNCTIONS
     */
    static void simpleBLEPeripheral_ProcessOSALMsg( osal_event_hdr_t *pMsg );
    static void simpleBLEPeripheral_ProcessGATTMsg( gattMsgEvent_t *pMsg );
    static void peripheralStateNotificationCB( gaprole_States_t newState );
    static void performPeriodicTask( void );
    static void simpleProfileChangeCB( uint8 paramID );
    
    #if !defined( CC2540_MINIDK )
    static void simpleBLEPeripheral_HandleKeys( uint8 shift, uint8 keys );
    #endif
    
    #if (defined HAL_LCD) && (HAL_LCD == TRUE)
    static char *bdAddr2Str ( uint8 *pAddr );
    #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
    /*********************************************************************
     * PROFILE CALLBACKS
     */
    
    // GAP Role Callbacks
    static gapRolesCBs_t simpleBLEPeripheral_PeripheralCBs =
    {
      peripheralStateNotificationCB,  // Profile State Change Callbacks
      NULL                            // When a valid RSSI is read from controller (not used by application)
    };
    
    // GAP Bond Manager Callbacks
    static gapBondCBs_t simpleBLEPeripheral_BondMgrCBs =
    {
      NULL,                     // Passcode callback (not used by application)
      NULL                      // Pairing / Bonding state Callback (not used by application)
    };
    
    // Simple GATT Profile Callbacks
    static simpleProfileCBs_t simpleBLEPeripheral_SimpleProfileCBs =
    {
      simpleProfileChangeCB    // Charactersitic value change callback
    };
    /*********************************************************************
     * PUBLIC FUNCTIONS
     */
    
    /*********************************************************************
     * @fn      SimpleBLEPeripheral_Init
     *
     * @brief   Initialization function for the Simple BLE Peripheral App Task.
     *          This is called during initialization and should contain
     *          any application specific initialization (ie. hardware
     *          initialization/setup, table initialization, power up
     *          notificaiton ... ).
     *
     * @param   task_id - the ID assigned by OSAL.  This ID should be
     *                    used to send messages and set timers.
     *
     * @return  none
     */
    void SimpleBLEPeripheral_Init( uint8 task_id )
    {
      simpleBLEPeripheral_TaskID = task_id;
    
      
      // Setup the GAP
      VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );
      
      // Setup the GAP Peripheral Role Profile
      {
        #if defined( CC2540_MINIDK )
          // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed
          uint8 initial_advertising_enable = FALSE;
        #else
          // For other hardware platforms, device starts advertising upon initialization
          uint8 initial_advertising_enable = TRUE;
        #endif
    
        // By setting this to zero, the device will go into the waiting state after
        // being discoverable for 30.72 second, and will not being advertising again
        // until the enabler is set back to TRUE
        uint16 gapRole_AdvertOffTime = 0;
    
        uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
        uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
        uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
        uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
        uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;
    
        // Set the GAP Role Parameters
        GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
        GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );
    
        GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData );
        GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );
    
        GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
        GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
        GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
        GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
        GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
      }
    
      // Set the GAP Characteristics
      GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );
    
      // Set advertising interval
      {
        uint16 advInt = DEFAULT_ADVERTISING_INTERVAL;
    
        GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt );
        GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt );
        GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt );
        GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt );
      }
    
      // Setup the GAP Bond Manager
      {
        uint32 passkey = 0; // passkey "000000"
        uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
        uint8 mitm = TRUE;
        uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
        uint8 bonding = TRUE;
        GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey );
        GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode );
        GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm );
        GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap );
        GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding );
      }
    
      // Initialize GATT attributes
      GGS_AddService( GATT_ALL_SERVICES );            // GAP
      GATTServApp_AddService( GATT_ALL_SERVICES );    // GATT attributes
      DevInfo_AddService();                           // Device Information Service
      SimpleProfile_AddService( GATT_ALL_SERVICES );  // Simple GATT Profile
    #if defined FEATURE_OAD
      VOID OADTarget_AddService();                    // OAD Profile
    #endif
    
      // Setup the SimpleProfile Characteristic Values
      {
        //uint8 charValue1 = 1;
        uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN]={7};
        uint8 charValue2 = 2;
        uint8 charValue3 = 3;
        //uint8 charValue3[SIMPLEPROFILE_CHAR3_LEN]={7};
        uint8 charValue4 = 4;
        uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 };
        //SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, sizeof ( uint8 ), &charValue1 );
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 );
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &charValue2 );
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 );
        //SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, SIMPLEPROFILE_CHAR3_LEN, charValue3 );
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 );
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 );
      }
    
    
    //#if defined( CC2540_MINIDK )
    
      //SK_AddService( GATT_ALL_SERVICES ); // Simple Keys Profile
    
      // Register for all key events - This app will handle all key events
      //RegisterForKeys( simpleBLEPeripheral_TaskID );
    
      
      // For keyfob board set GPIO pins into a power-optimized state
      // Note that there is still some leakage current from the buzzer,
      // accelerometer, LEDs, and buttons on the PCB.
    
      P0SEL = 0; // Configure Port 0 as GPIO
      P1SEL = 0; // Configure Port 1 as GPIO
      P2SEL = 0; // Configure Port 2 as GPIO
    
      P0DIR = 0x1F;               
      P1DIR = 0xDE;                
      P2DIR = 0xFE; 
    
      //P0 = 0x00; // All pins on port 0 to low 
      //P1 = 0x0E;   // All pins on port 1 to low
      //P2 = 0x00;   // All pins on port 2 to low
      PWM = 0;
      //POWER = 0;
      R_LED = 1;
      CHARGE_LED = 1;
      MUSIC_DAT = 1;
      //end
      
      /*EN = 1;
      for(int i=0;i<10000;i++);
      LED_Blink();
     // EN = 0;
     */
    //#endif // #if defined( CC2540_MINIDK )
    
    #if (defined HAL_LCD) && (HAL_LCD == TRUE)
    
    #if defined FEATURE_OAD
      #if defined (HAL_IMAGE_A)
        HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
      #else
        HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
      #endif // HAL_IMAGE_A
    #else
      HalLcdWriteString( "BLE Peripheral", HAL_LCD_LINE_1 );
    #endif // FEATURE_OAD
    
    #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
      
      // Register callback with SimpleGATTprofile
      VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs );
    
      // Enable clock divide on halt
      // This reduces active current while radio is active and CC254x MCU
      // is halted
     // HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT );
      HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_DISABLE_CLK_DIVIDE_ON_HALT );
    
    #if defined ( DC_DC_P0_7 )
    
      // Enable stack to toggle bypass control on TPS62730 (DC/DC converter)
      HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 );
    
    #endif // defined ( DC_DC_P0_7 )
    
      // Setup a delayed profile startup
      osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT );  
    }
    
    /*********************************************************************
     * @fn      SimpleBLEPeripheral_ProcessEvent
     *
     * @brief   Simple BLE Peripheral Application Task event processor.  This function
     *          is called to process all events for the task.  Events
     *          include timers, messages and any other user defined events.
     *
     * @param   task_id  - The OSAL assigned task ID.
     * @param   events - events to process.  This is a bit map and can
     *                   contain more than one event.
     *
     * @return  events not processed
     */
    static uint8 event=1;
    uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
    {
    
      VOID task_id; // OSAL required parameter that isn't used in this function
      static int count=0;
    
      if ( events & SYS_EVENT_MSG )
      {
        uint8 *pMsg;
    
        if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
        {
          simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
    
          // Release the OSAL message
          VOID osal_msg_deallocate( pMsg );
        }
    
        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
      }
    
      if ( events & SBP_START_DEVICE_EVT )
      {
        key_dptr = 0;
        pinInit();   
        //device_start_stop = DEVICE_START;
        
        // Start the Device
        VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );
    
        // Start Bond Manager
        VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );
    
        // Set timer for first periodic event
       // osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_KEY_EVT, SBP_KEY_EVT_PERIOD );
        osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
        return ( events ^ SBP_START_DEVICE_EVT );
      }
      
      //Key Event
      if ( events & SBP_KEY_EVT ) // Key Press Event
      {
         key_dptr++;
         if((key_dptr >= 2) && (device_start_stop == DEVICE_STOP))
         {  
             if(KEY == KEY_LOW)
             {
               //POWER = 1;
               key_dptr = 0; 
               device_start_stop = DEVICE_START;
               //led_mode = LED_MODE_OFF; // Led in off  mode, default condition
               PWM = 1;
               R_LED = 0;
               Indicative_voice(1);            //Boot Sound
               ti_pwm_init(1000,50);
               timer3Init();
               osal_set_event( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT ); 
               //osal_set_event( simpleBLEPeripheral_TaskID, SBP_BLINK_EVT ); 
               return (events ^ SBP_KEY_EVT);  
             }
         }
         else if((key_dptr >= 2) && (device_start_stop == DEVICE_START))
         { 
             if(KEY == KEY_LOW)
             {
                 PWM = 0;
                 R_LED = 1;
                 CHARGE_LED = 1;
                 Indicative_voice(2);
                  Indicative_voice(0);
                 //ti_pwm_init(1000,50);
               //  ti_pwm_init(0);
                 //POWER = 0;
                 key_dptr = 0;
                 device_start_stop = DEVICE_STOP;
                 //led_mode = LED_MODE_OFF; // Led in off  mode, default condition
                 osal_set_event( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT );  
                 return (events ^ SBP_KEY_EVT);  
             }
         }
         /*else if((key_dptr >= 1) && (KEY == KEY_HIGH) && (device_start_stop == DEVICE_START) && ((led_mode == LED_MODE_OFF) || (led_mode == LED_MODE_HIGH)))
         { 
               key_dptr = 0;
               led_mode = LED_MODE_LOW; // Led in low  mode
               osal_set_event( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT );  
               return (events ^ SBP_KEY_EVT);  
         }
         else if((key_dptr >=1) && (KEY == KEY_HIGH) && (device_start_stop == DEVICE_START) && (led_mode == LED_MODE_LOW) )
         {
               key_dptr = 0;
               led_mode = LED_MODE_HIGH; // Led in high  mode    
               osal_set_event( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT );  
               return (events ^ SBP_KEY_EVT);  
         }
         else 
             key_pressed = KEY_PRESS_NO;
        */
         
      
        osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_KEY_EVT, SBP_KEY_EVT_PERIOD );   
        return (events ^ SBP_KEY_EVT);        
      }
      
      //Periodic Event
      if ( events & SBP_PERIODIC_EVT )
      {
          if(BAT_CHARG == 0) // if battery charging is going ON
          {
              CHARGE_LED = 0; // turn on charging LED, Actie low
          }
          else
          {
              CHARGE_LED = 1; // turn off charging LED, Actie high
          }
          
          IEN2 |= 0x10;
          //EA = 1;
          
          if(sound_flag == MIN_1_SOUND){          
              if(!count){
                  Indicative_voice(3);
              //  ti_pwm_init(1000,50);
                  count++;
              }
              else if(count==1){
                    Indicative_voice(0);
             //   ti_pwm_init(0);
                sound_flag = NONE;
                count=0;
              }
          }
          else if(sound_flag == MIN_2_SOUND){        
              if(!count){
                Indicative_voice(3);
             //   ti_pwm_init(1000,50);
                while(WIN_BUSY==0);  
                count++;
              }
              else if(count==1){
                Indicative_voice(3);
                //ti_pwm_init(1000,50);
                count++;
              }
              else if(count==2){
                Indicative_voice(0);
            //    ti_pwm_init(0);
                count=0;
                sound_flag = NONE;
              }
          }
          else if(sound_flag == MIN_3_SOUND){
              if(!count){
                Indicative_voice(3);
              //  ti_pwm_init(1000,50);
                while(WIN_BUSY==0);  
                count++;
              }
              else if(count==1){
                Indicative_voice(3);
            //    ti_pwm_init(1000,50);
                while(WIN_BUSY==0);  
                count++;
              }
              else if(count==2){
                Indicative_voice(3);
            //    ti_pwm_init(1000,50);
                while(WIN_BUSY==0);  
                count++;
              }
              else if(count==3){
               Indicative_voice(2);
             //   ti_pwm_init(1000,50);
                while(WIN_BUSY==0); 
                count++;
              }
              else if(count==4){
                count=0;
                sound_flag = NONE;
                time_data  = 0;
                PWM = 0;
                R_LED = 1;
                CHARGE_LED = 1;
                Indicative_voice(0);
             //   ti_pwm_init(0);
                //POWER = 0;
              }
          }
          osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
          return (events ^ SBP_PERIODIC_EVT);        
      }  
    
      // Discard unknown events
      return 0;
    }
    
    void ProcessBLECommands(uint8 command)
    {
            if((command == 0) && (device_start_stop == DEVICE_START))  
            {   
               LED = 1;
               LED_1 = 0;
               Indicative_voice(3);
               Indicative_voice(0);
             //  ti_pwm_init(1000,50);
              // ti_pwm_init(0);
            }
            else if ((command == 1) && (device_start_stop == DEVICE_START)) 
            {
              LED = 0;
              LED_1 = 1;
              Indicative_voice(0);
              //ti_pwm_init(0);
            }
            else if ((command == 2) && (device_start_stop == DEVICE_START)) 
            {
               
               LED = 0;
               PWM = 0;
               LED_1 = 0;
               LED_2 = 0;
               MUSIC_DAT =0;
               CHARGE_LED =0;
               R_LED = 0;
               Indicative_voice(0);
               //ti_pwm_init(0);
               //POWER = 0;
            }
    }
    /*********************************************************************
     * @fn      simpleBLEPeripheral_ProcessOSALMsg
     *
     * @brief   Process an incoming task message.
     *
     * @param   pMsg - message to process
     *
     * @return  none
     */
    static void simpleBLEPeripheral_ProcessOSALMsg( osal_event_hdr_t *pMsg )
    {
      switch ( pMsg->event )
      {     
      #if !defined( CC2540_MINIDK )
        case KEY_CHANGE:
          simpleBLEPeripheral_HandleKeys( ((keyChange_t *)pMsg)->state, 
                                          ((keyChange_t *)pMsg)->keys );
          break;
      #endif // #if defined( CC2540_MINIDK )
     
        case GATT_MSG_EVENT:
          // Process GATT message
          simpleBLEPeripheral_ProcessGATTMsg( (gattMsgEvent_t *)pMsg );
          break;
          
        default:
          // do nothing
          break;
      }
    }
    
    #if !defined( CC2540_MINIDK )
    /*********************************************************************
     * @fn      simpleBLEPeripheral_HandleKeys
     *
     * @brief   Handles all key events for this device.
     *
     * @param   shift - true if in shift/alt.
     * @param   keys - bit field for key events. Valid entries:
     *                 HAL_KEY_SW_2
     *                 HAL_KEY_SW_1
     *
     * @return  none
     */
    static void simpleBLEPeripheral_HandleKeys( uint8 shift, uint8 keys )
    {
      uint8 SK_Keys = 0;
       VOID shift;  // Intentionally unreferenced parameter
    
      if ( keys & HAL_KEY_SW_6 )
      {
        SK_Keys |= HAL_KEY_SW_6;
      }
    
      if ( keys & HAL_KEY_SW_7 )
      {
        SK_Keys |= HAL_KEY_SW_7;
      }
    
      // Set the value of the keys state to the Simple Keys Profile;
      // This will send out a notification of the keys state if enabled
     // SK_SetParameter( SK_KEY_ATTR, sizeof ( uint8 ), &SK_Keys );
    }
    #endif // #if !defined( CC2540_MINIDK )
    
    /*********************************************************************
     * @fn      simpleBLEPeripheral_ProcessGATTMsg
     *
     * @brief   Process GATT messages
     *
     * @return  none
     */
    static void simpleBLEPeripheral_ProcessGATTMsg( gattMsgEvent_t *pMsg )
    {  
      GATT_bm_free( &pMsg->msg, pMsg->method );
    }
    
    /*********************************************************************
     * @fn      peripheralStateNotificationCB
     *
     * @brief   Notification from the profile of a state change.
     *
     * @param   newState - new state
     *
     * @return  none
     */
    static void peripheralStateNotificationCB( gaprole_States_t newState )
    {
    #ifdef PLUS_BROADCASTER
      static uint8 first_conn_flag = 0;
    #endif // PLUS_BROADCASTER
      
      
      switch ( newState )
      {
        case GAPROLE_STARTED:
          {
            uint8 ownAddress[B_ADDR_LEN];
            uint8 systemId[DEVINFO_SYSTEM_ID_LEN];
    
            GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);
    
            // use 6 bytes of device address for 8 bytes of system ID value
            systemId[0] = ownAddress[0];
            systemId[1] = ownAddress[1];
            systemId[2] = ownAddress[2];
    
            // set middle bytes to zero
            systemId[4] = 0x00;
            systemId[3] = 0x00;
    
            // shift three bytes up
            systemId[7] = ownAddress[5];
            systemId[6] = ownAddress[4];
            systemId[5] = ownAddress[3];
    
            DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
    
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              // Display device address
              HalLcdWriteString( bdAddr2Str( ownAddress ),  HAL_LCD_LINE_2 );
              HalLcdWriteString( "Initialized",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
          }
          break;
    
        case GAPROLE_ADVERTISING:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Advertising",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
          }
          break;
    
    #ifdef PLUS_BROADCASTER   
        /* After a connection is dropped a device in PLUS_BROADCASTER will continue
         * sending non-connectable advertisements and shall sending this change of 
         * state to the application.  These are then disabled here so that sending 
         * connectable advertisements can resume.
         */
        case GAPROLE_ADVERTISING_NONCONN:
          {
            uint8 advertEnabled = FALSE;
          
            // Disable non-connectable advertising.
            GAPRole_SetParameter(GAPROLE_ADV_NONCONN_ENABLED, sizeof(uint8),
                               &advertEnabled);
            
            // Reset flag for next connection.
            first_conn_flag = 0;
          }
          break;
    #endif //PLUS_BROADCASTER         
          
        case GAPROLE_CONNECTED:
          {        
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Connected",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
              
    #ifdef PLUS_BROADCASTER
            // Only turn advertising on for this state when we first connect
            // otherwise, when we go from connected_advertising back to this state
            // we will be turning advertising back on.
            if ( first_conn_flag == 0 ) 
            {
                uint8 advertEnabled = FALSE; // Turn on Advertising
    
                // Disable connectable advertising.
                GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8),
                                     &advertEnabled);
                
                // Set to true for non-connectabel advertising.
                advertEnabled = TRUE;
                
                // Enable non-connectable advertising.
                GAPRole_SetParameter(GAPROLE_ADV_NONCONN_ENABLED, sizeof(uint8),
                                     &advertEnabled);
                
                first_conn_flag = 1;
            }
    #endif // PLUS_BROADCASTER
          }
          break;
    
        case GAPROLE_CONNECTED_ADV:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Connected Advertising",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
          }
          break;      
        case GAPROLE_WAITING:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Disconnected",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
              
    #ifdef PLUS_BROADCASTER                
            uint8 advertEnabled = TRUE;
          
            // Enabled connectable advertising.
            GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8),
                                 &advertEnabled);
    #endif //PLUS_BROADCASTER
          }
          break;
    
        case GAPROLE_WAITING_AFTER_TIMEOUT:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Timed Out",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
              
    #ifdef PLUS_BROADCASTER
            // Reset flag for next connection.
            first_conn_flag = 0;
    #endif //#ifdef (PLUS_BROADCASTER)
          }
          break;
    
        case GAPROLE_ERROR:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "Error",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
          }
          break;
    
        default:
          {
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteString( "",  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
          }
          break;
    
      }
    
      gapProfileState = newState;
    
    #if !defined( CC2540_MINIDK )
      VOID gapProfileState;     // added to prevent compiler warning with
                                // "CC2540 Slave" configurations
    #endif
    
    
    }
    
    /*********************************************************************
     * @fn      performPeriodicTask
     *
     * @brief   Perform a periodic application task. This function gets
     *          called every five seconds as a result of the SBP_PERIODIC_EVT
     *          OSAL event. In this example, the value of the third
     *          characteristic in the SimpleGATTProfile service is retrieved
     *          from the profile, and then copied into the value of the
     *          the fourth characteristic.
     *
     * @param   none
     *
     * @return  none
     */
    static void performPeriodicTask( void )
    {
      uint8 valueToCopy;
      uint8 stat;
    
      // Call to retrieve the value of the first characteristic in the profile
      stat = SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, &valueToCopy);
    
      if( stat == SUCCESS )
      {
        /*
         * Call to set that value of the fourth characteristic in the profile. Note
         * that if notifications of the fourth characteristic have been enabled by
         * a GATT client device, then a notification will be sent every time this
         * function is called.
         */
        SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof(uint8), &valueToCopy);
      }
    }
    
    /*********************************************************************
     * @fn      simpleProfileChangeCB
     *
     * @brief   Callback from SimpleBLEProfile indicating a value change
     *
     * @param   paramID - parameter ID of the value that was changed.
     *
     * @return  none
     */
    static void simpleProfileChangeCB( uint8 paramID )
    {
      //uint8 newValue[21];
      uint8 newValue;
      uint8 Data[SIMPLEPROFILE_CHAR1_LEN+1]={0};
      
      switch( paramID )
      {
        case SIMPLEPROFILE_CHAR3:
            SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue );
            //lvalRed = newValue << 4;
            #if (defined HAL_LCD) && (HAL_LCD == TRUE)
              HalLcdWriteStringValue( "Char 3:", (uint16)(newValue), 10,  HAL_LCD_LINE_3 );
            #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
    
            break;
    
        case SIMPLEPROFILE_CHAR1:
            //SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR3, &newValue );     
            SimpleProfile_GetParameter( SIMPLEPROFILE_CHAR1, Data );
             if(strstr(Data,LED1_ON)) // LED ON command
                ProcessBLECommands(0);
            else if(strstr(Data,LED1_OFF)) // LED OFF command
                ProcessBLECommands(1);
            else if(strstr(Data,DEVICE_OFF)) // Device OFF command
                ProcessBLECommands(2);
            
         
          break;
    
        default:
          // should not reach here!
          break;
      }
       
    }
    
    #if (defined HAL_LCD) && (HAL_LCD == TRUE)
    /*********************************************************************
     * @fn      bdAddr2Str
     *
     * @brief   Convert Bluetooth address to string. Only needed when
     *          LCD display is used.
     *
     * @return  none
     */
    char *bdAddr2Str( uint8 *pAddr )
    {
      uint8       i;
      char        hex[] = "0123456789ABCDEF";
      static char str[B_ADDR_STR_LEN];
      char        *pStr = str;
    
      *pStr++ = '0';
      *pStr++ = 'x';
    
      // Start from end of addr
      pAddr += B_ADDR_LEN;
    
      for ( i = B_ADDR_LEN; i > 0; i-- )
      {
        *pStr++ = hex[*--pAddr >> 4];
        *pStr++ = hex[*pAddr & 0x0F];
      }
    
      *pStr = 0;
    
      return str;
    }
    #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
    
    
    
    /*********************************************************************
    *********************************************************************/
    

  • Like after 1 or 2 or 3 minutes buzzer will turn ON for 0.5 seconds

  • Hi Yatin,

    I'm not familiar with the API you listed ( ti_pwm_init), can you link me the documentation for this one?

  • Hi Yatin,

    The linked PWM driver is intended for CC13x2/CC26x2 devices, not CC2541.

    You can search on this forum for alternative ways of implementing PWM on CC2541.

  • Hi Marie,

    Thanks for the reply. I have a quick question, how to set the 0.5 sec timer in PWM where after the timer PWM will turn OFF.

    Regards,

    Yatin Baluja 

  • Hi Yatin,

    See e.g. this post for a code example (using timer 4):