Traffic lights

 

Now I'm having trouble with 'WHILEs' and 'IFs':

 

#include "mbed.h"

DigitalOut red(LED4);
DigitalOut yellow(LED3);
DigitalOut green(LED2);
DigitalOut w(LED1);
bool Peds;

int main() {
    Peds = rand();
    while(1){
        while(Peds == 1) {
            w = 1;
            if(red == 1) {
                wait(7.5);
                w = 0;
                Peds = rand();
            }
        }
        while(1) {
        red = 1;
        wait(12.3);
        red = 0;
        yellow = 1;
        wait(0.5);
        yellow = 0;
        green = 1;
        wait(20.3);
        green = 0;
        }
    }
}

Works in thery... I will (probably) make a text based version in c++.


1 comment

23 Dec 2009

C (C++) is a case-sensitive language so you need to remember that. E.g. it's "int", not "Int", and you have both "Peds" and "peds". Another gotcha coming from Pascal is that assignment is '=' and comparison is '=='.

rand() doesn't take a parameter in C. If you need a random 0 or 1, you can get it as the remainder of the value returned by rand(), e.g. "peds = rand()%1".  The "%" operator is equivalent to "mod" in Pascal.

Hope you'll make it work!

You need to log in to post a comment