文件名称:
Serial Programming Guide for POSIX Operating Systems.pdf
开发工具:
文件大小: 675kb
下载次数: 0
上传时间: 2019-06-30
详细说明:linux 串口编程,串口设置。老外文档。
介绍了linux串口的基本操作,国内很多博客都引用和翻译此文。
1.基本串口通信
2.如何配置串口
3.调制解调通信
4.高级串口编程Serial programming Guide for posiX Operating Systems
https://www.cmrr.umnedu/strupp/serial.htm1#contents
When referring to serial devices or ports, they are either labeled as Dala Communications Equipmen(Dce")or Dula Terminal
Equipment(DTE). The difference between these is simple- every signal pair, like transmit and receive, is swapped. When connecting
two DtE or two DCE interfaces together, a serial null-MODEM cable or adapter is used that swaps the signal pairs
What Is rs-232?
RS-232 is a standard electrical interface for serial communications defined by the Electronic Industries Association C"EIA". RS-232
actually comes in 3 different flavors(A, B, and C)with each one defining a different voltage range for the on and off levels. The most
commonly used variety is rs-232C, which defines a mark(on) bit as a voltage between -3V and -12V and a space(off) bit as a voltage
between+3V and +12V. The rS-232C specification says these signals can go about 25 feet( 8m) before they become unusable. You can
usually send signals a bit farther than this as long as the baud is low enough
Besides wires for incoming and outgoing data, there are others that provide timing, status, and handshaking
Table 1-Rs-232 Pin assignments
Pin Description Pin Description Pin Description Pin Description Pin Descriptio
Igna
Earth Ground 6 DSR-Data
Secondary
1Unassigned16
Set ready
RXD
21 Quality
Detect
TXD
2Transmitted 7- Logic
Secondar
17 Receiver Clock 22 Ring Detect
Ground
DCD
Data
3 XD
/8DCD-Data
Received Data
Carrier Detect 13 Secondary
CTS
18 Unassigned
123 Data Rate
Select
/4 RTS-RO
quest
Secondar
9 Reserved
To Send
19 Secondary RTS 24Iransmit
TXD
Clock
DTR-Data
15CTS-Clear
Transmit
Reserved
15
To Send
Clock
20 Terminal
25 Unassigned
Read
Two standards for serial interfaces you may also see are rs-422 and rs-574 Rs-422 uses lower voltages and differential signals to
allow cable lengths up to about 1000ft(300m). Rs-574 defines the 9-pin PC serial connector and voltages
Signal Definitions
The rs-232 standard defines some 18 different signals for serial communications. Of these, only six are generally available in the UNIX
environment
GND- Logic Ground
Technically the logic ground is not a signal, but without it none of the other signals will operate. Basically, the logic ground acts as a
reference voltage so that the electronics know which voltages are positive or negative
TXD- Transmitted data
第3页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umn.edustrupp/serial.html#contents
The TXD Signal carries data transmitted from your workstation to the computer or device on the other end (like a MODEm). a mark
voltage is interpreted as a value of l, while a space voltage is interpreted as a value of o
RXD Received data
The rXd signal carries data transmitted from the computer or device on the other end to your workstation. Like TXD, mark and space
voltages are interpreted as l and 0, respectively
DCD- Data Carrier Detect
The dcd signal is received from the computer or device on the other end of your serial cable. a space voltage on this signal line
indicates that the computer or device is currently connected or on line dCd is not always used or available
DTR- Data Terminal Ready
The dTR signal is generated by your workstation and tells the computer or device on the other end that you are ready (a space voltage)
or not-ready(a mark voltage). DtR is usually enabled automatically whenever you open the serial interface on the workstation
CTS- Clear To send
The CTS signal is received from the other end of the serial cable. A space voltage indicates that is alright to send more serial data from
your workstation.
CTS is usually used to regulate the flow of serial data from your workstation to the other end
RTS- Request To send
The rts signal is set to the space voltage by your workstation to indicate that more data is ready to be sent
Like cts, rts helps to regulate the flow of data between your workstation and the computer or device on the other end of the serial
cable. Most workstations leave this signal set to the space voltage all the time
Asynchronous Communications
For the computer to understand the serial data coming into it, it needs some way to determine where one character ends and the next
begins. This guide deals exclusively with asynchronous serial data
In asynchronous mode the serial data line stays in the mark (1)state until a character is transmitted a start bit preceeds each character
and is followed immediately by each bit in the character, an optional parity bit, and one or more stop bits. The start bit is always a space
(O)and tells the computer that new serial data is available. Data can be sent or received at any time, thus the name asynchronous
第4页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umnedu/strupp/serial.htm1#contents
Figure 1- Asynchronous Data Transmission
SPAGE
+12V
MARK
12v
The optional parity bit is a simple sum of the data bits indicating whether or not the data contains an even or odd number of 1 bits. With
even parity, the parity bit is 0 if there is an even number of l's in the character. With odd parity, the parity bit is 0 if there is an odd
number of I's in the data. You may also hear the terms space parity, mark parity, and no parity space parity means that the parity bit is
always 0, while mark parity means the bit is always 1. No parity means that no parity bit is present or transmitted
The remaining bits are called stop bits. There can be 1,1.5, or 2 stop bits between characters and they always have a value of 1. Stop bits
traditionally were used to give the computer time to process the previous character, but now only serve to synchronize the receiving
computer to the incoming characters
Asynchronous data formats are usually expressed as 8N1", 7El", and so forth These stand for"8 data bits, no parity, I stop bit "and"7
data bits, even parity, I stop bit" respectively
What Are Full Duplex and Half duplex?
Full duplex means that the computer can send and receive data simultaneously -there are two separate data channels(one coming in,
one going out
Half duplex means that the computer cannot send or receive data at the same time. Usually this means there is only a single data channel
to talk over. This does not mean that any of the rs-232 signals are not used. Rather, it usually means that the communications link uses
some standard other than rs-232 that does not support full duplex operation
Flow control
It is often necessary to regulate the flow of data when transferring data between two serial interfaces. This can be due to limitations in an
intermediate serial communications link, one of the serial interfaces, or some storage media. Two methods are commonly used for
asynchronous data
The first method is often called "software" flow control and uses special characters to start (Xon or dcl, 02l octal or stop (Xoff or
DC3, 023 octal)the flow of data. These characters are defined in the American Standard Code for Information Interchange("ASCII"
While these codes are useful when transferring textual information, they cannot be used when transferring other types of information
without special programming
The second method is called"hardware"flow control and uses the rs-232 CTS and RTS Signals instead of special characters. The
receiver sets CTs to the space voltage when it is ready to receive more data and to the mark voltage when it is not ready. Likewise, the
sender sets rts to the space voltage when it is ready to send more data. Because hardware flow control uses a separate set of signals, it
is much faster than software flow control which needs to send or receive multiple bits of information to do the same thing CTS/ RTS
flow control is not supported by all hardware or operating systems
What s a break?
第5页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umn.edustrupp/serial.html#contents
Normally a receive or transmit data signal stays at the mark voltage until a new character is transferred. If the signal is dropped to the
space voltage for a long period of time, usually 1/4 to 1/2 second, then a break condition is said to exist
a break is sometimes used to reset a communications line or change the operating mode of communications hardware like a modem
Chapter 3, Talking to MODEMs covers these applications in more depth
Synchronous Communications
Unlike asynchronous data, synchronous data appears as a constant stream of bits. To read the data on the line, the computer must
provide or receive a common bit clock so that both the sender and receiver are synchronized
Even with this synchronization, the computer must mark the beginning of the data somehow. The most common way of doing this is to
use a data packet protocol like Serial Data Link Control ("SDlC )or High-Speed Data Link Control ("HDLC")
Each protocol defines certain bit sequences to represent the beginning and end of a data packet Each also defines a bit sequence that is
used when there is no data. These bit sequences allow the computer see the beginning of a data packet
Because synchronous protocols do not use per-character synchronization bits they typically provide at least a 25% improvement in
performance over asynchronous communications and are suitable for remote networking and configurations with more than two serial
interfaces
Despite the speed advantages of synchronous communications, most Rs-232 hardware does not support it due to the extra hardware and
software required
Accessing Serial Ports
Like all devices, UNIX provides access to serial ports via device files. To access a serial port you simply open the corresponding device
file
Serial Port filles
Each serial port on a UNIX System has one or more device files(files in the /dev directory) associated with it
Table 2-Serial port Device files
sⅤstem
Port 1
Port 2
IRIXR
Vdev/tyfl /dev/ty f2
HP-UX
/dev/tty l po/dev/tty 2pO
Solaris R/SunOS(R/ dev/ttya /dev/ttyb
LinuX R
/dev/ttys0 /dev/ttyS1
Digital uNiX dev/ttyo1 /dev/tty02
Opening a serial Port
Since a serial port is a file, the open (2) function is used to access it. The one hitch with uNiX is that device files are usually not
accessable by normal users. Workarounds include changing the access permissions to the file(s)in question, running your program as the
super-user(root), or making your program set-userid so that it runs as the owner of the device file
第6页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umn.edustrupp/serial.html#contents
For now we ll assume that the file is accessable by all users. The code to open serial port 1 on an sgiB workstation running IrIX is
Listing 1-Opening a serial port
#include
k standard input/output de=initions */
#include /* String function definitions *
#include /* UNIx standard function definitions
#include /* File control definitions *
#include errno.h> /* Error number definitions
#include /* posix terminal control definitions *
x 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 x
fd oper("/dev/ttyfl",O RDWR I C NOCTTY O NDELAY)
if(fd==-1)
大Cou1 d not open the port
perrcr("open port: Unable to open /dev/ttyf1
}
else
fcntl(fd, F stFt o)i
return (fd)
Other systems would require the corresponding device file name, but otherwise the code is the same
Open Options
You' ll notice that when we opened the device file we used two other flags along with the read-+ write mode
fd= open("/dev/ttyf1", O RDWR I O NOCTTY I O NDE-AY)i
The O NOCTTY flag tells UNIX that this program doesn't want to be the"controlling terminal "for that port. If you don' t specify this
then any input(such as keyboard abort signals and so forth)will affect your process. Programs like getty(1M/8 )use this feature when
starting the login process, but normally a user program does not want this behavior
The O NDELAy flag tells UNIX that this program doesn't care what state the dCd signal line is in-whether the other end of the port is
up and running. If you do not specify this flag, your process will be put to sleep until the dCd signal line is the space voltage
Writing data to the port
Writing data to the port is easy-just use the write(2) system call to send data it
n= write(fd,AZ\2,4)
f(n<0)
puts("write()of 1 bytes failed! \n", stderr)i
第7页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umnedu/strupp/serial.html#contents
The write function returns the number of bytes sent or-l if an error occurred Usually the only error you ll run into is elo when a
MODEM or data link drops the Data Carrier Detect (DCD) line. This condition will persist until you close the port
Reading data from the Port
Reading data from a port is a little trickier. When you operate the port in raw data mode, each read(2) system call will return however
many characters are actually available in the serial input buffers. If no characters are available, the call will block(wait)until characters
come in, an interval timer expires, or an error occurs. The read function can be made to return immediately by doing the following
fcntl(fd, F SETFL, FNDELAY
The FNDELAY option causes the read function to return 0 if no characters are available on the port. To restore normal (blocking)
behavior, call cnllo without the FNDELAY option
fcntl(fd, F SETFL, 0)
This is also used after opening a serial port with theo ndelay option
Closing a serial Port
To close the serial port, just use the close system call
close(fd)i
Closing a serial port will also usually set the dtR signal low which causes most MODEMs to hang up
Chapter 2, Configuring the Serial Port
This chapter discusses how to configure a serial port from C using the PosiX termios interface
The posix terminal Interface
Most systems support the POSIX terminal(serial) interface for changing parameters such as baud rate, character size, and so on. The
first thing you need to do is include the file ; this defines the terminal control structure as well as the POsIX control
functions
The two most important POSIX functions are tcgetattr (3) and tcsetattr (3) These get and set terminal attributes, respectively; you
provide a pointer to a termios structure that contains all of the serial options available
Table 3- Termios Structure members
Member
Description
c cflag
Control options
c lfas
8
Line options
ifl
g
put options
oflag Output options
c cC
Control characters
Ic_ispeed Input baud(new interface)
第8页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umnedu/strupp/serial.html#contents
c spee
Output baud (new interface)
Control Options
The c cflag member controls the baud rate, number of data bits, parity, stop bits, and hardware flow control. There are constants for all
of the supported configurations
Table 4-Constants for the c cflag member
Constant
Description
BAUD
Bit mask for baud rate
Bo
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
200 baud
Bl800
1800 baud
B2400
2400 baud
B4800
4800 baud
B9600
9600 baud
B19200
19200 baud
B38400
38400 baud
B57600
57,600baud
B76800
76800 baud
B115200
115,200baud
EXTA
External rate clock
EXTB
External rate clock
CSIZE
Bit mask for data bits
CS5
data bits
CS6
6 data bits
CS7
7 data bits
CS8
8 data bits
CSTOPB 2 stop bits(I otherwise)
CREAD
Enable receiver
PARenT
Enable parity bit
PARODI
Use odd parity instead of even
HUPCL
Hangup( drop DTR)on last close
第9页共26页
Serial programming Guide for posiX Operating Systems
https://www.cmrr.umnedu/strupp/serial.htm1#contents
CLOCAL
Local line -do not change"owner"of port
LOBLK
Block job control output
CNEW RTSCTS Enable hardware flow control(not
CRTSCTS
supported on all platforms)
The c cflag member contains two options that should always be enabled, CLOCAL and CREAD. These will ensure that your program
does not become the ownerof the port subject to sporatic job control and hangup signals, and also that the serial interface driver will
read incoming data bytes
The baud rate constantS(CBAUD, B9600, etc. ) are used for older interfaces that lack the c ispeed and c speed members. See the next
section for in formation on the posix functions used to set the baud rate
Never initialize the c cflag(or any other flag) member directly; you should always use the bitwise AND, OR, and not operators to set
or clear bits in the members. Different operating system versions(and even patches) can and do use the bits differently, so using the
bitwise operators will prevent you from clobbering a bit flag that is needed in a newer serial driver
Setting the Baud Rate
using one of the baud rate constants in table 4, while newer implementations provide the c ispeed and c-ospeed members that contai
The baud rate is stored in different places depending on the operating system. Older interfaces store the baud rate in the c cflag member
the actual baud rate value
The cfsetospeed (3) and cfsetispeed functions are provided to set the baud rate in the termios structure regardless of the underlying
operating system interface. Typically you'd use the following code to set the baud rate
Listing 2- Sctting the baud rate
struct termios options
Cet the current opions for the pcrt
tcgetattr(fd, &options)i
x Set the baud rates = o 19200.
cfsetispeed(&options, B19200
cfsetospeed(&options, B19200)
Enable the receiver and set local mode
options.c cflag
(CLOCAL I CREAD);
Set the new options for the port
tcsctattr(fd, TCSANOW, options)i
The tcgetattr() function fills the termios structure you provide with the current serial port configuration. After we set the baud rates and
enable local mode and serial data receipt, we select the new configuration using tcsetattr(3). The TCSANOW constant specifies that all
changes should occur immediately without waiting for output data to finish sending or input data to finish receiving. There are other
constants to wait for input and output to finish or to flush the input and output buffers
第10页共26页
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.