AnsweredAssumed Answered

Erroneous result in arithmetic operations

Question asked by Guillermo Corrales on Mar 8, 2018
Latest reply on Mar 14, 2018 by Guillermo Corrales

Hi all,


I'm developing an application (PROJECT) for a STM8S208RB (128k flash) that was using around 100kB of flash and I have added recently a new library (LIBRARY) that has increased memory usage up yo 120kB of flash.


I had an issue because of this event that has been solved. More info in here: Section Boundary Crossing linker error  


In the new library I have a function that reads a frequency in Hz (IE: 208064) and then print it in MHz (IE: 208.064 Hz):

void disp_freq_mhz(void)
   uint32_t frequency;
   uint16_t mhz_num, khz_num;


   frequency = frequency_hz;                                                            // frequency_hz is a global variable (uint32_t)


   mhz_num = (uint16_t)(frequency/1000);                                       
   khz_num = (uint16_t)(frequency%1000);


   printf (" %03d.%03d MHz", mhz_num, khz_num);



The problem is sometimes the division and/or modulus operations returns an erroneous value.


I have been debugging this error with STVD in the following way:


  • Known that frequency_hz == 208064, I have added the following code after khz_num assignation:

mhz_num = (uint16_t)(frequency/1000);
khz_num = (uint16_t)(frequency%1000);


if(khz_num != 64 || mhz_num != 208)


  • I have placed a breakpoint in the  return; , so the execution stops when I get a bad division or modulus.
  • This is one reading of the variables involved in the function during one stop (the erroneous values are not always the same):

frequency_hz = 208064

frequency = 208064

mhz_num = 208              

khz_num = 872                          // sometimes it is 640, but most of the time the erroneous value is 872


Result of printf -> " 208.872 MHz "


Has anybody any idea of why is failing this arithmetic operations?


Thanks all of you in advance,