Serial Port Complete - Latest Microcontroller projects

(lily) #1

Chapter 2


COM-port drivers in PCs maintain software buffers that are programmable in
size and can be as large as system memory permits. The driver transfers data
between the software and hardware buffers as needed.
Buffers in microcontrollers tend to be small. Some UARTs have no hardware
buffers at all. A computer with small or non-existent buffers may need to use
other methods to prevent lost data.

08 "  8
  


  


Events that can occur at a serial port include sending and receiving data,
changes in flow-control signals, errors in received data, and timeouts when
attempting to send or receive data. There are two ways for program code to
detect these events.
One way is to jump to a routine when an event occurs. The code responds
quickly to port activity without having to waste time checking only to learn
that no activity has occurred. This type of programming is called event driven
because an external event can break in at any time and cause the program’s exe-
cution to branch to a routine to handle the event.
The .NET Framework’s SerialPort class includes the DataReceived, Pin-
Changed, and ErrorReceived events. Handler routines can execute when a soft-
ware buffer’s count reaches a trigger value, when the state of a flow-control or
status pin changes, and when an error or timeout occurs. Many microcontrol-
lers have hardware interrupts that can perform similar functions.
The other approach to detecting events is to poll the port by periodically read-
ing properties, signal states, or registers to find out if an event has occurred.
This type of programming doesn’t use a port’s hardware interrupts. The code
has to poll often enough to detect all data and events in time to prevent lost dat
or other problems. The needed frequency of polling depends on buffer size, the
amount of data expected, and whether the code must respond quickly to events.
For example, a device that has a 16-byte buffer and polls the port once per sec-
ond can receive no more than 16 bytes per second or the buffer might overflow
and data will be lost.
Polling is often appropriate when transferring short bursts of data or when a
computer sends a command and expects an immediate reply. A polled interface
doesn’t require a hardware interrupt, so you can use this type of programming
on a port that doesn’t support hardware interrupts. The code can perform the
polling in a task loop that repeatedly performs required tasks, or a timer inter-
rupt can schedule tasks at intervals.
Free download pdf