Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Random Time Delay in C

Status
Not open for further replies.

ninnymoggin

Newbie level 4
Newbie level 4
Joined
May 24, 2020
Messages
6
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Activity points
47
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; 
        }
    }    
}
 

what contoller compiler are you using?

1)your for() loop execute only once.

what is the rand() output range ?
in standard c it may be anything from 0 to 32k.

dividing by 5 , you may get a max of 6000 approx.
equivalent remainder of 2000(approx) seconds in your timedelay routine.

and you are conveting it into milliseconds and waiting for that time.
 
Last edited:

I'm using scons (is that a compiler, idk I'm a noooob).

I got rid of the for() loop in random() because I only want to generate one number, and set the range to 6 (I think) so it looks like this now:
Code:
int random() 
{ 
    int num; 
    num = rand() % 6; 
    return num;  
}

The code runs but there's no delay.
 

ok.scons is software construction tool -not a compiler.
which controller are you targetting and its compiler?
 

I don't know what you're asking me, could you try rephrasing it as if I were a five year old?
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top