Ports for Embedded Systems
When sending data, firmware can read the flow-control input and wait if
needed before writing a byte to TXREG. In normal operation, the waits should
be short, but it’s always possible the remote computer will malfunction and
leave its flow-control output de-asserted for a long time.
For efficient operation, firmware should minimize the time devoted to waiting
for the flow-control input to change state and provide a way to bail out if the
wait goes on too long. Tools that can help include timers, task loops, and hard-
ware interrupts.
Firmware with data to send can start a timeout timer and end the wait if the
flow-control input isn’t asserted after the timer times out. This approach can
work well if the waits are normally short or infrequent.
In a task loop, the device performs communications and other tasks as needed
in an endless loop. On each pass through the loop, a device with data to send
reads the flow-control input. If the input isn’t asserted, firmware moves on to
the next task. If the input is asserted, the firmware writes the data to the port
and performs any other related actions before moving on to the next task. Task
loops can work well for many applications.
A hardware interrupt can detect a rising or falling edge on the flow-control
input. Firmware can use the ISR to send data when the flow-control pin has
indicated that the remote interface is ready to receive data. An interrupt can
give the quickest response to changes at a flow-control input.
The PIC18F4520 supports three hardware interrupts on Port B: bit 0 (INT0),
bit 1 (INT1), and bit 2 (INT2). Three registers contain bits that monitor or
control the interrupts.
Interrupt Control Register (INTCON)
Bit 1 (INT0IF) is set to 1 when INT0 interrupts. Firmware must clear the bit.
Bit 4 (INT0IE) enables INT0.
Bits 6 (GIE) and bit 7 (PEIE) enable the interrupts as described earlier in this
chapter.
Interrupt Control Register 2 (INTCON2)
Bit 0 (INTEDG0), bit 1 (INTEDG1), and bit 2 (INTEDG2) configure their
corresponding interrupts to generate interrupts on the rising (1) or falling (0)
edges on the pins.