Skip to main content
Associate III
May 1, 2024
Solved

rand()

  • May 1, 2024
  • 8 replies
  • 4067 views

Hi,

I want to use random number.

But, the same random number is generated each time it is run.

When I debug the code below, W change with the same pattern every time I debug.

 

What's the problem and is there any solution to make random number which is not depend on the order? 

 

 

/* USER CODE BEGIN 0 */

double uniform_rand(){

return (double)rand()/((double)RAND_MAX + 1);

}

/* USER CODE END 0 */

 

 

int main(void) {

/* USER CODE BEGIN 2 */

srand(time(NULL));

/* USER CODE END 2 */

 

while {

W = uniform_rand();

}

}

This topic has been closed for replies.
Best answer by mƎALLEm

I'm using 2 kinds of board for i2c.

One is U575ZI-Q for master and the other is L432KC for slave.


Hello,

The two devices feature RNG (random number generator) as shown in their respective DS:

SofLit_0-1714645265840.png

You can inspire from one of the examples of RNG. Example:

https://github.com/STMicroelectronics/STM32CubeL4/tree/master/Projects/NUCLEO-L432KC/Examples/RNG/RNG_MultiRNG

8 replies

mƎALLEm
ST Technical Moderator
May 1, 2024

Hello,

What product you're using so you can use RNG peripheral instead of that "rand" library?

To give better visibility on the answered topics, please click "Best answer" on the reply which solved your issue or answered your question.
eunniAuthor
Associate III
May 1, 2024

sorry but I can't understand what you're saying...

isn't it "rand" library?

 

srand(time(NULL));

mƎALLEm
ST Technical Moderator
May 1, 2024

rand() from stdlib.h

What MCU part number are you using?

To give better visibility on the answered topics, please click "Best answer" on the reply which solved your issue or answered your question.
Tesla DeLorean
Guru
May 1, 2024

Need to seed it better.

Is there a clock or anything behind time() ? There'd need to be some association with the RTC and it would need to be running.

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
eunniAuthor
Associate III
May 2, 2024

I didn't use anything according to the clock.

Is there any recommandation to make better seed?

 

srand(time(NULL)); <----------- I think it change seed every single second

Tesla DeLorean
Guru
May 2, 2024

That supposes time() is working and there's anything making it tick.

In embedded you'd actually need to facilitate this.

You should confirm that it is working as you imagine.

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..