5th Edition, 6th Revision Copyright 1994-2005 by Michael R. Sweet Tłumaczenie: Paweł Janik
Udziela się zgody na kopiowanie, dystrybucję i / lub modyfikowanie tego dokumentuzgodnie z warunkami licencji GNU Free Documentation License w wersji 1.2 lub nowszej, opublikowanej przez Free Software Foundation; bez Sekcje niezmienne, bez umieszczenia na przedniej okładce, ani na końcowej kładce. Kopia licencji załączona jest w dodatku C, GNU Free Documentation License.
Spis treści
Wprowadzenie
- Licencja
- Organizacja
Rozdział 1, Podstawy komunikacji przez port szeregowy
- Co to jest transmisja szeregowa?
- Co to jest RS-232?
- Definicja sygnału
- Transmisja asynchroniczna
- Co to jest Full Duplex i Half Duplex?
- Potwierdzenie transmisji
- Co to jest przerwa?
- Transmisja synchroniczna
- Dostęp do portów szeregowych
- Pliki portu szeregowego
- Otwieranie portu
- Wpisywanie danych do portu
- Czytanie danych z portu
- Zamykanie portu szeregowego
Rozdział 2, Konfiguracja portu szeregowego
- Interfejs transmisji w systemach POSIX
- Opcje kontroli
- Opcje lokalne
- Opcje wejścia
- Opcje wyjścia
- Znaki konfiguracyjne
Rozdział 3, Komunikacja z modemem
- Co to jest modem?
- Komunikacja z modemem
- Standardowe komendy modemu
- Częste problemy przy komunikacji z modemem
Rozdział 4, Zaawansowane programowanie portu szeregowego
- Port szeregowy IOCTL
- Pobieranie sygnałów kontrolnych
- Ustawianie sygnałów kontrolnych
- Pobieranie ilości dostępnych bajtów
- Wybór wejścia do portu szeregowego
- The SELECT System Call
- Używanie the SELECT System Call
- Używanie SELECT with the X Intrinsics Library
Dodatek A, Piny portu
- RS-232 piny
- RS-422 piny
- RS-574 (IBM PC/AT) piny
- SGI piny
Dodatek B, ASCII kody kontroli
- Kody kontroli
Dodatek C, GNU Free Documentation License
- Jak używać tej licencji w swoich dokumentach
Dodatek D, Historia zmian
- Edition 5, Revision 6
- Edition 5, Revision 5
- Edition 5, Revision 4
- Edition 5, Revision 3
Wstęp
The Serial Programming Guide for POSIX Operating Systems nauczy Cię, jak skutecznie i efektywnie tworzyć przenośne programy obsługujące porty szeregowe, stacji roboczej lub komputera. Każdy rozdział zawiera przykłady programowania, które korzystają z POSIX (Portable Standard for UNIX) funkcji kontrolnych terminala i powinien działać przy niewielkich zmianach w IRIX ?, HP-UX, SunOS ?, Solaris ?, Digital UNIX ?, Linux ? i UNIX większości innych systemów operacyjnych. Największą różnicą między systemami operacyjnymi jest to, że mają inne nazwy plików używanych przez port szeregowy i inne blokady.
Licencja
Udziela się zgody na kopiowanie, dystrybucję i / lub modyfikowanie tego dokumentuzgodnie z warunkami licencji GNU Free Documentation License w wersji 1.2 lub nowszej, opublikowanej przez Free Software Foundation; bez Sekcje niezmienne, bez umieszczenia na przedniej okładce, ani na końcowej kładce. Kopia licencji załączona jest w dodatku C, GNU Free Documentation License.
Organizacja
Ten podręcznik jest zorganizowany według tych rozdziałów i dodatków
-
Rozdział 1, Podstawy komunikacji przez port szeregowy
-
Rozdział 2, Konfiguracja portu szeregowego
-
Rozdział 3, Rozmowa z modemem
-
Rozdział 4, Zaawansowane programowanie portu
-
Dodatek A, Wyjścia RS-232
-
Dodatek B, ASCII kody kontroli
-
Dodatek C, GNU Free Documentation License
-
Dodatek D, Historia zmian
Rozdział 1, Podstawy komunikacji przez port szeregowy
W tym rozdziale będzie wstęp do komunikacji szeregowej RS-232 oraz innych norm, które są używane w większości komputerów, a także jak uzyskać dostęp do portu szeregowego z programu C.
Co to jest transmisja szeregowa?
Komputery przesyłają informacje (dane) jednego lub więcej bitów na raz. Transmisja szeregowa odnosi się do przekazywania danych o jeden bit na raz. Komunikacja szeregowa to większość urządzeń sieciowych, klawiatur, myszy, modemy, terminale.

Szybkość interfejsu szeregowego jest najczęściej wyrażona w bitach na sekundę („bps”) lub baudot rate („baud”). To właśnie oznacza liczbę zer i jedynek, które można wysłać w ciągu jednej sekundy. Na początku ery komputerów, 300 bodów uznano za szybko, ale dzisiaj komputery mogą obsługiwać RS-232 z prędkością aż 430.800 bodów! Jeśli szybkość transmisji przekracza 1000, można zwykle znaleźć w prędkość w kilo baud, lub kbps (np. 9,6 k, 19.2k, itp.). Dla transmisji powyżej 1.000.000, że wskaźnik jest wyświetlany w megabaud lub Mb/s (np. 1,5 Mbps).
Odnosząc się do urządzeń szeregowych lub portów, są one albo oznakowane Data Communications Equipment (DCE) lub Data Terminal Equipment (DTE). Różnica pomiędzy tymi jest prosta – każdą parę sygnałów, takich jak nadawanie i odbiór jest zamieniona. Połączenia dwóch DTE DCE lub dwóch interfejsów, kablem null-modem lub zastosowania adaptera, który zamienia sygnał par.
Co to jest RS-232?
RS-232 jest standardem elektrycznym dla komunikacji szeregowej określone przez Electronic Industries Association (EIA). RS-232 rzeczywiście jest w 3 typach (A, B i C) z których każdy określa inny zakres napięcia przy danym stanie logicznym. Najczęściej stosowane odmiany RS-232C, która definiuje logiczną jedynkę jako napięcie z przedziału -3V i -12V oraz oraz logicznego zera jako napięcie między +3 V i +12 V. W RS-232C Specyfikacja mówi, że przewody nie mogą być dłuższe niż 8 metrów, inaczej sygnały będą bezużyteczne. Zazwyczaj można wysyłać sygnały nieco dalej niż to mówi norma, o ile szybkość transmisji jest wystarczająco niska.
Oprócz przewodów dla danych przychodzących i wychodzących, istnieją inne, które zapewniają stabilność transmisji. Piny dal złącza 25 stykowym:
Table 1 – RS-232 Pin Assignments
| Pin | Opis | Pin | Opis | Pin | Opis | Pin | Opis | Pin | Opis |
|---|---|---|---|---|---|---|---|---|---|
| 1 | Ziemia ochronna | 6 | DSR ? gotowość DCE | 11 | Nieprzypisane | 16 | Drugi RXD | 21 | Pętla RDL |
| 2 | TXD ? Dane nadawane | 7 | GND - masa | 12 | Drugi DCD | 17 | Zegar retransmisji | 22 | Wskaźnik dzwonienia |
| 3 | RXD ? Dane odbierane | 8 | DCD ? poziom sygnału odbieranego | 13 | Drugi CTS | 18 | Nieprzypisane | 23 | Wybur szybkośc transmisji |
| 4 | RTS ? Żądanie nadawania | 9 | Zarezerwowane | 14 | Drugi TXD | 19 | Drugi RTS | 24 | Zegar transmisji |
| 5 | CTS ? Gotowość do nadawania | 10 | Zarezerwowane | 15 | Zagar transmisji | 20 | DTR ?Gotowość DTE | 25 | Nieprzypisane |
Istnieją dwie normy dla interfejsów szeregowych można również zobaczyć to RS-422 i RS-574. RS-422 korzysta z niższych napięć i sygnałów różnicowych, aby umożliwić długości kabla do około (300m). RS-574 definiuje 9-pinowe złącze szeregowe PC i napięcia.
Definicje sygnałów
Standard RS-232 definiuję 18 różnych sygnałów do komunikacji. Z tych sygnałów sześć z nich jest dostępnych w środowisku UNIX.
GND ? Masa logiczna
Technicznie masa nie jest sygnał, ale bez niej żadne inne sygnały będą działać. Zasadniczo, masa działa jako napięcie odniesienia tak, że elektronika może wiedzieć, które napięcia są pozytywne lub negatywne.
TXD ? Dane transmisji
Sygnał TXD przekazuje dane ze stacji roboczej do komputera lub innego urządzenia na drugim końcu (jak na przykład modem).
RXD ? Dane retransmisji
Sygnał RXD przesyła dane z komputera lub urządzenia na drugim końcu do stacji roboczej.
DCD - poziom sygnału odbieranego
Sygnał DCD jest odbierany z komputera lub innego urządzenia na drugim końcu kabla szeregowego. Napięcie na tej linii oznacza, że komputer lub urządzenie jest podłączone lub on-line. DCD nie zawsze jest dostępne.
DTR ? Gotowość transmisji danych
Sygnał DTR jest generowany przez system stacji roboczej i mówi do komputera lub urządzenia na drugim końcu, że jesteś gotowy lub niegotowy. DTR jest zwykle włączane automatycznie przy każdym otwarciu portu szeregowego na stacji roboczej.
CTS ? Gotowość nadawania
Sygnał CTS jest odbierany na drugim końcu kabla szeregowego. Mówi o możliwości nadawania. CTS jest zwykle używane do regulowania przepływu danych z własnego komputera na drugi koniec.
RTS ? Żądanie nadawania
Sygnał RTS w stacji roboczej wskazuje, że coraz więcej danych jest gotowych do wysłania. Podobnie jak CTS, RTS pomaga w regulacji przepływu danych między stacją roboczą a komputer lub urządzeniem na drugim końcu kabla szeregowego. Większość stacji zostawić to sygnał ustawiony przez cały czas.
Transmisja asynchroniczna
Aby komputer mógł zrozumieć przypływające pod porcie szeregowym dane, muszą te dane zawierać znak stopu i znak końca. Podręcznik ten dotyczy wyłącznie transmisji asynchronicznej.
W trybie asynchronicznym bezczynna linia danych pozostaje w stanie logicznym 1, aż do momentu transmisji. Bit startu poprzedza każdy znak(daną) następnie ,opcjonalnie bit parzystości, oraz jeden lub więcej bitów stopu. Bit startu zawsze ma stan logicznego 0 i mówi, że będą przesyłane dane. Dane mogą być przesyłane w dowolnym czasie,stąd nazwa asynchroniczne.
Figure 1 – Asynchronous Data Transmission
Opcjonalny bit parzystości, mówi komputerowi, bądź innemu urządzeniowi czy liczba 1 w danej jest parzysta lub nieparzysta. Bit parzystości ma logiczne 0 gdy liczba 1 jest nieparzysta.
Pozostałe bity to bity stopu. Mogą mieć 1, 1.5 lub 2 bity długości i zawsze mają wartość 1. Bity stopu były używane tradycyjnie do pozwolenia komputerowi przetworzyć daną otrzymaną, jednak dzisiaj służą tylko do synchronizacji.
Formaty danych asynchronicznych są zwykle wyrażone jako „8N1″,”7E1″, i tak dalej. Te zapisy oznaczają dla „8 bitów danych, bez parzystości, 1 bit stopu”i” 7 bitów danych, kontrola parzystości, 1 bit stop „, odpowiednio.
Co to jest Full Duplex i Half Duplex?
Full duplex oznacza, że komputer może równocześnie nadawać i odbierać dane, ma dwie niezależne linie (jedna do odbierania, i jedna do nadawania).
Half duplex oznacza, że komputer nie może nadawać i odbierać w tym samym czasie. Zwyczajowo ma tylko jedną lnie do komunikacji. Nie oznacza to, że żaden z sygnałów RS-232 nie jest wykorzystywany. Przeciwnie, zazwyczaj oznacza, że łącze komunikacyjne korzysta z niektórych standardów innych niż RS-232, które nie obsługują trybu full duplex.
Potwierdzenie transmisji
Często jest to niezbędne do regulacji przepływu danych podczas transferu danych pomiędzy dwoma interfejsami szeregowymi. Może to być koniecze ze względu na ograniczenia w komunikacji. Są Dwie metody powszechnie stosowane do asynchronicznej transmisji danych.
Pierwsza metoda jest często nazywana „oprogramowania”, kontroli przepływu i używa znaków specjalnych, aby rozpocząć (XON lub DC1, 021 ósemkowo) lub stop (XOFF lub DC3, 023 ósemkowo) przepływ danych. Znaki te są zdefiniowane w American Standard Code for Information Interchange („ASCII”). Podczas gdy kody te są przydatne przy przekazywaniu informacji tekstowych, nie mogą być używane przy przesyłaniu informacji innego rodzaju, bez specjalnego oprogramowania.
Druga metoda nazywa się „hardware” kontroli przepływu i korzysta z RS-232 sygnałów CTS i RTS zamiast znaków specjalnych. Odbiornik ustala CTS do logicznego 0, gdy jest gotowy do odbioru większej ilości danych i do stanu 1, gdy nie jest gotowy. Podobnie, nadawca ustawia RTS do stanu 0, gdy jest ona gotowa wysłać więcej danych. Ponieważ sprzętowa kontrola przepływu wykorzystuje oddzielny zestaw sygnałów, jest znacznie szybsza niż sterowanie przepływem, który musi wysyłać i odbierać wiele bitów informacji. Kontrola przepływu CTS/RTS nie jest obsługiwana przez wszystkie urządzenia lub systemy operacyjne.
Co to jest przerwa?
Zwykle po wysyłaniu u odbieraniu linia pozostaje w stanie niskim(logiczna 1), dopóki nie zostanie nadany następny znak. Jeżeli ten stan utrzyma się przez dłuższy okres czasu, zwykle 1/4 do 1/2 sekundy, wtedy mówi się, że jest przerwa.
Przerwy używa się do resetowania linii lub zmiany urządzenia z którym zachodzi komunikacja np. modem.
Komunikacja synchroniczna
W przeciwieństwie do asynchronicznej transmisji danych, dane pojawia się jako stały strumień bitów. Aby odczytać dane, komputer musi dostarczyć lub odebrać wspólny zegar, że zarówno nadajnik i odbiornik są zsynchronizowane.
Nawet przy takiej synchronizacji, na komputerze musi być oznaczony początek danej. Najczęstszym sposobem na osiągnięcie tego jest użycie protokołu pakietowej transmisji danych, takich jak Serial Data Link Control (SDLC) lub High-Speed Data Link Control (HDLC).
Każdy protokół określa sekwencje do reprezentowania początku i na końca pakietu danych. Każdy definiuje również sekwencji bitów, która jest używana gdy nie ma danych. Sekwencje te pozwalają komputer, sprawdzać czy nie występuje początek pakietu.
Ponieważ protokoły synchroniczne nie używają bitów synchronizacji są one zazwyczaj co najmniej 25% sprawniejsze w stosunku do komunikacji asynchronicznej i nadają się do zdalnej sieci i konfigurowane z większej ilości interfejsów szeregowych.
Pomimo zalet prędkości komunikacji synchronicznej, nie jest ona często używana ze względu na zastosowanie dodatkowego oprzyrządowania i oprogramowania.
Dostęp do portów szeregowych
Jak we wszystkich urządzeniach, UNIX zapewnia dostęp do portu szeregowego za pomocą plików urządzeń. Aby uzyskać dostęp do portu szeregowego należy po prostu otworzyć odpowiedni plik urządzenia.
Pliki portu szeregowego
Każdy port szeregowy w systemie UNIX posiada jeden lub więcej urządzenie(pliki w katalogu / dev):
Table 2 – Serial Port Device Files
| System | Port 1 | Port 2 |
|---|---|---|
| IRIX? | /dev/ttyf1 | /dev/ttyf2 |
| HP-UX | /dev/tty1p0 | /dev/tty2p0 |
| Solaris?/SunOS? | /dev/ttya | /dev/ttyb |
| Linux? | /dev/ttyS0 | /dev/ttyS1 |
| Digital UNIX? | /dev/tty01 | /dev/tty02 |
Otwieranie porty szeregowego
Ponieważ port szeregowy jest plikiem, funkcja open służy do dostępu do niego. W UNIX pliki urządzeń są zazwyczaj niedostępne dla zwykłych użytkowników. Obejście to zmiana uprawnień dostępu do pliku (-ów), uruchamianie programu jako super-użytkownik (root).
Na razie zakładamy, że plik jest dostępny dla wszystkich użytkowników kodu. Sposób otwarcia otwarcia portu szeregowego nr 1 na komputerze z systemem Linux jest pokazana na Listing 1.
Listing 1 – Opening a serial port.
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int
open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
/*
* Could not open the port.
*/
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
fcntl(fd, F_SETFL, 0);
return (fd);
}
Inne systemy wymagają odpowiedniej nazwy pliku urządzenia, ale w przeciwnym razie kod jest taki sam.
Opcje otwarcia
Zauważ, że kiedy otworzyliśmy plik urządzenia, użyliśmy dwóch innych flag wraz z flagami odczytu i zapisu:
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
Flaga O_NOCTTY mówi systemowi, że ten program nie chce być „sterującym terminala”tego portu. Jeśli nie podasz tego parametru to wtedy z żadnych danych (takich jak sygnały przerwania klawiatury itd.) nie wpływa na proces. Programy takie jak getty (1m/8) nie mogą korzystać z tej funkcji, gdyz zaczyna proces logowania, ale zwykle użytkownik nie chce tego problemu.
Flaga O_NDELAY mówi systemowi, że tego programu nie obchodzi, jaki stan jest na linii DCD ? czy na drugim końcu port jest uruchomiony. Jeśli nie podano tej flagi, proces zostanie uśpiony aż do pojawienia się odpowiedniego sygnału na linii DCD.
Wpisywanie danych do portu
Zapisywanie danych do portu jest łatwe – wystarczy skorzystać z write (2), przykład wysyłania danych do portu to:
n = write(fd, "ATZ\r", 4);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
Napisana funkcja zwraca liczbę bajtów wysłanych lub -1, jeśli wystąpił błąd.
Czytanie danych z portu
Odczyt danych z portu jest trochę trudniejszy. Podczas korzystania z portu w trybie RAW, każde wywołanie systemowe read (2) zwraca liczbę znaków, które są rzeczywiście dostępne w buforze wejściowym portu. Jeśli nie są dostępne żadne znaki, to wywołanie będzie blokować (czekać) do znaków chwili pojawienia się znaków wejściowych, bądź do minięcia czasu, lub wystąpił błąd. Funkcja read do natychmiastowego powrotu można urzyć w następujący sposób:
fcntl(fd, F_SETFL, FNDELAY);
Opcja FNDELAY powoduje, że funkcja zwraca 0, jeśli nie ma żadnych znaków dostępnych w buforze portu. Aby przywrócić normalne (blokujące) zachowanie, fcntlcall (), bez możliwości FNDELAY:
fcntl(fd, F_SETFL, 0);
Jest też używana po otwarciu portu szeregowego z możliwością O_NDELAY.
Zamykanie portu szeregowego
W celu zamknięcia portu, użyj funkcji close:
close(fd);
Zamknięcie portu szeregowego również jest możliwe poprzez DTR słaby sygnał, który wysyła większość modemów aby się rozłączyć.
Rozdział 2, Konfiguracja portu szeregowego
W tym rozdziale opisano, jak skonfigurować port szeregowy z C przy użyciu interfejsu termios.
Interfejs POSIX
Większość systemów wsparcia terminalu POSIX do zmiany parametrów takich jak prędkość transmisji, rozmiar czcionki, i tak dalej. Pierwszą rzeczą, którą musisz zrobić, to dołączyć plik ;ten określa strukturę kontroli końcowych, jak również funkcje kontroli POSIX.
Dwie najważniejsze funkcje POSIX są tcgetattr (3) i tcsetattr (3). Atrybuty get i set terminal, pobierają wskaźnik do struktury termos, który zawiera wszystkie dostępne opcje portu szeregowego:
Table 3 – Termios Structure Members
| Element | Opis |
|---|---|
| c_cflag | Control options |
| c_lflag | Line options |
| c_iflag | Input options |
| c_oflag | Output options |
| c_cc | Control characters |
| c_ispeed | Input baud (new interface) |
| c_ospeed | Output baud (new interface) |
Opcje kontroli
Element c_cflag kontroluje szybkość transmisji, liczbę bitów danych, parzystość, bity stopu i sprzętową kontrolę przepływu. Są to stałe dla wszystkich obsługiwanych konfiguracjach.
Table 4 – Constants for the c_cflag Member
| Stała | Opis |
|---|---|
| CBAUD | Bit mask for baud rate |
| B0 | 0 baud (drop DTR) |
| B50 | 50 baud |
| B75 | 75 baud |
| B110 | 110 baud |
| B134 | 134.5 baud |
| B150 | 150 baud |
| B200 | 200 baud |
| B300 | 300 baud |
| B600 | 600 baud |
| B1200 | 1200 baud |
| B1800 | 1800 baud |
| B2400 | 2400 baud |
| B4800 | 4800 baud |
| B9600 | 9600 baud |
| B19200 | 19200 baud |
| B38400 | 38400 baud |
| B57600 | 57,600 baud |
| B76800 | 76,800 baud |
| B115200 | 115,200 baud |
| EXTA | External rate clock |
| EXTB | External rate clock |
| CSIZE | Bit mask for data bits |
| CS5 | 5 data bits |
| CS6 | 6 data bits |
| CS7 | 7 data bits |
| CS8 | 8 data bits |
| CSTOPB | 2 stop bits (1 otherwise) |
| CREAD | Enable receiver |
| PARENB | Enable parity bit |
| PARODD | Use odd parity instead of even |
| HUPCL | Hangup (drop DTR) on last close |
| CLOCAL | Local line – do not change „owner” of port |
| LOBLK | Block job control output |
| CNEW_RTSCTS CRTSCTS |
Enable hardware flow control (not supported on all platforms) |
Element c_cflag zawiera dwie opcje, które powinny być zawsze włączone, CLOCAL i CREAD. Zapewnią one, że program nie staje się „właścicielem”, kontroli pracy portu i rozłączy sygnały, a także, że sterownik portu szeregowego będzie odbierał przychodzące dane.
Stałe szybkości transmisji (CBAUD, B9600, itp.) są stosowane w przypadku starszych interfejsów, gdzie brakuje elementów c_ispeed i c_ospeed. W następnej sekcji informacji będzie na temat funkcji POSIX służących do ustawienia szybkości transmisji.
Nigdy nie wolno zainicjować c_cflag (lub innych flag) bezpośrednio, należy zawsze używać bitowych operatorów do ustawiania lub czyszczenia bitów elementów. Różne wersje systemu operacyjnego (a nawet dodatki) mogą korzystać z bitów inaczej, więc korzystając z bitowych operatorów uniemożliwimy przykrywania flag bitowych.
Ustawianie prędkości transmisji
Szybkość jest przechowywane w różnych miejscach w zależności od systemu operacyjnego. Starsze interfejsy przechowują szybkość transmisji w c_cflag za pomocą jednej z transmisji stałych szybkości w tabeli 4, podczas gdy nowsze implementacje dostarczają c_ispeed i c_ospeed, które zawierają aktualne prędkość transmisji.
Funkcje Cfsetospeed (3) i cfsetispeed (3) są, aby ustawić prędkość transmisji w strukturze termios. Zazwyczaj można użyć kodu z listingu 2, aby ustawić szybkość transmisji danych.
Listing 2 – Setting the baud rate.
struct termios options;
/*
* Get the current options for the port...
*/
tcgetattr(fd, &options);
/*
* Set the baud rates to 19200...
*/
cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);
/*
* Enable the receiver and set local mode...
*/
options.c_cflag |= (CLOCAL | CREAD);
/*
* Set the new options for the port...
*/
tcsetattr(fd, TCSANOW, &options);
Funkcja tcgetattr (3) wypełnia termios bieżącą konfiguracji portu szeregowego. Po ustawienie prędkości transmisji oraz umożliwia lokalnie odbioru danych. Wybieranie nowej konfiguracji odbywa się za pomocą tcsetattr (3).Stała TCSANOW określa, że wszystkie zmiany powinny pojawić się natychmiast, nie czekając na dane wyjściowe, aby zakończyć wprowadzanie danych do wysyłania lub odbioru. Istnieją inne stałe takie jak: czekać na wejście i wyjście do końca lub do czyszczenia wejściowych i wyjściowych buforów.
Większość systemów nie obsługuje innych prędkości wejście i wyjść,więc należy ustawić tę samą prędkość transmisji dla maksymalnej przenośności.
Table 5 – Constants for tcsetattr
| Stała | Opis |
|---|---|
|
TCSANOW |
Wprowadzanie zmian teraz, nie czekając na pełne dane |
| TCSADRAIN | Czekania, aż wszystko zostanie przekazane |
| TCSAFLUSH | Czyszczenie buforów wejściowych i wyjściowych przed zapisaniem zmian |
Ustawianie rozmiaru znaku
W odróżnieniu ustawiania od szybkości transmisji, nie ma osobnej funkcji. Zamiast tego należy zrobić maskę, aby wszystko skonfigurować. Rozmiar znaków jest określony w bitach:
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= CS8; /* Select 8 data bits */
Ustawianie bitu parzystości
Podobnie jak z rozmiarem znaku należy ręcznie włączyć ustawienie parzystości i bity parzystości. Sterowniki portu szeregowego obsługują tryb z parzystością i bez bez bitu parzystości. Przestrzeń bitu parzystości może być symulowana za pomocą sprytnego kodowania.
-
No parity (8N1):
options.c_cflag &= ~PARENB options.c_cflag &= ~CSTOPB options.c_cflag &= ~CSIZE; options.c_cflag |= CS8;
-
Even parity (7E1):
options.c_cflag |= PARENB options.c_cflag &= ~PARODD options.c_cflag &= ~CSTOPB options.c_cflag &= ~CSIZE; options.c_cflag |= CS7;
-
Odd parity (7O1):
options.c_cflag |= PARENB options.c_cflag |= PARODD options.c_cflag &= ~CSTOPB options.c_cflag &= ~CSIZE; options.c_cflag |= CS7;
-
Space parity is setup the same as no parity (7S1):
options.c_cflag &= ~PARENB options.c_cflag &= ~CSTOPB options.c_cflag &= ~CSIZE; options.c_cflag |= CS8;
Ustawianie sprzętowej kontroli
Niektóre wersje UNIX wspierają sprzętowe sterowanie przepływem za pomocą linii CTS (Clear To Send) i RTS (Request To Send). Jeśli stałe CNEW_RTSCTS lub CRTSCTS są zdefiniowane w systemie to sprzętowe sterowanie przepływem jest prawdopodobnie obsługiwane. Wykonaj następujące czynności, aby umożliwić sprzętową kontrolę przepływu:
options.c_cflag |= CNEW_RTSCTS; /* Also called CRTSCTS */
Podobnie, aby wyłączyć sprzętowe sterowanie przepływem:
options.c_cflag &= ~CNEW_RTSCTS;
Opcje lekalne
Element c_lflag kontroluje znaki wejściowe zarządzane przez sterownik portu. Ogólnie można skonfigurować element c_lflag na wejście kanoniczne lub RAW.
Table 6 – Constants for the c_lflag Member
| Stała | Opis |
|---|---|
| ISIG | Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals |
| ICANON | Enable canonical input (else raw) |
| XCASE | Map uppercase \lowercase (obsolete) |
| ECHO | Enable echoing of input characters |
| ECHOE | Echo erase character as BS-SP-BS |
| ECHOK | Echo NL after kill character |
| ECHONL | Echo NL |
| NOFLSH | Disable flushing of input buffers after interrupt or quit characters |
| IEXTEN | Enable extended functions |
| ECHOCTL | Echo control characters as ^char and delete as ~? |
| ECHOPRT | Echo erased character as character erased |
| ECHOKE | BS-SP-BS entire line on line kill |
| FLUSHO | Output being flushed |
| PENDIN | Retype pending input at next read or input char |
| TOSTOP | Send SIGTTOU for background output |
Wybór kanonicznego wejścia
Wejście kanoniczne jest zorientowane liniowo. Wejściowe znaki wprowadzane są do bufora, który może być edytowany interaktywnie przez użytkownika do znaku CR lub LF.
Ten tryb normalnie wybierasz poprzez opcje ICANON, ECHO, i ECHOE:
options.c_lflag |= (ICANON | ECHO | ECHOE);
Wybór wejścia RAW
Wejście RAW jest w stanie nieprzetworzonym. Znaki wejściwe przychodzą dokładnie w takiej formie w jakiej zostały wysłane. Generalnie możesz odznaczyć opcje ICANON, ECHO, ECHOE i ISIG, podczas użycia wejścia RAW:
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
Uwagi dotyczące wejścia Echo
Nigdy nie można ustawić wejścia echo (ECHO, echoe) podczas wysyłania poleceń do modemu lub komputera, który jest echem innych znaków, będzie się w tedy generować pętls sprzężenia między dwoma interfejsami szeregowymi!
Opcje wejścia
Element wejściowy c_iflag kontroluje przetwarzanie danych wejściowych, które odbywa się na znakach odbieranych z portu. Podobnie jak c_cflag należy odnosić się do tego elementu w sposób bitowy.
Table 7 – Constants for the c_iflag Member
| Constant | Description |
|---|---|
| INPCK | Enable parity check |
| IGNPAR | Ignore parity errors |
| PARMRK | Mark parity errors |
| ISTRIP | Strip parity bits |
| IXON | Enable software flow control (outgoing) |
| IXOFF | Enable software flow control (incoming) |
| IXANY | Allow any character to start flow again |
| IGNBRK | Ignore break condition |
| BRKINT | Send a SIGINT when a break condition is detected |
| INLCR | Map NL to CR |
| IGNCR | Ignore CR |
| ICRNL | Map CR to NL |
| IUCLC | Map uppercase to lowercase |
| IMAXBEL | Echo BEL on input line too long |
Ustawianie opcji parzystości danych wejściowych
Należy włączyć sprawdzanie parzystości danych przychodzących, gdy masz włączoną parzystość w c_cflag. Istotne stałe, sprawdzające parzystości danych wejściowych to INPCK, IGNPAR, PARMRK i istrip. Ogólnie można wybrać INPCK i istrip Aby umożliwić kontrolę i demontaż bitu parzystości:
options.c_iflag |= (INPCK | ISTRIP);
GNPAR jest nieco niebezpieczną opcją, która mówi sterownikowi, że ma ignorować błędy parzystości i przekazać dane przychodzące tak jak by błędy nie miały miejsca. Może to być przydatne do testowania jakości połączenia komunikacyjnego, ale w ogóle nie jest wykorzystywana z powodów praktycznych.
PARMRK powoduje, że błędy parzystości „zauważalne” są w strumieniu danych wejściowych przy użyciu znaków specjalnych. Jeśli IGNPAR jest włączona, znak NUL jest przesyłany do programu przed każdym znakiem z błędem parzystości. W przeciwnym razie, DEL oraz znak NUL wysyłany jest wraz z złym znakiem.
Ustawianie programowej kontroli przepływu danych
Programowe sterowanie przepływem jest możliwe dzięki zastosowaniu stałych ixon, ixoff i IXANY:
options.c_iflag |= (IXON | IXOFF | IXANY);
Aby wyłączyć kontrolę przepływu danych po prostu wykonaj operacje:
options.c_iflag &= ~(IXON | IXOFF | IXANY);
XON (dane startowe) i XOFF (dane końcowe) znaki,są określone w c_cc tablicy poniżej.
Opcje wyjścia
Element c_oflag zawiera opcje filtrowania wyjścia. Podobnie jak przy wejściu, można wybrać dane przetworzone lub RAW.
Table 8 – Constants for the c_oflag Member
| Constant | Description |
|---|---|
| OPOST | Postprocess output (not set = raw output) |
| OLCUC | Map lowercase to uppercase |
| ONLCR | Map NL to CR-NL |
| OCRNL | Map CR to NL |
| NOCR | No CR output at column 0 |
| ONLRET | NL performs CR function |
| OFILL | Use fill characters for delay |
| OFDEL | Fill character is DEL |
| NLDLY | Mask for delay time needed between lines |
| NL0 | No delay for NLs |
| NL1 | Delay further output after newline for 100 milliseconds |
| CRDLY | Mask for delay time needed to return carriage to left column |
| CR0 | No delay for CRs |
| CR1 | Delay after CRs depending on current column position |
| CR2 | Delay 100 milliseconds after sending CRs |
| CR3 | Delay 150 milliseconds after sending CRs |
| TABDLY | Mask for delay time needed after TABs |
| TAB0 | No delay for TABs |
| TAB1 | Delay after TABs depending on current column position |
| TAB2 | Delay 100 milliseconds after sending TABs |
| TAB3 | Expand TAB characters to spaces |
| BSDLY | Mask for delay time needed after BSs |
| BS0 | No delay for BSs |
| BS1 | Delay 50 milliseconds after sending BSs |
| VTDLY | Mask for delay time needed after VTs |
| VT0 | No delay for VTs |
| VT1 | Delay 2 seconds after sending VTs |
| FFDLY | Mask for delay time needed after FFs |
| FF0 | No delay for FFs |
| FF1 | Delay 2 seconds after sending FFs |
Wybór wyjścia przetworzonego
Przetworzone jest wybierany poprzez ustawienie opcji OPOST w elemencie c_oflag:
options.c_oflag |= OPOST;
Spośród wszystkich opcji, prawdopodobnie będzie tylko skorzystać z opcji ONLCR. Reszta opcji wyjścia to są przede wszystkim opcje historyczne i datuje się na czas, kiedy linia drukarek i terminali nie mogła nadążyć za strumieniem danych!
Wybór wyjścia RAW
Wyjście RAWjest wybrane przez zresetowanie opcji OPOST w elemencie c_oflag:
options.c_oflag &= ~OPOST;
Gdy opcja OPOST jest wyłączona, wszystkie pozostałe bity opcji c_oflag są ignorowane.
Znaki kontrolne
Tablica c_cc znaków zawiera definicje znaków kontroli, jak również parametry czasu. Stałe są zdefiniowane dla każdego elementu tej tablicy.
Table 9 – Control Characters in the c_cc Member
| Stała | Opis | Klawisz |
|---|---|---|
| VINTR | Interrupt | CTRL-C |
| VQUIT | Quit | CTRL-Z |
| VERASE | Erase | Backspace (BS) |
| VKILL | Kill-line | CTRL-U |
| VEOF | End-of-file | CTRL-D |
| VEOL | End-of-line | Carriage return (CR) |
| VEOL2 | Second end-of-line | Line feed (LF) |
| VMIN | Minimum number of characters to read | - |
| VSTART | Start flow | CTRL-Q (XON) |
| VSTOP | Stop flow | CTRL-S (XOFF) |
| VTIME | Time to wait for data (tenths of seconds) | - |
Ustawianie znaków programowej kontroli
Elementy VSTART i VSTOP z tablicy c_cc zawierają znaki używane do kontroli przepływu danych. Normalnie powinny one być ustawione na DC1 (021 ósemkowy) i DC3 (023 ósemkowym), które stanowią standard ASCII znaków XON i XOFF.
Ustawianie limitu czasu czytania
W UNIX interfejs portu szeregowego zapewnia sterownikowi możliwość określenia charakteru pakietu i limitu czasu. Dwa elementy tablicy c_cc są stosowane do limitowania czasu: Vmin i VTIME. Limity czasu są ignorowane w trybie kanonicznym sygnału wejściowego lub, gdy opcja NDELAY jest ustawiona w pliku za pomocą otwarcia lub fcntl.
Vmin określa minimalną liczbę znaków do odczytania. Jeśli jest ona ustawiona na 0, to wartość VTIME określa czas oczekiwania na każdy znak. Zauważ, że to nie oznacza, że dalsze rozmowy na N bajtów będzie czekać na znaki N wejdźcie raczej czasu stosuje się do pierwszego znaku, a dalsze rozmowy zwracają liczbę znaków jaka jest dostępna (do numeru, który jest żądany).
Jeśli Vmin jest różna od zera, VTIME określa czas oczekiwania na pierwszy znak. Jeżeli znak jest odczytywany w wyznaczonym terminie, wszelkie dalsze zablokuje (czekaj), aż wszystkie znaki Vmin będą odczytane. Oznacza to, że jak po raz pierwszy czyta znak to, sterownik portu oczekuje całego pakietu znaków (Vmin bajtów łącznie). Jeśli nie będzie znak odczytywany w wyznaczonym terminie, to wezwanie do odczytu zwraca 0. Ta metoda pozwala powiedzieć sterownikowi ile trzeba dokładnie N bajtów i wszelkie dalsze rozmowy będą zwracać 0 lub N bajtów. Jednakże, stosuje się tylko do czasu pierwszego czytania znaku, więc jeśli z jakiegoś powodu sterownik traci jeden znak wewnątrz pakietu N bajtów, to dalsze połączenia może blokować zawsze czekają na dodatkowe znaki wejściowe.
VTIME określa czas oczekiwania na przychodzące znaki,czas jest określany w dziesiętnych częściach sekundy. Jeśli VTIME jest ustawiona na 0 (ustawienie domyślne), czytanie zablokuje (czeka) na czas nieokreślony.
Chapter 3, MODEM Communications
This chapter covers the basics of dialup telephone Modulator/Demodulator (MODEM) communications. Examples are provided for MODEMs that use the defacto standard „AT” command set.
What Is a MODEM?
MODEMs are devices that modulate serial data into frequencies that can be transferred over an analog data link such as a telephone line or cable TV connection. A standard telephone MODEM converts serial data into tones that can be passed over the phone lines; because of the speed and complexity of the conversion these tones sound more like loud screeching if you listen to them.
Telephone MODEMs are available today that can transfer data across a telephone line at nearly 53,000 bits per second, or 53kbps. In addition, most MODEMs use data compression technology that can increase the bit rate to well over 100kbps on some types of data.
Communicating With a MODEM
The first step in communicating with a MODEM is to open and configure the port for raw input as shown in Listing 3 .
Listing 3 – Configuring the port for raw input.
int fd;
struct termios options;
/* open the port */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, 0);
/* get the current options */
tcgetattr(fd, &options);
/* set raw input, 1 second timeout */
options.c_cflag |= (CLOCAL | CREAD);
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
/* set the options */
tcsetattr(fd, TCSANOW, &options);
Next you need to establish communications with the MODEM. The best way to do this is by sending the „AT” command to the MODEM. This also allows smart MODEMs to detect the baud you are using. When the MODEM is connected correctly and powered on it will respond with the response „OK”.
Listing 4 – Initializing the MODEM.
int /* O - 0 = MODEM ok, -1 = MODEM bad */
init_modem(int fd) /* I - Serial port file */
{
char buffer[255]; /* Input buffer */
char *bufptr; /* Current char in buffer */
int nbytes; /* Number of bytes read */
int tries; /* Number of tries so far */
for (tries = 0; tries < 3; tries ++)
{
/* send an AT command followed by a CR */
if (write(fd, "AT\r", 3) 0)
{
bufptr += nbytes;
if (bufptr[-1] == '\n' || bufptr[-1] == '\r')
break;
}
/* nul terminate the string and see if we got an OK response */
*bufptr = '\0';
if (strncmp(buffer, "OK", 2) == 0)
return (0);
}
return (-1);
}
Standard MODEM Commands
Most MODEMs support the „AT” command set, so called because each command starts with the „AT” characters. Each command is sent with the „AT” characters starting in the first column followed by the specific command and a carriage return (CR, 015 octal). After processing the command the MODEM will reply with one of several textual messages depending on the command.
ATD – Dial A Number
The ATD command dials the specified number. In addition to numbers and dashes you can specify tone („T”) or pulse („P”) dialing, pause for one second („,”), and wait for a dialtone („W”):
ATDT 555-1212
ATDT 18008008008W1234,1,1234
ATD T555-1212WP1234
The MODEM will reply with one of the following messages:
NO DIALTONE
BUSY
NO CARRIER
CONNECT
CONNECT baud
ATH – Hang Up
The ATH command causes the MODEM to hang up. Since the MODEM must be in „command” mode you probably won’t use it during a normal phone call.
Most MODEMs will also hang up if DTR is dropped; you can do this by setting the baud to 0 for at least 1 second. Dropping DTR also returns the MODEM to command mode.
After a successful hang up the MODEM will reply with „NO CARRIER”. If the MODEM is still connected the „CONNECT” or „CONNECT baud” message will be sent.
ATZ – Reset MODEM
The ATZ command resets the MODEM. The MODEM will reply with the string „OK”.
Common MODEM Communication Problems
First and foremost, don’t forget to disable input echoing. Input echoing will cause a feedback loop between the MODEM and computer.
Second, when sending MODEM commands you must terminate them with a carriage return (CR) and not a newline (NL). The C character constant for CR is „\r”.
Finally, when dealing with a MODEM make sure you use a baud that the MODEM supports. While many MODEMs do auto-baud detection, some have limits (19.2kbps is common on older MODEMs) that you must observe.
Chapter 4, Advanced Serial Programming
This chapter covers advanced serial programming techniques using the ioctl(2) and select(2) system calls.
Serial Port IOCTLs
In Chapter 2, Configuring the Serial Port we used the tcgetattr and tcsetattr functions to configure the serial port. Under UNIX these functions use the ioctl(2) system call to do their magic.
The ioctl system call takes three arguments:
int ioctl(int fd, int request, ...);
The fd argument specifies the serial port file descriptor. The request argument is a constant defined in the header file and is typically one of the constants listed in Table 10.
Table 10 – IOCTL Requests for Serial Ports
| Request | Description | POSIX Function |
|---|---|---|
| TCGETS | Gets the current serial port settings. | tcgetattr |
| TCSETS | Sets the serial port settings immediately. | tcsetattr(fd, TCSANOW, &options) |
| TCSETSF | Sets the serial port settings after flushing the input and output buffers. | tcsetattr(fd, TCSAFLUSH, &options) |
| TCSETSW | Sets the serial port settings after allowing the input and output buffers to drain/empty. | tcsetattr(fd, TCSADRAIN, &options) |
| TCSBRK | Sends a break for the given time. | tcsendbreak, tcdrain |
| TCXONC | Controls software flow control. | tcflow |
| TCFLSH | Flushes the input and/or output queue. | tcflush |
| TIOCMGET | Returns the state of the „MODEM” bits. | None |
| TIOCMSET | Sets the state of the „MODEM” bits. | None |
| FIONREAD | Returns the number of bytes in the input buffer. | None |
Getting the Control Signals
The TIOCMGET ioctl gets the current „MODEM” status bits, which consist of all of the RS-232 signal lines except RXD and TXD, listed in Table 11.
To get the status bits, call ioctl with a pointer to an integer to hold the bits, as shown in Listing 5 .
Listing 5 – Getting the MODEM status bits.
#include
#include
int fd;
int status;
ioctl(fd, TIOCMGET, &status);
Table 11 – Control Signal Constants
| Constant | Description |
|---|---|
| TIOCM_LE | DSR (data set ready/line enable) |
| TIOCM_DTR | DTR (data terminal ready) |
| TIOCM_RTS | RTS (request to send) |
| TIOCM_ST | Secondary TXD (transmit) |
| TIOCM_SR | Secondary RXD (receive) |
| TIOCM_CTS | CTS (clear to send) |
| TIOCM_CAR | DCD (data carrier detect) |
| TIOCM_CD | Synonym for TIOCM_CAR |
| TIOCM_RNG | RNG (ring) |
| TIOCM_RI | Synonym for TIOCM_RNG |
| TIOCM_DSR | DSR (data set ready) |
Setting the Control Signals
The TIOCMSET ioctl sets the „MODEM” status bits defined above. To drop the DTR signal you can use the code in Listing 6.
Listing 6 – Dropping DTR with the TIOCMSET ioctl.
#include
#include
int fd;
int status;
ioctl(fd, TIOCMGET, &status);
status &= ~TIOCM_DTR;
ioctl(fd, TIOCMSET, &status);
The bits that can be set depend on the operating system, driver, and modes in use. Consult your operating system documentation for more information.
Getting the Number of Bytes Available
The FIONREAD ioctl gets the number of bytes in the serial port input buffer. As with TIOCMGET you pass in a pointer to an integer to hold the number of bytes, as shown in Listing 7.
Listing 7 – Getting the number of bytes in the input buffer.
#include
#include
int fd;
int bytes;
ioctl(fd, FIONREAD, &bytes);
This can be useful when polling a serial port for data, as your program can determine the number of bytes in the input buffer before attempting a read.
Selecting Input from a Serial Port
While simple applications can poll or wait on data coming from the serial port, most applications are not simple and need to handle input from multiple sources.
UNIX provides this capability through the select(2) system call. This system call allows your program to check for input, output, or error conditions on one or more file descriptors. The file descriptors can point to serial ports, regular files, other devices, pipes, or sockets. You can poll to check for pending input, wait for input indefinitely, or timeout after a specific amount of time, making the select system call extremely flexible.
Most GUI Toolkits provide an interface to select; we will discuss the X Intrinsics („Xt”) library later in this chapter.
The SELECT System Call
The select system call accepts 5 arguments:
int select(int max_fd, fd_set *input, fd_set *output, fd_set *error,
struct timeval *timeout);
The max_fd argument specifies the highest numbered file descriptor in the input, output, and error sets. The input, output, and error arguments specify sets of file descriptors for pending input, output, or error conditions; specify NULL to disable monitoring for the corresponding condition. These sets are initialized using three macros:
FD_ZERO(&fd_set);
FD_SET(fd, &fd_set);
FD_CLR(fd, &fd_set);
The FD_ZERO macro clears the set entirely. The FD_SET and FD_CLR macros add and remove a file descriptor from the set, respectively.
The timeout argument specifies a timeout value which consists of seconds (timeout.tv_sec) and microseconds (timeout.tv_usec ). To poll one or more file descriptors, set the seconds and microseconds to zero. To wait indefinitely specify NULL for the timeout pointer.
The select system call returns the number of file descriptors that have a pending condition, or -1 if there was an error.
Using the SELECT System Call
Suppose we are reading data from a serial port and a socket. We want to check for input from either file descriptor, but want to notify the user if no data is seen within 10 seconds. To do this we’ll need to use the select system call, as shown in Listing 8.
Listing 8 – Using SELECT to process input from more than one source.
#include
#include
#include
#include
int n;
int socket;
int fd;
int max_fd;
fd_set input;
struct timeval timeout;
/* Initialize the input set */
FD_ZERO(&input);
FD_SET(fd, &input);
FD_SET(sock, &input);
max_fd = (sock > fd ? sock : fd) + 1;
/* Initialize the timeout structure */
timeout.tv_sec = 10;
timeout.tv_usec = 0;
/* Do the select */
n = select(max_fd, &input, NULL, NULL, &timeout);
/* See if there was an error */
if (n < 0)
perror("select failed");
else if (n == 0)
puts("TIMEOUT");
else
{
/* We have input */
if (FD_ISSET(fd, &input))
process_fd();
if (FD_ISSET(sock, &input))
process_socket();
}
You’ll notice that we first check the return value of the select system call. Values of 0 and -1 yield the appropriate warning and error messages. Values greater than 0 mean that we have data pending on one or more file descriptors.
To determine which file descriptor(s) have pending input, we use the FD_ISSET macro to test the input set for each file descriptor. If the file descriptor flag is set then the condition exists (input pending in this case) and we need to do something.
Using SELECT with the X Intrinsics Library
The X Intrinsics library provides an interface to the select system call via the XtAppAddInput(3x) and XtAppRemoveInput(3x) functions:
int XtAppAddInput(XtAppContext context, int fd, int mask,
XtInputProc proc, XtPointer data);
void XtAppRemoveInput(XtAppContext context, int input);
The select system call is used internally to implement timeouts, work procedures, and check for input from the X server. These functions can be used with any Xt-based toolkit including Xaw, Lesstif, and Motif.
The proc argument to XtAppAddInput specifies the function to call when the selected condition (e.g. input available) exists on the file descriptor. In the previous example you could specify the process_fd or process_socketfunctions.
Because Xt limits your access to the select system call, you’ll need to implement timeouts through another mechanism, probably via XtAppAddTimeout(3x).
Appendix A, Pinouts
This appendix provides pinout information for many of the common serial ports you will find.
RS-232 Pinouts
RS-232 comes in three flavors (A, B, C) and uses a 25-pin D-Sub connector:
Figure 2 – RS-232 Connector
Table 12 – RS-232 Signals
| Pin | Description | Pin | Description |
|---|---|---|---|
| 1 | Earth Ground | 14 | Secondary TXD |
| 2 | TXD - Transmitted Data | 15 | Transmit Clock |
| 3 | RXD - Received Data | 16 | Secondary RXD |
| 4 | RTS - Request To Send | 17 | Receiver Clock |
| 5 | CTS - Clear To Send | 18 | Unassigned |
| 6 | DSR - Data Set Ready | 19 | Secondary RTS |
| 7 | GND - Logic Ground | 20 | DTR - Data Terminal Ready |
| 8 | DCD - Data Carrier Detect | 21 | Signal Quality Detect |
| 9 | Reserved | 22 | Ring Detect |
| 10 | Reserved | 23 | Data Rate Select |
| 11 | Unassigned | 24 | Transmit Clock |
| 12 | Secondary DCD | 25 | Unassigned |
| 13 | Secondary CTS | ||
RS-422 Pinouts
RS-422 also uses a 25-pin D-Sub connector, but with differential signals:
Figure 3 – RS-422 Connector
Table 13 – RS-422 Signals
| Pin | Description | Pin | Description |
|---|---|---|---|
| 1 | Earth Ground | 14 | TXD+ |
| 2 | TXD- - Transmitted Data | 15 | Transmit Clock- |
| 3 | RXD- - Received Data | 16 | RXD+ |
| 4 | RTS- - Request To Send | 17 | Receiver Clock- |
| 5 | CTS- - Clear To Send | 18 | Unassigned |
| 6 | DSR - Data Set Ready | 19 | RTS+ |
| 7 | GND - Logic Ground | 20 | DTR- - Data Terminal Ready |
| 8 | DCD- - Data Carrier Detect | 21 | Signal Quality Detect |
| 9 | Reserved | 22 | Unassigned |
| 10 | Reserved | 23 | DTR+ |
| 11 | Unassigned | 24 | Transmit Clock+ |
| 12 | DCD+ | 25 | Receiver Clock+ |
| 13 | CTS+ | ||
RS-574 (IBM PC/AT) Pinouts
The RS-574 interface is used exclusively by PC manufacturers and uses a 9-pin male D-Sub connector:
Figure 4 – RS-574 Connector
Table 14 – RS-574 (IBM PC/AT) Signals
| Pin | Description | Pin | Description |
|---|---|---|---|
| 1 | DCD - Data Carrier Detect | 6 | Data Set Ready |
| 2 | RXD - Received Data | 7 | RTS - Request To Send |
| 3 | TXD - Transmitted Data | 8 | CTS - Clear To Send |
| 4 | DTR - Data Terminal Ready | 9 | Ring Detect |
| 5 | GND - Logic Ground | ||
SGI Pinouts
Older SGI equipment uses a 9-pin female D-Sub connector. Unlike RS-574, the SGI pinouts nearly match those of RS-232:
Figure 5 – SGI 9-Pin Connector
Table 15 – SGI 9-Pin DSUB Signals
| Pin | Description | Pin | Description |
|---|---|---|---|
| 1 | Earth Ground | 6 | DSR - Data Set Ready |
| 2 | TXD - Transmitted Data | 7 | GND - Logic Ground |
| 3 | RXD - Received Data | 8 | DCD - Data Carrier Detect |
| 4 | RTS - Request To Send | 9 | DTR - Data Terminal Ready |
| 5 | CTS - Clear To Send | ||
The SGI Indigo, Indigo2, and Indy workstations use the Apple 8-pin MiniDIN connector for their serial ports:
Figure 6 – SGI 8-Pin Connector
Table 16 – SGI 8-Pin MiniDIN Signals
| Pin | Description | Pin | Description |
|---|---|---|---|
| 1 | DTR - Data Terminal Ready | 5 | RXD - Received Data |
| 2 | CTS - Clear To Send | 6 | RTS - Request To Send |
| 3 | TXD - Transmitted Data | 7 | DCD - Data Carrier Detect |
| 4 | GND - Logic Ground | 8 | GND - Logic Ground |
Appendix B, ASCII Control Codes
This chapter lists the ASCII control codes and their names.
Control Codes
The following ASCII characters are used for control purposes:
Table 17 – ASCII Control Codes
| Name | Binary | Octal | Decimal | Hexadecimal |
|---|---|---|---|---|
| NUL | 00000000 | 000 | 0 | 00 |
| SOH | 00000001 | 001 | 1 | 01 |
| STX | 00000010 | 002 | 2 | 02 |
| ETX | 00000011 | 003 | 3 | 03 |
| EOT | 00000100 | 004 | 4 | 04 |
| ENQ | 00000101 | 005 | 5 | 05 |
| ACK | 00000110 | 006 | 6 | 06 |
| BEL | 00000111 | 007 | 7 | 07 |
| BS | 00001000 | 010 | 8 | 08 |
| HT | 00001001 | 011 | 9 | 09 |
| NL | 00001010 | 012 | 10 | 0A |
| VT | 00001011 | 013 | 11 | 0B |
| NP, FF | 00001100 | 014 | 12 | 0C |
| Name | Binary | Octal | Decimal | Hexadecimal |
| CR | 00001101 | 015 | 13 | 0D |
| SO | 00001110 | 016 | 14 | 0E |
| SI | 00001111 | 017 | 15 | 0F |
| DLE | 00010000 | 020 | 16 | 10 |
| XON, DC1 | 00010001 | 021 | 17 | 11 |
| DC2 | 00010010 | 022 | 18 | 12 |
| XOFF, DC3 | 00010011 | 023 | 19 | 13 |
| DC4 | 00010100 | 024 | 20 | 14 |
| NAK | 00010101 | 025 | 21 | 15 |
| SYN | 00010110 | 026 | 22 | 16 |
| ETB | 00010111 | 027 | 23 | 17 |
| CAN | 00011000 | 030 | 24 | 18 |
| EM | 00011001 | 031 | 25 | 19 |
| SUB | 00011010 | 032 | 26 | 1A |
| ESC | 00011011 | 033 | 27 | 1B |
| FS | 00011100 | 034 | 28 | 1C |
| GS | 00011101 | 035 | 29 | 1D |
| RS | 00011110 | 036 | 30 | 1E |
| US | 00011111 | 037 | 31 | 1F |
Appendix C, GNU Free Documentation License
Version 1.2, November 2002
Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document „free” in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of „copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The „Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as „you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A „Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A „Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The „Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The „Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A „Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not „Transparent” is called „Opaque”.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The „Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, „Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text.
A section „Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as „Acknowledgements”, „Dedications”, „Endorsements”, or „History”.) To „Preserve the Title” of such a section when you modify the Document means that it remains a section „Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
-
A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
-
B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
-
C. State on the Title page the name of the publisher of the Modified Version, as the publisher.
-
D. Preserve all the copyright notices of the Document.
-
E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
-
F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
-
G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice.
-
H. Include an unaltered copy of this License.
-
I. Preserve the section Entitled „History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled „History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
-
J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the „History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
-
K. For any section Entitled „Acknowledgements” or „Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
-
L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
-
M. Delete any section Entitled „Endorsements”. Such a section may not be included in the Modified Version.
-
N. Do not retitle any existing section to be Entitled „Endorsements” or to conflict in title with any Invariant Section.
-
O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles.
You may add a section Entitled „Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties–for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled „History” in the various original documents, forming one section Entitled „History”; likewise combine any sections Entitled „Acknowledgements”, and any sections Entitled „Dedications”. You must delete all sections Entitled „Endorsements.”
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an „aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled „Acknowledgements”, „Dedications”, or „History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License „or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.
How to use this License for your documents
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (c) YEAR YOUR NAME.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the „with…Texts.” line with this:
with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
Appendix D, Change History
This appendix lists the changes that have been made in this edition.
Edition 5, Revision 6
The following changes were made for the 6th revision:
-
The select() example did not correctly use the FD macros.
-
The title page and this appendix were not properly updated.
Edition 5, Revision 5
The following changes were made for the 5th revision:
-
The select() documentation did not correctly describe the FD macros.
-
Appendix C was missing the „how to use” part of the GNU FDL.
Edition 5, Revision 4
The following changes were made for the 4th revision:
-
Changed the description of the read() system call semantics in chapter 1.
-
Added descriptions for VSTART and VSTOP to chapter 2.
Edition 5, Revision 3
The following changes were made for the 3rd revision:
-
Now use the GNU Free Documentation License for the guide.
-
Changed the examples to use the Linux serial port filenames.
-
Put the infrastructure in place to allow for easier translations of the guide.
-
The guide text is now fully justified.

PeeR
/ 10 sierpnia 2011W rozdziale: „Otwieranie porty szeregowego”
pominięte zostały nazwy bibliotek.
#include /* Standard input/output definitions */
#include /* String function definitions */
#include /* UNIX standard function definitions */
#include /* File control definitions */
#include /* Error number definitions */
#include /* POSIX terminal control definitions */
Paweł Janik
/ 10 sierpnia 2011Dzięki za informacje. Już poprawione.