Programming variables

23 Dec 2009 . Edited: 23 Dec 2009

<DR.Palmers son is the one who is writing this.>

Hi,

I have been making a traffic light system, but I need to add an integer which will be used to define if there is a pedestrian trying to cross the 'road'.

This would use a random, wich is also not included in the mbed standard library. Does anyone know which librarys I could use?

N Palmer.

 

Code: http://mbed.org/users/DrPalmer/notebook/traffic-lights/

23 Dec 2009

rand() and srand() are included in the CRT used by mbed's online compiler.

printf("rand: %d\n", rand());

23 Dec 2009 . Edited: 23 Dec 2009

Where can I get that library?

Thx,

N

23 Dec 2009

It's standard, you don't need to "get" it anywhere...

23 Dec 2009

Looking at your code you've currently got the following line:

Peds = rand(1);

In C the rand() function doesn't accept any parameters, if you wish to define a maximum value then you can do so via the modulus operator (this determines the remainder after integer devision between any two given numbers), so for example if you want rand() to produce either 0 or 1 you can do:

Peds = rand() % 2;
As the remainder after dividing any number by 2 will either be 0 (it was a multiple of 2, i.e. an even number) or 1 (it was an odd number).

rand() only produces pseudo-random numbers, so if you use rand() on its own you'll always get the same sequence of random numbers each time you run the program, to add a little more "randomness" to your program you can use the srand() command to "seed" the random number generator. For example you might pass the current time to srand() so a different random sequence will be generated for each second. You'd perform the same tasks as before, only you'd run srand() first, e.g.:

srand(somevalue);
Peds = rand() % 2;

Hope that helps,

Mike.

23 Dec 2009

Another small note on your code, with your if and while statements you currently have lines like this:

if(Peds = 1) {
In C a single "=" sign is the "assignment operator", i.e. it changes the value of the thing on the left hand side to have the value of the item on the right hand side. For testing to see if something has a certain value you'll need the "equality operator", which is "==". Otherwise your code would currently set Peds to equal 1 when it reaches that if statement rather than testing to see if it's equal to 1. So you want:

if (Peds == 1)
And the same holds true for any while statements as well (or anywhere else you're testing the value of something).

Cheers,

Mike.

23 Dec 2009

Thanks a tonne!