Hardware Reference
In-Depth Information
5.7.7 Unions
A union is a variable that may hold (at different times) objects of different types and sizes,
with the compiler keeping track of size and alignment requirements. Unions provide a way to
manipulate different kinds of data in a single area of storage, without embedding any machine-
dependent information in the program. The syntax of the union is
union union_name {
type-name1
element1;
type-name2
element2;
. . .
type-namen
elementn;
};
The field union_name is optional. When it exists, it is also called union-tag . We can declare
a union variable at the same time we declare a union type. The union variable name should be
placed after the right brace }. In order to represent the current temperature using both the inte-
ger and string, we can use the following declaration:
union u_tag {
int i;
char c[4];
} temp;
Four characters must be allocated to accommodate the larger of the two types. Integer type
is good for internal computation, whereas string type is suitable for output. Of course, some
conversion may be needed before making a certain kind of interpretation. Using this method,
the variable temp can be interpreted as an integer or a string, depending on the purpose. Syntac-
tically, members of a union are accessed as
union-name.member or union-pointer member
just as for structures.
5.8 Writing C Programs to Perform Simple I/O
The parallel I/O ports have been briefly discussed in Section 4.10. Before performing an I/O
operation, the user needs to configure the I/O port for either input or output. By writing a 1 to a
bit in the data direction register (DDRx, x is the port name), the associated I/O pin is configured
for output. By writing a 0 to a bit in the data direction register, the associated I/O pin is config-
ured for input.
For example, the following statement configures Port B for output:
DDRB 5 0xFF;
The following statement confi gures Port B for input:
DDRB 5 0;
The user may also configure a few pins of a port for output and other pins for input. For
example, the following statement configures the upper four pins of Port B for output and the
lower four pins of Port B for input:
DDRB 5 0xF0;
 
Search WWH ::




Custom Search