blog:2020-12-23_stm32f103_pseudo_random_number_generator



2020-12-23 STM32F103 Pseudo Random Number Generator

  • STM32F103 does no random number generator hardware but STM32F4 does
  • So, we need implement the random number generator by software

Solution

  • implement a pseudo random number generator
    int seed;
    seed = seed + 271828192;
    seed = seed * 314159;
  • give a initial value: 0xACE1u;
  • The implemented reference code like this:
    ...
    int random_number_seed = 0xACE1u; 
    ...
    int RND()
    {
      random_number_seed = random_number_seed + 271828192;
      random_number_seed = random_number_seed * 314159;
      return random_number_seed;
    }
  • but each time the random_number_seed will be initial,
  • It will cause that the same sequence each time I reset the chip:
    Random Number Test V0.01
    1457057135
    -973774463
    -1937705265
    79575585
    -1180197841
    -1988512063
    -1234805361
    ▒
    Random Number Test V0.01
    1457057135
    -973774463
    -1937705265
    79575585
    -1180197841
    -1988512063
    ▒
    Random Number Test V0.01
    1457057135
    -973774463
    -1937705265
    79575585
    -1180197841
  • I use __no_init __root before variables, variables will not init again if I reset system. It keep the values before reset.
  • Rewrite program as follows:
    ...
    __no_init __root int random_number_seed; // Do Not Assign Value
    ...
    void Initial_RandomNumberSeed()
    {
      // 初始化 Random Number Seed
       if (random_number_seed == 0) 
         random_number_seed = 0xACE1u;
    }
    ...
    int RND()
    {
      random_number_seed = random_number_seed + 271828192;
      random_number_seed = random_number_seed * 314159;
      return random_number_seed;
    }
  • Then, the output as follows:
    Random Number Test V0.01
    1457057135
    -973774463
    -1937705265
    79575585
    -1180197841
    -1988512063
    -1234805361
    ▒
    Random Number Test V0.01
    1171481418
    416394678
    ▒
    Random Number Test V0.01
    -1540031606
    829907318
    1596603338
    ▒
    Random Number Test V0.01
    -9376458
    1087120394
    Random Number Test V0.01
    1884639478
    -1529629622
    236686518
    -1130763126
    2065342582
    ▒
    Random Number Test V0.01
    1394068682
    1846119478
    283530506
    771706870
    1077839178
    -1905071178
    ▒
    Random Number Test V0.01
    284777866
    1799053174
    1552932298
    -1534088394
    -367327734
    -1694052618
    ▒
    Random Number Test V0.01
    844355146
    731368118
    -1550627190
    731487862

Reference

TAGS

  • 2 person(s) visited this page until now.

blog/2020-12-23_stm32f103_pseudo_random_number_generator.txt · Last modified: 2020/12/25 09:06 (external edit)