# Thread: Random Time Delay

1. ## Random Time Delay

I want to put a delay in my code to wait for a random number of seconds before going forward. I'm new to C and coding in general so I tried to patch together two example functions I found (random and delay), but so far it's not working. This is what I have so far:

Code:
```// generate a random number between 1 and 5
int random()
{
int i;
for (i = 0; i < 1; i++) {
int num = (rand() %
(5 - 1 + 1)) + 1;
return num;
}
}

//wait x number of seconds
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;

// Storing start time
clock_t start_time = clock();

// looping till required time is not achieved
while (clock() < start_time + milli_seconds);
}

main(void) {
init_elecanisms();

while (1) {
if (start==0){
int t = random();       //t=random number betwen 1 and 5
delay(t);               //delay for random number of seconds
led = ON;
LED2 = (p1 == 0) ? ON : OFF;
l1 = (SW3 == 0) ? ON : OFF;
}
}
}```

2. [QUOTE=ninnymoggin;1296135]I want to put a delay in my code to wait for a random number of seconds before going forward. I'm new to C and coding in general so I tried to patch together two example functions I found (random and delay), but so far it's not working. This is what I have so far:

Code:
```// generate a random number between 1 and 5
int random()
{
int i;
for (i = 0; i < 1; i++) {
int num = (rand() %
(5 - 1 + 1)) + 1;
return num;
}
}```
strange random() function. If you want a random number on 1-5,
just take (rand() % 5) + 1.

Code:
```//wait x number of seconds
void delay(int number_of_seconds)
{
// Converting time into milli_seconds
int milli_seconds = 1000 * number_of_seconds;

// Storing start time
clock_t start_time = clock();

// looping till required time is not achieved
while (clock() < start_time + milli_seconds);
}```
THis is called busy idling. You sometimes need to do it. Fundamentally this code is correct, but the clock doesn't always tick
in milliseconds. You need to use the constant CLK_TCK to
get clock ticks per second.
However it's better to use the system-defined Sleep() or
usleep() function if you want to idle for a set period. It's not
ANSI C, but it's provided for this purpose, and will almost certainly
exist in some form on your particular platform.

Popular pages Recent additions