fsl_pwm integer conversion failure?

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

fsl_pwm integer conversion failure?

581 Views
choix361
Contributor II

The processor is RT1064.

Release Name: MCUXpresso Software Development Kit (SDK)
Release Version: 25.12.00

In fsl_pwm.c line 790,

pulseCnt = pulseEndCnt - base->SM[subModuleSync].INIT + 1U;

Each term is uint16_t.

 

When pulseEndCnt < base->SM[subModuleSync].INIT, the result can be negative as int32_t. pulseCnt(uint16_t) will take the result and upper two bytes would be truncated. What would be the proper casting to keep the intention?

 

 

0 Kudos
Reply
3 Replies

554 Views
mayliu1
NXP Employee
NXP Employee

Hi @choix361 ,

Thank you so much for your interest in our products and for using our community.

 

Please notes that RT1064 eFlexPWM count-related registers are defined as signed 16-bit values.

1.png

I suggest you can try to do the arithmetic in int32_t , and only then convert to uint16_t after range checking.

int32_t pulseCntCalc = (int32_t)(int16_t)pulseEndCnt - (int32_t)(int16_t)base->SM[subModuleSync].INIT + 1;

 

if(( pulseCntCalc < 0) || (pulseCntCalc > UINT16_MAX))

{

// you can print log and handle invalid range

}

else

{

pulseCnt = (uint16_t)pulseCntCalc;

}

Wish it helps you

Best Regards

MayLiu

0 Kudos
Reply

538 Views
choix361
Contributor II

if(( pulseCntCalc < 0) || (pulseCntCalc > UINT16_MAX))

{

    // you can print log and handle invalid range

}

 

I saw many cases fall into if statement. Is it ok to intentionally truncate the data here?

Or set PulseCnt to certain fixed value?

if((pulseCntCalc < 0) || (pulseCntCalc > UINT16_MAX))
{
    //Intentionally truncate data
    pulseCntCalc = pulseCntCalc & 0x0000FFFF;
    pulseCnt = (uint16_t)pulseCntCalc;
}

0 Kudos
Reply

414 Views
mayliu1
NXP Employee
NXP Employee
I don’t recommend truncating the value. It’s better to first identify the root cause of why it exceeds the valid range.
0 Kudos
Reply