Page 415 - Programming Microcontrollers in C
P. 415
400 Chapter 8 MCORE, A RISC Machine
while(semaphore[i]==TRUE)
;
}
Listing 8-2: Semaphore functions
This problem is avoided by disabling all interrupts prior to reading
the semaphore state during the attachment process. Interrupts are
disabled and enabled by setting and clearing bits in the PSR register
on the core processor. If you examine the mmc2001.h header file,
there are four macros, Enable_Interrupts(),
Enable_Fast_Interrupts(), Disable_Interrupts()
and Disable_Fast _Interrupts() defined. These macros
are all written in assembly language because the C language cannot
access core control registers directly. In the attach_semaphore()
routine above, there is one line of assembly code as follows
asm(“ mfcr R1,PSR\n lrw R2,save\n stw R1,(R2,0)\n”);
These three assembly instructions save the contents of the PSR reg
ister in the memory location named save. The code
asm(“ lrw r2,save\n ldw R1,(r2,0)\n mtcr R1,PSR\n”);
moves the contents of the memory location save back into the PSR.
The bits that enable both the fast interrupts and the conventional
interrupts are contained in this register. Therefore, the code as shown
in the attach_semaphore() routine saves the currently enabled
interrupts, disables all interrupts, and after the status of the semaphore
is established and set properly, restores the PSR to its original value.
When the semaphore is attached, it is marked true in the array of
available semaphores. The function release_semaphore()
marks the semaphore as FALSE. The program can query the
semaphore to determine if it is being used. This function returns the
value saved in the specified location in the array of semaphores that
is TRUE when the semaphore is being used. The final function is to
wait_for_semaphore(). When this function is entered, control
will remain in the function until the specified semaphore is released.
It is important that you do not attempt to wait for an unattached
semaphore. In that case, control will never be returned to the calling
program.