PROJECT 10.2—Random Number Generator
In this slightly more complex RTOS project, a random number between 0 and 255 is generated. Eight LEDs are connected to PORTB of a PIC18F452 microcontroller. In addition, a push-button switch is connected to bit 0 of PORTD (RD0), and an LED is connected to bit 7 of PORTD (RD7).
Three tasks are used in this project: Live, Generator, and Display.
• Task Live runs every 200ms and flashes the LED on port pin RD7 to indicate that the system is working.
• Task Generator increments a variable from 0 to 255 continuously and checks the status of the push-button switch. When the push-button switch is pressed, the value of the current count is sent to task Display using a messaging queue.
• Task Display reads the number from the message queue and sends the received byte to the LEDs connected to PORTB. Thus, the LEDs display a random pattern every time the push button is pressed.
Figure 10.9 shows the project’s block diagram. The circuit diagram is given in Figure 10.10. The microcontroller is operated from a 4MHz crystal.
The program listing of the project (RTOS2.C) is given in Figure 10.11. The main part of the program is in the later portion, and it configures PORTB pins as outputs. Also,
bit 0 of PORTD is configured as input and other pins of PORTD are configured as outputs.
Timer 0 is used as the RTOS timer, and the minor_cycle is set to 1s. The program consists of three tasks:
• Task Live runs every 200ms and flashes the LED connected to port pin RD7.
This LED indicates that the system is working.
• Task Generator runs every millisecond and increments a byte variable called count continuously. When the push-button switch is pressed, pin 0 of PORTD (RD0) goes to logic 0. When this happens, the current value of count is sent to task Display using RTOS function call rtos_msg_send(display, count), where
Display is the name of the task where the message is sent and count is the byte sent.
• Task Display runs every 10ms. This task checks whether there is a message in the queue. If so, the message is extracted using RTOS function call rtos_msg_read(), and the read byte is sent to the LEDs connected to PORTB.
Thus, the LEDs display the binary value of count as the switch is pressed. The message queue should be checked by using function rtos_msg_poll(), as trying to read the queue without any bytes in the queue may freeze the program.