user3481085
user3481085

Reputation: 5

Randomizing Switch

How can I create a random loop for this code so that it does not do the same case all the time and also this is a function being called in to the main. Hope this helps a bit more i was just thinking of using the rand() function.

int escapeRoom()
{ 
    alt_u16 wheels;
    alt_u16 Bumper;
    int i;

        Bumper = IORD_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE);
        Bumper = rand() & (LEFT_FRONT_BUMPER | RIGHT_FRONT_BUMPER);   

       switch(Bumper)
        {
            case BOTH_BUMPERS:
            wheels = BACKWARDS;
            IOWR_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE, wheels);
            break;

            case RIGHT_FRONT_BUMPER:
            wheels = RIGHT_BACKWARDS;
            IOWR_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE, wheels);
            break;

            case LEFT_FRONT_BUMPER:
            wheels = LEFT_BACKWARDS;
            IOWR_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE, wheels);
            break;

            case NO_BUMPERS:
            wheels = FORWARD;
            IOWR_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE, wheels);
            break;

            for (i=1 ; i<5 ; i++) ;
            {
            IOWR_ALTERA_AVALON_PIO_DATA(EXPANSION_JP1_BASE, !wheels);
            }  
            break;

        }
}

Upvotes: 0

Views: 118

Answers (1)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5733

You need to make Bumper be random. e.g. using

Bumper = rand() & (LEFT_FRONT_BUMPER | RIGHT_FRONT_BUMPER);

Whether that particular statement is right for you depends on what you have in mind. For example, I don't know why you do an an initial read from the I/O port. If you need those bits, then you will need to keep them in some variable other than your random bumper.

Update: rand() can give the same pseudo-random sequence each time. This might be OK for a robot interacting with an uncertain environment; but in most applicatons you want a random seed. The easy option is to just call srand(some unpredictable value such as sensor data or a high-resolution timer). Always I am assuming that you don't Need high Quality randomness.

Upvotes: 1

Related Questions