18.11.2014 Views

The Microcontroller Idea Book - Jan Axelson's Lakeview Research

The Microcontroller Idea Book - Jan Axelson's Lakeview Research

The Microcontroller Idea Book - Jan Axelson's Lakeview Research

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Inputs and Outputs<br />

Listing 6-2. Sets or clears a bit at output port E400h.<br />

5 REM variable A contains the last data written to 0E400h<br />

10 INPUT “Enter a bit to set or clear (0-7) :”,X<br />

20 INPUT “Enter 1 to set, 0 to clear :”,Y<br />

30 IF Y=1 THEN A=A.OR.2**X<br />

40 IF Y=0 THEN A=A.AND.0FFH-2**X<br />

50 XBY(0E400H)=A<br />

60 END<br />

Listing 6-1 is a program that reads the buffer and displays the value of each bit. <strong>The</strong> program<br />

is similar to Listing 3-1, which displays the bit values at Port 1.<br />

Line 20 finds the logic state of bit 0 by logically ANDing the byte with a mask byte that is<br />

all 0’s except for bit 0: 00000001. <strong>The</strong> result is 1 if bit 0 is 1, and 0 if bit 0 is 0. Lines 30-90<br />

are similar, except that each time a different bit in the mask byte is 1. In each case, the<br />

program divides the result by 2 raised to the power of the bit number. Since (2**0 equals 1,<br />

line 20 leaves out this step.) Each PRINT statement shows the logic state of one of the bits.<br />

At the output port, if you want to change just one bit in the byte, you have to know the<br />

current value of the byte. <strong>The</strong> simplest way to accomplish this is to save the last value you<br />

wrote. Or, you could wire an input buffer at the same address, with each input bit connecting<br />

to the corresponding output bit, and read the input when you need to know the current value.<br />

Listing 6-2 prompts you for a bit to set and clear, then does so. It assumes that you’ve stored<br />

the current value of E400h in variable A.<br />

To set a bit, line 30 logically ORs the current value with a mask byte that is all 0s except for<br />

the bit to be set. For example, to set bit 4, the mask byte is 0001 0000, or 10h, which leaves<br />

bits 0-3 and 5-7 unchanged, but forces bit 4 to be 1.<br />

To clear a bit, line 40 logically ANDs the byte with a mask byte that is all 1s except for the<br />

bit or bits to be cleared. For example, to clear bit 3, the mask byte is 1111 0111, or F7h. <strong>The</strong><br />

result is that bits 0-2 and 4-7 are unchanged, but bit 3 must be 0.<br />

Line 50 writes the new byte to the port.<br />

<strong>The</strong> <strong>Microcontroller</strong> <strong>Idea</strong> <strong>Book</strong> 97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!