This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

How to use _WFI and WFE to enter idle mode

Hi all: To saving power I implement the function to read data after interrupt is triggered..

below are my codes.. My expectation is..

Let CPU enter idle mode to wait interrupt by call _WFI() After interrupt is triggered start to read data and call _WFE() to save power. After read out 100 datas, CPU enter idle mode to wait interrupt triggered again...

However, the function of LIS3DH_ReadOutZYX(XYZ_Data) is always called even there is no any interrupt is triggered. How can I revise my code to meet my requirements? Thanks..

int main(void)
{
  BSP_Init();

  static bool bPoweSaving = true;


    int16_t         XYZ_Data[3]={0};

    uint8_t reg = 0;
    ret_code_t err_code;
    static int i = 0;

     
    while(true)
    {
     
        /* Start transaction with a slave with the specified address. */
     if( bPoweSaving)
     {
       __WFI();
       
     }
     else
     {
     
       __WFE();
     }
     bPoweSaving = false;
     err_code = LIS3DH_ReadOutZYX(XYZ_Data);  
    }
     i ++; 
     if (i > 100)
       bPoweSaving = true;
 
}
  • You still have a race condition when you use bPoweSaving with __WFI. Please read Anders comment here Because you are using WFI and the flag in the same context, I think it is ok but i see something wrong in you code.

    I also do not understand your while state, since it will not allow the bPoweSaving to be set to true ever as while loop will never end

    int main(void)
    {
      BSP_Init();
    
      static bool bPoweSaving = false;
    
    
        int16_t         XYZ_Data[3]={0};
    
        uint8_t reg = 0;
        ret_code_t err_code;
        static int i = 0;
    
    
        while(true)
        {
    
            /* Start transaction with a slave with the specified address. */
         if( bPoweSaving)
         {
           bPoweSaving = false;
           __WFI();
    
         }
         else
         {
           __WFE();
         }
    
         err_code = LIS3DH_ReadOutZYX(XYZ_Data);  
         
         if (i++ > 100)
         {
           i = 0;  
           bPoweSaving = true;
         }
        }
    
    }
    

    This above code will first sleep on WFI on every 100th reads and sleeps on WFE before 0 to 99 reads.

Related