Topics within this section include:

Efficiently Timing Out

In a complex protocol where many events occur in rapid sequence (such as bytes coming in through the serial port), there may be a need to time out when there is a gap of duration M milliseconds between bytes. The typical approach is to reset the countdown timer for every byte to M milliseconds into the future. Of course, this approach can be very inefficient.

A better way is to set the countdown timer M milliseconds into the future, and simply let it run to expiration. When it expires, check if the maximum of M milliseconds has elasped since the last byte. If not, reset the timer for only the remaining allowable period. The trick is to keep track of when the last byte was received. So do something like this:

At start:

// Set the initial timeout timer.
SetTimer(M)

Received character:

// Make note of when the character was received.
LastRxByteTime = ReadTime()

On timer expiry:

if (LastRxByteTime - ReadTime() > M){
// It has been interval M. Timeout applies.
do timeout handling
}else{
// If no further bytes are received, set timer
// to expire when the timeout would occur.
SetTimer(M - (LastRxByteTime - ReadTime())
}

Random Numbers

Random number can be generated by using the srand() and rand() functions with the BlackBerry TIME structure. The code fragment below details how to create random numbers:

#include "pager.h"
#include "ribbon.h"

// Initialization
int AppStackSize = 2048;
char VersionPtr[] = "RandomNumbers";
// Main entry point
void PagerMain(void) {
MESSAGE msg;
// The TIME structure stores the local
// time of the device.
TIME t;

// Register Application with Ribbon
RibbonRegisterApplication(VersionPtr, NULL, 0, 20);

// Grab the time every time the application
// is loaded on the device.
RimGetDateTime(&t);

// Create a unique seed every time the
// application is loaded on the device.
srand(t.minute+t.hour*60+t.date*60*24);

//Message loop
for (;;) {
// Create a new secret code for a game.
// 'a_SecretCode' is an array of 4 structs
// 'code' is an int variable in a struct that
// can only take on the values from 0 to 5.
for (int i = 0; i < 4; ++i)
a_SecretCode[i].code = rand()%6;

RimGetMessage(&msg);
//your code;
}
}

The following code fragment uses srand() to seed rand() with TIME then shuffles a deck of cards:

//Randomize the seed
TIME t;
int counter = 0;
int MAX_SHUFFLE = 10;

RimGetDateTime(&t);
srand(t.minute+t.hour*60+t.date*60*24);

while ( counter < MAX_SHUFFLE ) {
//Local Variables used in shuffling the deck
unsigned short int randNum1=rand()%52;
unsigned short int randNum2=rand()%52;

//Swap two random cards in the deck
//MAX_SHUFFLE times to shuffle the deck
temp_storage = deck[randNum1];
deck[randNum1] = deck[randNum2];
deck[randNum2] = temp_storage;

//Increment counter
counter++;
}