linux下串口通讯相关资料

Serial Programming HOWTO(老外写得,还不错)
Linux 下串口编程入门
 LINUX 串口通讯源码
Linux操作系统下的串口通信学习笔记
 关于Linux下串口通信的一点心得


Serial Programming HOWTO


Gary Frerking

牋牋牋牋gary@frerking.org
牋牋牋

Peter Baumann

Revision History
Revision 1.01 2001-08-26 Revised by: glf
New maintainer, converted to DocBook
Revision 1.0 1998-01-22 Revised by: phb
Initial document release


This document describes how to program communications with devices over a
serial port on a Linux box.

-----------------------------------------------------------------------------
Table of Contents
1. Introduction
1.1. Copyright Information
1.2. Disclaimer
1.3. New Versions
1.4. Credits
1.5. Feedback


2. Getting started
2.1. Debugging
2.2. Port Settings
2.3. Input Concepts for Serial Devices
2.3.1. Canonical Input Processing
2.3.2. Non-Canonical Input Processing
2.3.3. Asynchronous Input
2.3.4. Waiting for Input from Multiple Sources




3. Program Examples
3.1. Canonical Input Processing
3.2. Non-Canonical Input Processing
3.3. Asynchronous Input
3.4. Waiting for Input from Multiple Sources


4. Other Sources of Information

-----------------------------------------------------------------------------
1. Introduction

This is the Linux Serial Programming HOWTO. All about how to program
communications with other devices / computers over a serial line under Linux.
Different techniques are explained: Canonical I/O (only complete lines are
transmitted/received), asyncronous I/O, and waiting for input from multiple
sources.

This is the first update to the initial release of the Linux Serial
Programming HOWTO. The primary purpose of this update is to change the author
information and convert the document to DocBook format. In terms of technical
content, very little if anything has changed at this time. Sweeping changes
to the technical content aren't going to happen overnight, but I'll work on
it as much as time allows.

If you've been waiting in the wings for someone to take over this HOWTO,
you've gotten your wish. Please send me any and all feedback you have, it'd
be very much appreciated.

All examples were tested using a i386 Linux Kernel 2.0.29.
-----------------------------------------------------------------------------

1.1. Copyright Information

This document is copyrighted (c) 1997 Peter Baumann, (c) 2001 Gary Frerking
and is distributed under the terms of the Linux Documentation Project (LDP)
license, stated below.

Unless otherwise stated, Linux HOWTO documents are copyrighted by their
respective authors. Linux HOWTO documents may be reproduced and distributed
in whole or in part, in any medium physical or electronic, as long as this
copyright notice is retained on all copies. Commercial redistribution is
allowed and encouraged; however, the author would like to be notified of any
such distributions.

All translations, derivative works, or aggregate works incorporating any
Linux HOWTO documents must be covered under this copyright notice. That is,
you may not produce a derivative work from a HOWTO and impose additional
restrictions on its distribution. Exceptions to these rules may be granted
under certain conditions; please contact the Linux HOWTO coordinator at the
address given below.

In short, we wish to promote dissemination of this information through as
many channels as possible. However, we do wish to retain copyright on the
HOWTO documents, and would like to be notified of any plans to redistribute
the HOWTOs.

If you have any questions, please contact <linux-howto@metalab.unc.edu>
-----------------------------------------------------------------------------

1.2. Disclaimer

No liability for the contents of this documents can be accepted. Use the
concepts, examples and other content at your own risk. As this is a new
edition of this document, there may be errors and inaccuracies, that may of
course be damaging to your system. Proceed with caution, and although this is
highly unlikely, the author(s) do not take any responsibility for that.

All copyrights are held by their by their respective owners, unless
specifically noted otherwise. Use of a term in this document should not be
regarded as affecting the validity of any trademark or service mark.

Naming of particular products or brands should not be seen as endorsements.

You are strongly recommended to take a backup of your system before major
installation and backups at regular intervals.
-----------------------------------------------------------------------------

1.3. New Versions

As previously mentioned, not much is new in terms of technical content yet.
-----------------------------------------------------------------------------

1.4. Credits

The original author thanked Mr. Strudthoff, Michael Carter, Peter Waltenberg,
Antonino Ianella, Greg Hankins, Dave Pfaltzgraff, Sean Lincolne, Michael
Wiedmann, and Adrey Bonar.
-----------------------------------------------------------------------------

1.5. Feedback

Feedback is most certainly welcome for this document. Without your
submissions and input, this document wouldn't exist. Please send your
additions, comments and criticisms to the following email address : <
gary@frerking.org>.
-----------------------------------------------------------------------------

2. Getting started

2.1. Debugging

The best way to debug your code is to set up another Linux box, and connect
the two computers via a null-modem cable. Use miniterm (available from the
LDP programmers guide (ftp://sunsite.unc.edu/pub/Linux/docs/LDP/
programmers-guide/lpg-0.4.tar.gz in the examples directory) to transmit
characters to your Linux box. Miniterm can be compiled very easily and will
transmit all keyboard input raw over the serial port. Only the define
statement #define MODEMDEVICE "/dev/ttyS0" has to be checked. Set it to ttyS0
for COM1, ttyS1 for COM2, etc.. It is essential for testing, that all
characters are transmitted raw (without output processing) over the line. To
test your connection, start miniterm on both computers and just type away.
The characters input on one computer should appear on the other computer and
vice versa. The input will not be echoed to the attached screen.

To make a null-modem cable you have to cross the TxD (transmit) and RxD
(receive) lines. For a description of a cable see sect. 7 of the
Serial-HOWTO.

It is also possible to perform this testing with only one computer, if you
have two unused serial ports. You can then run two miniterms off two virtual
consoles. If you free a serial port by disconnecting the mouse, remember to
redirect /dev/mouse if it exists. If you use a multiport serial card, be sure
to configure it correctly. I had mine configured wrong and everything worked
fine as long as I was testing only on my computer. When I connected to
another computer, the port started loosing characters. Executing two programs
on one computer just isn't fully asynchronous.
-----------------------------------------------------------------------------

2.2. Port Settings

The devices /dev/ttyS* are intended to hook up terminals to your Linux box,
and are configured for this use after startup. This has to be kept in mind
when programming communication with a raw device. E.g. the ports are
configured to echo characters sent from the device back to it, which normally
has to be changed for data transmission.

All parameters can be easily configured from within a program. The
configuration is stored in a structure struct termios, which is defined in <
asm/termbits.h>:
+---------------------------------------------------------------------------+
| #define NCCS 19 |
| struct termios { |
| tcflag_t c_iflag; /* input mode flags */ |
| tcflag_t c_oflag; /* output mode flags */ |
| tcflag_t c_cflag; /* control mode flags */ |
| tcflag_t c_lflag; /* local mode flags */ |
| cc_t c_line; /* line discipline */ |
| cc_t c_cc[NCCS]; /* control characters */ |
| }; |
| |
+---------------------------------------------------------------------------+

This file also includes all flag definitions. The input mode flags in c_iflag
handle all input processing, which means that the characters sent from the
device can be processed before they are read with read. Similarly c_oflag
handles the output processing. c_cflag contains the settings for the port, as
the baudrate, bits per character, stop bits, etc.. The local mode flags
stored in c_lflag determine if characters are echoed, signals are sent to
your program, etc.. Finally the array c_cc defines the control characters for
end of file, stop, etc.. Default values for the control characters are
defined in <asm/termios.h>. The flags are described in the manual page
termios(3). The structure termios contains the c_line (line discipline)
element, which is not used in POSIX compliant systems.
-----------------------------------------------------------------------------

2.3. Input Concepts for Serial Devices

Here three different input concepts will be presented. The appropriate
concept has to be chosen for the intended application. Whenever possible, do
not loop reading single characters to get a complete string. When I did this,
I lost characters, whereas a read for the whole string did not show any
errors.
-----------------------------------------------------------------------------

2.3.1. Canonical Input Processing

This is the normal processing mode for terminals, but can also be useful for
communicating with other dl input is processed in units of lines, which means
that a read will only return a full line of input. A line is by default
terminated by a NL (ASCII LF), an end of file, or an end of line character. A
CR (the DOS/Windows default end-of-line) will not terminate a line with the
default settings.

Canonical input processing can also handle the erase, delete word, and
reprint characters, translate CR to NL, etc..
-----------------------------------------------------------------------------

2.3.2. Non-Canonical Input Processing

Non-Canonical Input Processing will handle a fixed amount of characters per
read, and allows for a character timer. This mode should be used if your
application will always read a fixed number of characters, or if the
connected device sends bursts of characters.
-----------------------------------------------------------------------------

2.3.3. Asynchronous Input

The two modes described above can be used in synchronous and asynchronous
mode. Synchronous is the default, where a read statement will block, until
the read is satisfied. In asynchronous mode the read statement will return
immediatly and send a signal to the calling program upon completion. This
signal can be received by a signal handler.
-----------------------------------------------------------------------------

2.3.4. Waiting for Input from Multiple Sources

This is not a different input mode, but might be useful, if you are handling
multiple devices. In my application I was handling input over a TCP/IP socket
and input over a serial connection from another computer
quasi-simultaneously. The program example given below will wait for input
from two different input sources. If input from one source becomes available,
it will be processed, and the program will then wait for new input.

The approach presented below seems rather complex, but it is important to
keep in mind that Linux is a multi-processing operating system. The select
system call will not load the CPU while waiting for input, whereas looping
until input becomes available would slow down other processes executing at
the same time.
-----------------------------------------------------------------------------

3. Program Examples

All examples have been derived from miniterm.c. The type ahead buffer is
limited to 255 characters, just like the maximum string length for canonical
input processing (<linux/limits.h> or <posix1_lim.h>).

See the comments in the code for explanation of the use of the different
input modes. I hope that the code is understandable. The example for
canonical input is commented best, the other examples are commented only
where they differ from the example for canonical input to emphasize the
differences.

The descriptions are not complete, but you are encouraged to experiment with
the examples to derive the best solution for your application.

Don't forget to give the appropriate serial ports the right permissions (e.
g.: chmod a+rw /dev/ttyS1)!
-----------------------------------------------------------------------------

3.1. Canonical Input Processing


+--------------------------------------------------------------------------------------+
| #include <sys/types.h> |
| #include <sys/stat.h> |
| #include <fcntl.h> |
| #include <termios.h> |
| #include <stdio.h> |
| |
| /* baudrate settings are defined in <asm/termbits.h>, which is |
| included by <termios.h> */ |
| #define BAUDRATE B38400 |
| /* change this definition for the correct port */ |
| #define MODEMDEVICE "/dev/ttyS1" |
| #define _POSIX_SOURCE 1 /* POSIX compliant source */ |
| |
| #define FALSE 0 |
| #define TRUE 1 |
| |
| volatile int STOP=FALSE; |
| |
| main() |
| { |
| int fd,c, res; |
| struct termios oldtio,newtio; |
| char buf[255]; |
| /* |
| Open modem device for reading and writing and not as controlling tty |
| because we don't want to get killed if linenoise sends CTRL-C. |
| */ |
| fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY ); |
| if (fd <0) {perror(MODEMDEVICE); exit(-1); } |
| |
| tcgetattr(fd,&oldtio); /* save current serial port settings */ |
| bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */ |
| |
| /* |
| BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed. |
| CRTSCTS : output hardware flow control (only used if the cable has |
| all necessary lines. See sect. 7 of Serial-HOWTO) |
| CS8 : 8n1 (8bit,no parity,1 stopbit) |
| CLOCAL : local connection, no modem contol |
| CREAD : enable receiving characters |
| */ |
| newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; |
| |
| /* |
| IGNPAR : ignore bytes with parity errors |
| ICRNL : map CR to NL (otherwise a CR input on the other computer |
| will not terminate input) |
| otherwise make device raw (no other input processing) |
| */ |
| newtio.c_iflag = IGNPAR | ICRNL; |
| |
| /* |
| Raw output. |
| */ |
| newtio.c_oflag = 0; |
| |
| /* |
| ICANON : enable canonical input |
| disable all echo functionality, and don't send signals to calling program |
| */ |
| newtio.c_lflag = ICANON; |
| |
| /* |
| initialize all control characters |
| default values can be found in /usr/include/termios.h, and are given |
| in the comments, but we don't need them here |
| */ |
| newtio.c_cc[VINTR] = 0; /* Ctrl-c */ |
| newtio.c_cc[VQUIT] = 0; /* Ctrl-/ */ |
| newtio.c_cc[VERASE] = 0; /* del */ |
| newtio.c_cc[VKILL] = 0; /* @ */ |
| newtio.c_cc[VEOF] = 4; /* Ctrl-d */ |
| newtio.c_cc[VTIME] = 0; /* inter-character timer unused */ |
| newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */ |
| newtio.c_cc[VSWTC] = 0; /* '/0' */ |
| newtio.c_cc[VSTART] = 0; /* Ctrl-q */ |
| newtio.c_cc[VSTOP] = 0; /* Ctrl-s */ |
| newtio.c_cc[VSUSP] = 0; /* Ctrl-z */ |
| newtio.c_cc[VEOL] = 0; /* '/0' */ |
| newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */ |
| newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */ |
| newtio.c_cc[VWERASE] = 0; /* Ctrl-w */ |
| newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */ |
| newtio.c_cc[VEOL2] = 0; /* '/0' */ |
| |
| /* |
| now clean the modem line and activate the settings for the port |
| */ |
| tcflush(fd, TCIFLUSH); |
| tcsetattr(fd,TCSANOW,&newtio); |
| |
| /* |
| terminal settings done, now handle input |
| In this example, inputting a 'z' at the beginning of a line will |
| exit the program. |
| */ |
| while (STOP==FALSE) { /* loop until we have a terminating condition */ |
| /* read blocks program execution until a line terminating character is |
| input, even if more than 255 chars are input. If the number |
| of characters read is smaller than the number of chars available, |
| subsequent reads will return the remaining chars. res will be set |
| to the actual number of characters actually read */ |
| res = read(fd,buf,255); |
| buf[res]=0; /* set end of string, so we can printf */ |
| printf(":%s:%d/n", buf, res); |
| if (buf[0]=='z') STOP=TRUE; |
| } |
| /* restore the old port settings */ |
| tcsetattr(fd,TCSANOW,&oldtio); |
| } |
| |
| |
+--------------------------------------------------------------------------------------+
-----------------------------------------------------------------------------

3.2. Non-Canonical Input Processing

In non-canonical input processing mode, input is not assembled into lines and
input processing (erase, kill, delete, etc.) does not occur. Two parameters
control the behavior of this mode: c_cc[VTIME] sets the character timer, and
c_cc[VMIN] sets the minimum number of characters to receive before satisfying
the read.

If MIN > 0 and TIME = 0, MIN sets the number of characters to receive before
the read is satisfied. As TIME is zero, the timer is not used.

If MIN = 0 and TIME > 0, TIME serves as a timeout value. The read will be
satisfied if a single character is read, or TIME is exceeded (t = TIME *0.1
s). If TIME is exceeded, no character will be returned.

If MIN > 0 and TIME > 0, TIME serves as an inter-character timer. The read
will be satisfied if MIN characters are received, or the time between two
characters exceeds TIME. The timer is restarted every time a character is
received and only becomes active after the first character has been received.

If MIN = 0 and TIME = 0, read will be satisfied immediately. The number of
characters currently available, or the number of characters requested will be
returned. According to Antonino (see contributions), you could issue a fcntl
(fd, F_SETFL, FNDELAY); before reading to get the same result.

By modifying newtio.c_cc[VTIME] and newtio.c_cc[VMIN] all modes described
above can be tested.


+--------------------------------------------------------------------------------+
| #include <sys/types.h> |
| #include <sys/stat.h> |
| #include <fcntl.h> |
| #include <termios.h> |
| #include <stdio.h> |
| |
| #define BAUDRATE B38400 |
| #define MODEMDEVICE "/dev/ttyS1" |
| #define _POSIX_SOURCE 1 /* POSIX compliant source */ |
| #define FALSE 0 |
| #define TRUE 1 |
| |
| volatile int STOP=FALSE; |
| |
| main() |
| { |
| int fd,c, res; |
| struct termios oldtio,newtio; |
| char buf[255]; |
| |
| fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY ); |
| if (fd <0) {perror(MODEMDEVICE); exit(-1); } |
| |
| tcgetattr(fd,&oldtio); /* save current port settings */ |
| |
| bzero(&newtio, sizeof(newtio)); |
| newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; |
| newtio.c_iflag = IGNPAR; |
| newtio.c_oflag = 0; |
| |
| /* set input mode (non-canonical, no echo,...) */ |
| newtio.c_lflag = 0; |
| |
| newtio.c_cc[VTIME] = 0; /* inter-character timer unused */ |
| newtio.c_cc[VMIN] = 5; /* blocking read until 5 chars received */ |
| |
| tcflush(fd, TCIFLUSH); |
| tcsetattr(fd,TCSANOW,&newtio); |
| |
| |
| while (STOP==FALSE) { /* loop for input */ |
| res = read(fd,buf,255); /* returns after 5 chars have been input */ |
| buf[res]=0; /* so we can printf... */ |
| printf(":%s:%d/n", buf, res); |
| if (buf[0]=='z') STOP=TRUE; |
| } |
| tcsetattr(fd,TCSANOW,&oldtio); |
| } |
| |
+--------------------------------------------------------------------------------+
-----------------------------------------------------------------------------

3.3. Asynchronous Input


+-----------------------------------------------------------------------------------+
| #include <termios.h> |
| #include <stdio.h> |
| #include <unistd.h> |
| #include <fcntl.h> |
| #include <sys/signal.h> |
| #include <sys/types.h> |
| |
| #define BAUDRATE B38400 |
| #define MODEMDEVICE "/dev/ttyS1" |
| #define _POSIX_SOURCE 1 /* POSIX compliant source */ |
| #define FALSE 0 |
| #define TRUE 1 |
| |
| volatile int STOP=FALSE; |
| |
| void signal_handler_IO (int status); /* definition of signal handler */ |
| int wait_flag=TRUE; /* TRUE while no signal received */ |
| |
| main() |
| { |
| int fd,c, res; |
| struct termios oldtio,newtio; |
| struct sigaction saio; /* definition of signal action */ |
| char buf[255]; |
| |
| /* open the device to be non-blocking (read will return immediatly) */ |
| fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK); |
| if (fd <0) {perror(MODEMDEVICE); exit(-1); } |
| |
| /* install the signal handler before making the device asynchronous */ |
| saio.sa_handler = signal_handler_IO; |
| saio.sa_mask = 0; |
| saio.sa_flags = 0; |
| saio.sa_restorer = NULL; |
| sigaction(SIGIO,&saio,NULL); |
| |
| /* allow the process to receive SIGIO */ |
| fcntl(fd, F_SETOWN, getpid()); |
| /* Make the file descriptor asynchronous (the manual page says only |
| O_APPEND and O_NONBLOCK, will work with F_SETFL...) */ |
| fcntl(fd, F_SETFL, FASYNC); |
| |
| tcgetattr(fd,&oldtio); /* save current port settings */ |
| /* set new port settings for canonical input processing */ |
| newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; |
| newtio.c_iflag = IGNPAR | ICRNL; |
| newtio.c_oflag = 0; |
| newtio.c_lflag = ICANON; |
| newtio.c_cc[VMIN]=1; |
| newtio.c_cc[VTIME]=0; |
| tcflush(fd, TCIFLUSH); |
| tcsetattr(fd,TCSANOW,&newtio); |
| |
| /* loop while waiting for input. normally we would do something |
| useful here */ |
| while (STOP==FALSE) { |
| printf("./n");usleep(100000); |
| /* after receiving SIGIO, wait_flag = FALSE, input is available |
| and can be read */ |
| if (wait_flag==FALSE) { |
| res = read(fd,buf,255); |
| buf[res]=0; |
| printf(":%s:%d/n", buf, res); |
| if (res==1) STOP=TRUE; /* stop loop if only a CR was input */ |
| wait_flag = TRUE; /* wait for new input */ |
| } |
| } |
| /* restore old port settings */ |
| tcsetattr(fd,TCSANOW,&oldtio); |
| } |
| |
| /*************************************************************************** |
| * signal handler. sets wait_flag to FALSE, to indicate above loop that * |
| * characters have been received. * |
| ***************************************************************************/ |
| |
| void signal_handler_IO (int status) |
| { |
| printf("received SIGIO signal./n"); |
| wait_flag = FALSE; |
| } |
| |
+-----------------------------------------------------------------------------------+
-----------------------------------------------------------------------------

3.4. Waiting for Input from Multiple Sources

This section is kept to a minimum. It is just intended to be a hint, and
therefore the example code is kept short. This will not only work with serial
ports, but with any set of file descriptors.

The select call and accompanying macros use a fd_set. This is a bit array,
which has a bit entry for every valid file descriptor number. select will
accept a fd_set with the bits set for the relevant file descriptors and
returns a fd_set, in which the bits for the file descriptors are set where
input, output, or an exception occurred. All handling of fd_set is done with
the provided macros. See also the manual page select(2).


+---------------------------------------------------------------------------+
| #include <sys/time.h> |
| #include <sys/types.h> |
| #include <unistd.h> |
| |
| main() |
| { |
| int fd1, fd2; /* input sources 1 and 2 */ |
| fd_set readfs; /* file descriptor set */ |
| int maxfd; /* maximum file desciptor used */ |
| int loop=1; /* loop while TRUE */ |
| |
| /* open_input_source opens a device, sets the port correctly, and |
| returns a file descriptor */ |
| fd1 = open_input_source("/dev/ttyS1"); /* COM2 */ |
| if (fd1<0) exit(0); |
| fd2 = open_input_source("/dev/ttyS2"); /* COM3 */ |
| if (fd2<0) exit(0); |
| maxfd = MAX (fd1, fd2)+1; /* maximum bit entry (fd) to test */ |
| |
| /* loop for input */ |
| while (loop) { |
| FD_SET(fd1, &readfs); /* set testing for source 1 */ |
| FD_SET(fd2, &readfs); /* set testing for source 2 */ |
| /* block until input becomes available */ |
| select(maxfd, &readfs, NULL, NULL, NULL); |
| if (FD_ISSET(fd1)) /* input from source 1 available */ |
| handle_input_from_source1(); |
| if (FD_ISSET(fd2)) /* input from source 2 available */ |
| handle_input_from_source2(); |
| } |
| } |
| |
+---------------------------------------------------------------------------+

The given example blocks indefinitely, until input from one of the sources
becomes available. If you need to timeout on input, just replace the select
call by:
+----------------------------------------------------------------------------+
| int res; |
| struct timeval Timeout; |
| |
| /* set timeout value within input loop */ |
| Timeout.tv_usec = 0; /* milliseconds */ |
| Timeout.tv_sec = 1; /* seconds */ |
| res = select(maxfd, &readfs, NULL, NULL, &Timeout); |
| if (res==0) |
| /* number of file descriptors with input = 0, timeout occurred. */ |
| |
+----------------------------------------------------------------------------+

This example will timeout after 1 second. If a timeout occurs, select will
return 0, but beware that Timeout is decremented by the time actually waited
for input by select. If the timeout value is zero, select will return
immediatly.
-----------------------------------------------------------------------------

4. Other Sources of Information



牋*燭he Linux Serial-HOWTO describes how to set up serial ports and contains
hardware information.

牋*燵http://www.easysw.com/~mike/serial] Serial Programming Guide for POSIX
Compliant Operating Systems, by Michael Sweet.

牋*燭he manual page termios(3) describes all flags for the termios structure.

Linux 下串口编程入门

developerWorks
文档选项
<script type="text/javascript" language="JavaScript"> </script>
将此页作为电子邮件发送

将此页作为电子邮件发送


级别: 初级

左锦 (zuo170@163.com), 副总裁, 南沙资讯科技园

2003 年 7 月 03 日

Linux 操作系统从一开始就对串行口提供了很好的支持,本文就 Linux 下的串行口通讯编程进行简单的介绍。

串口简介

串 行口是计算机一种常用的接口,具有连接线少,通讯简单,得到广泛的使用。常用的串口是 RS-232-C 接口(又称 EIA RS-232-C)它是在 1970 年由美国电子工业协会(EIA)联合贝尔系统、 调制解调器厂家及计算机终端生产厂家共同制定的用于串行通讯的标准。它的全名是"数据终端设备(DTE)和数据通讯设备(DCE)之间串行二进制数据交换 接口技术标准"该标准规定采用一个 25 个脚的 DB25 连接器,对连接器的每个引脚的信号内容加以规定,还对各种信号的电平加以规定。传输距离在码元畸变小于 4% 的情况下,传输电缆长度应为 50 英尺。

Linux 操作系统从一开始就对串行口提供了很好的支持,本文就 Linux 下的串行口通讯编程进行简单的介绍,如果要非常深入了解,建议看看本文所参考的 《Serial Programming Guide for POSIX Operating Systems》

计算机串口的引脚说明

序号信号名称符号流向功能
2发送数据TXDDTE→DCEDTE发送串行数据
3接收数据RXDDTE←DCEDTE 接收串行数据
4请求发送RTSDTE→DCEDTE 请求 DCE 将线路切换到发送方式
5允许发送CTSDTE←DCEDCE 告诉 DTE 线路已接通可以发送数据
6数据设备准备好DSRDTE←DCEDCE 准备好
7信号地     信号公共地
8载波检测DCDDTE←DCE表示 DCE 接收到远程载波
20数据终端准备好DTRDTE→DCEDTE 准备好
22振铃指示RIDTE←DCE表示 DCE 与线路接通,出现振铃




回页首


串口操作

串口操作需要的头文件

#include     <stdio.h>      /*标准输入输出定义*/
#include <stdlib.h> /*标准函数库定义*/
#include <unistd.h> /*Unix 标准函数定义*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX 终端控制定义*/
#include <errno.h> /*错误号定义*/





回页首


打开串口

在 Linux 下串口文件是位于 /dev 下的

串口一 为 /dev/ttyS0

串口二 为 /dev/ttyS1

打开串口是通过使用标准的文件打开函数操作:

int fd;
/*以读写方式打开串口*/
fd = open( "/dev/ttyS0", O_RDWR);
if (-1 == fd){
/* 不能打开串口一*/
perror(" 提示错误!");
}





回页首


设置串口

最基本的设置串口包括波特率设置,效验位和停止位设置。

串口的设置主要是设置 struct termios 结构体的各成员值。

struct termio
{ unsigned short c_iflag; /* 输入模式标志 */
unsigned short c_oflag; /* 输出模式标志 */
unsigned short c_cflag; /* 控制模式标志*/
unsigned short c_lflag; /* local mode flags */
unsigned char c_line; /* line discipline */
unsigned char c_cc[NCC]; /* control characters */
};

设置这个结构体很复杂,我这里就只说说常见的一些设置:

波特率设置

下面是修改波特率的代码:

struct  termios Opt;
tcgetattr(fd, &Opt);
cfsetispeed(&Opt,B19200); /*设置为19200Bps*/
cfsetospeed(&Opt,B19200);
tcsetattr(fd,TCANOW,&Opt);

设置波特率的例子函数:

/**
*@brief 设置串口通信速率
*@param fd 类型 int 打开串口的文件句柄
*@param speed 类型 int 串口速度
*@return void
*/
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400,
19200, 9600, 4800, 2400, 1200, 300, };
void set_speed(int fd, int speed){
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) {
if (speed == name_arr[i]) {
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, speed_arr[i]);
cfsetospeed(&Opt, speed_arr[i]);
status = tcsetattr(fd1, TCSANOW, &Opt);
if (status != 0) {
perror("tcsetattr fd1");
return;
}
tcflush(fd,TCIOFLUSH);
}
}
}

效验位和停止位的设置:

无效验8位 Option.c_cflag &= ~PARENB;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS8;
奇效验(Odd)7位 Option.c_cflag |= ~PARENB;
Option.c_cflag &= ~PARODD;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS7;
偶效验(Even)7位 Option.c_cflag &= ~PARENB;
Option.c_cflag |= ~PARODD;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= ~CSIZE;
Option.c_cflag |= ~CS7;
Space效验7位 Option.c_cflag &= ~PARENB;
Option.c_cflag &= ~CSTOPB;
Option.c_cflag &= &~CSIZE;
Option.c_cflag |= CS8;

设置效验的函数:

/**
*@brief 设置串口数据位,停止位和效验位
*@param fd 类型 int 打开的串口文件句柄
*@param databits 类型 int 数据位 取值 为 7 或者8
*@param stopbits 类型 int 停止位 取值为 1 或者2
*@param parity 类型 int 效验类型 取值为N,E,O,,S
*/
int set_Parity(int fd,int databits,int stopbits,int parity)
{
struct termios options;
if ( tcgetattr( fd,&options) != 0) {
perror("SetupSerial 1");
return(FALSE);
}
options.c_cflag &= ~CSIZE;
switch (databits) /*设置数据位数*/
{
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unsupported data size/n"); return (FALSE);
}
switch (parity)
{
case 'n':
case 'N':
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_iflag &= ~INPCK; /* Enable parity checking */
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
options.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'e':
case 'E':
options.c_cflag |= PARENB; /* Enable parity */
options.c_cflag &= ~PARODD; /* 转换为偶效验*/
options.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'S':
case 's': /*as no parity*/
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;break;
default:
fprintf(stderr,"Unsupported parity/n");
return (FALSE);
}
/* 设置停止位*/
switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits/n");
return (FALSE);
}
/* Set input parity option */
if (parity != 'n')
options.c_iflag |= INPCK;
tcflush(fd,TCIFLUSH);
options.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
options.c_cc[VMIN] = 0; /* Update the options and do it NOW */
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("SetupSerial 3");
return (FALSE);
}
return (TRUE);
}

需要注意的是:

如果不是开发终端之类的,只是串口传输数据,而不需要串口来处理,那么使用原始模式(Raw Mode)方式来通讯,设置方式如下:

options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
options.c_oflag &= ~OPOST; /*Output*/





回页首


读写串口

设置好串口之后,读写串口就很容易了,把串口当作文件读写就是。

  • 发送数据
    char  buffer[1024];int    Length;int    nByte;nByte = write(fd, buffer ,Length)

  • 读取串口数据

    使用文件操作read函数读取,如果设置为原始模式(Raw Mode)传输数据,那么read函数返回的字符数是实际串口收到的字符数。

    可以使用操作文件的函数来实现异步读取,如fcntl,或者select等来操作。

    char  buff[1024];int    Len;int  readByte = read(fd,buff,Len);





回页首


关闭串口

关闭串口就是关闭文件。

close(fd);





回页首


例子

下面是一个简单的读取串口数据的例子,使用了上面定义的一些函数和头文件

/**********************************************************************代码说明:使用串口二测试的,发送的数据是字符,
但是没有发送字符串结束符号,所以接收到后,后面加上了结束符号。我测试使用的是单片机发送数据到第二个串口,测试通过。
**********************************************************************/
#define FALSE -1
#define TRUE 0
/*********************************************************************/
int OpenDev(char *Dev)
{
int fd = open( Dev, O_RDWR ); //| O_NOCTTY | O_NDELAY
if (-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
}
else
return fd;
}
int main(int argc, char **argv){
int fd;
int nread;
char buff[512];
char *dev = "/dev/ttyS1"; //串口二
fd = OpenDev(dev);
set_speed(fd,19200);
if (set_Parity(fd,8,1,'N') == FALSE) {
printf("Set Parity Error/n");
exit (0);
}
while (1) //循环读取数据
{
while((nread = read(fd, buff, 512))>0)
{
printf("/nLen %d/n",nread);
buff[nread+1] = '/0';
printf( "/n%s", buff);
}
}
//close(fd);
// exit (0);
}

LINUX 串口通讯源码

主要函数

int openport(char *Dev) //打开串口

int setport(int fd, int baud,int databits,int stopbits,int parity)//设置串口,波特率,数据位,停止位,校验

int readport(int fd,char *buf,int len,int maxwaittime)//读数据,参数为串口,BUF,长度,超时时间

int writeport(int fd,char *buf,int len)  //发送数据

void clearport(int fd)      //如果出现数据与规约不符合,可以调用这个函数来刷新串口读写数据

 如果有BUG,请大家及时回复给我,EMAIL:41063473@QQ.COM。

#include   <stdio.h>  
#include   <string.h>  
#include   <unistd.h>  
#include   <fcntl.h>  
#include   <errno.h>  
#include   <termios.h>  
#include   <sys/time.h>
int openport(char *Dev)  
 {
 int fd = open( Dev, O_RDWR|O_NOCTTY|O_NDELAY );
 if (-1 == fd) 
 {    
  perror("Can''t Open Serial Port");
  return -1;  
 } 
 else 
  return fd;

 }  
   
int setport(int fd, int baud,int databits,int stopbits,int parity)
{
 int baudrate;
 struct   termios   newtio;  
 switch(baud)
 {
 case 300:
  baudrate=B300;
  break;
 case 600:
  baudrate=B600;
  break;
 case 1200:
  baudrate=B1200;
  break;
 case 2400:
  baudrate=B2400;
  break;
 case 4800:
  baudrate=B4800;
  break;
 case 9600:
  baudrate=B9600;
  break;
 case 19200:
  baudrate=B19200;
  break;
 case 38400:
  baudrate=B38400;
  break;
 default :
  baudrate=B9600;  
  break;
 }
 tcgetattr(fd,&newtio);    
 bzero(&newtio,sizeof(newtio));  
   //setting   c_cflag
 newtio.c_cflag   &=~CSIZE;    
 switch (databits) /*设置数据位数*/
 {  
 case 7:  
  newtio.c_cflag |= CS7; //7位数据位
  break;
 case 8:    
  newtio.c_cflag |= CS8; //8位数据位
  break;  
 default:   
  newtio.c_cflag |= CS8;
  break;    
 }
 switch (parity) //设置校验
 {  
 case 'n':
 case 'N':   
  newtio.c_cflag &= ~PARENB;   /* Clear parity enable */
  newtio.c_iflag &= ~INPCK;     /* Enable parity checking */
  break; 
 case 'o':  
 case 'O':    
  newtio.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/ 
  newtio.c_iflag |= INPCK;             /* Disnable parity checking */
  break; 
 case 'e': 
 case 'E':  
  newtio.c_cflag |= PARENB;     /* Enable parity */   
  newtio.c_cflag &= ~PARODD;   /* 转换为偶效验*/    
  newtio.c_iflag |= INPCK;       /* Disnable parity checking */
  break;
 case 'S':
 case 's':  /*as no parity*/  
     newtio.c_cflag &= ~PARENB;
  newtio.c_cflag &= ~CSTOPB;break; 
 default:  
  newtio.c_cflag &= ~PARENB;   /* Clear parity enable */
  newtio.c_iflag &= ~INPCK;     /* Enable parity checking */
  break;   
 }
 switch (stopbits)//设置停止位
 {  
 case 1:   
  newtio.c_cflag &= ~CSTOPB;  //1
  break; 
 case 2:   
  newtio.c_cflag |= CSTOPB;  //2
    break;
 default: 
  newtio.c_cflag &= ~CSTOPB; 
  break; 
 }
 newtio.c_cc[VTIME] = 0;   
 newtio.c_cc[VMIN] = 0;
 newtio.c_cflag   |=   (CLOCAL|CREAD);
 newtio.c_oflag|=OPOST;
 newtio.c_iflag   &=~(IXON|IXOFF|IXANY);                    
    cfsetispeed(&newtio,baudrate);  
    cfsetospeed(&newtio,baudrate);  
    tcflush(fd,   TCIFLUSH);
 if (tcsetattr(fd,TCSANOW,&newtio) != 0)  
 {
  perror("SetupSerial 3"); 
  return -1; 
 } 
 return 0;
}
int readport(int fd,char *buf,int len,int maxwaittime)//读数据,参数为串口,BUF,长度,超时时间
{
 int no=0;int rc;int rcnum=len;
 struct timeval tv;
 fd_set readfd;
 tv.tv_sec=maxwaittime/1000;    //SECOND
 tv.tv_usec=maxwaittime%1000*1000;  //USECOND
 FD_ZERO(&readfd);
 FD_SET(fd,&readfd);
 rc=select(fd+1,&readfd,NULL,NULL,&tv);
 if(rc>0)
 {
  while(len)
  {
   rc=read(fd,&buf[no],1);
   if(rc>0)
    no=no+1;
   len=len-1;   
  }
  if(no!=rcnum)
   return -1;      //如果收到的长度与期望长度不一样,返回-1
  return rcnum;      //收到长度与期望长度一样,返回长度
 }
 else
 {
  return -1;
 }
 return -1;
}
int writeport(int fd,char *buf,int len)  //发送数据
{
 write(fd,buf,len);
}
void clearport(int fd)      //如果出现数据与规约不符合,可以调用这个函数来刷新串口读写数据
{
 tcflush(fd,TCIOFLUSH);
}
main()  
{  
 int   fd,rc,i,ret;  
 unsigned char rbuf[256];
 unsigned char wbuf[256]="";
 for(i=0;i<256;i++)
  wbuf[i]=i;
 char *dev ="/dev/ttyS0";    //串口号 /dev/ttyS0  对应于串口1
    fd  =  openport(dev);     //打开串口
 if(fd>0)
 {
  ret=setport(fd,4800,8,1,'o');  //设置串口,波特率,数据位,停止位,校验
  if(ret<0)
  {
   printf("Can't Set Serial Port!/n");
   exit(0);
  }
 }
 else
 {
  printf("Can't Open Serial Port!/n");
  exit(0);
 }
 while(1){ 
  rc=readport(fd,rbuf,5,500);   //读取5个字节,超时时间为500毫秒
  if(rc>0)
  {
   writeport(fd,wbuf,rc);
   printf("recv:%d/n",rc);
   for(i=0;i<rc;i++)
   printf("%02x ",rbuf[i]);
   printf("/n");
  }
  else
   printf("recv none/n"); 
 }  
 close(fd);  
}  

 如何在LINUX下实现硬件的自动检测(上)

<script type="text/javascript">function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>  

       这几天,由于长春门检系统项目的需要,涉及到了读卡器信息的串口读取,所以在Linux下串口信息的读取有了一点心得体会。

1.         打开串口

       与其他的关于设备编程的方法一样,在Linux下,操作、控制串口也是通过操作起设备文件进行的。在Linux下,串口的设备文件是/dev/ttyS0/dev/ttyS1等。因此要读写串口,我们首先要打开串口:

       char *dev  = "/dev/ttyS0"; //串口1

       int    fd = open( dev, O_RDWR );

        //| O_NOCTTY | O_NDELAY      

       if (-1 == fd)   

       {                  

              perror("Can't Open Serial Port");

              return -1;       

       }    

       else 

              return fd;

      

2.         设置串口速度

       打开串口成功后,我们就可以对其进行读写了。首先要设置串口的波特率:

       int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,

                      B38400, B19200, B9600, B4800, B2400, B1200, B300, };

int name_arr[] = {38400,  19200,  9600,  4800,  2400,  1200,  300, 38400, 

                                   19200,  9600, 4800, 2400, 1200,  300, };

void set_speed(int fd, int speed){

       int   i;

       int   status;

       struct termios   Opt;

       tcgetattr(fd, &Opt);

       for ( i= 0;  i < sizeof(speed_arr) / sizeof(int);  i++) {

              if  (speed == name_arr[i]) {    

                     tcflush(fd, TCIOFLUSH);    

                     cfsetispeed(&Opt, speed_arr[i]); 

                     cfsetospeed(&Opt, speed_arr[i]);  

                     status = tcsetattr(fd, TCSANOW, &Opt); 

                     if  (status != 0) {       

                            perror("tcsetattr fd"); 

                            return;    

                     }   

                     tcflush(fd,TCIOFLUSH);  

              } 

       }

}

3.         设置串口信息

这主要包括:数据位、停止位、奇偶校验位这些主要的信息。

      /**

*@brief   设置串口数据位,停止位和效验位

*@param  fd     类型  int  打开的串口文件句柄

*@param  databits 类型  int 数据位   取值 为 7 或者8

*@param  stopbits 类型  int 停止位   取值为 1 或者2

*@param  parity  类型  int  效验类型 取值为N,E,O,,S

*/

int set_Parity(int fd,int databits,int stopbits,int parity)

{

       struct termios options;

       if  ( tcgetattr( fd,&options)  !=  0) {

              perror("SetupSerial 1");    

              return(FALSE); 

       }

       options.c_cflag &= ~CSIZE;

       options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/

       options.c_oflag  &= ~OPOST;   /*Output*/

 

       switch (databits) /*设置数据位数*/

       {  

       case 7:          

              options.c_cflag |= CS7;

              break;

       case 8:    

              options.c_cflag |= CS8;

              break;  

       default:   

              fprintf(stderr,"Unsupported data size/n"); return (FALSE); 

       }

switch (parity)

{  

       case 'n':

       case 'N':   

              options.c_cflag &= ~PARENB;   /* Clear parity enable */

              options.c_iflag &= ~INPCK;     /* Enable parity checking */

              break; 

       case 'o':  

       case 'O':    

              options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/ 

              options.c_iflag |= INPCK;             /* Disnable parity checking */

              break; 

       case 'e': 

       case 'E':  

              options.c_cflag |= PARENB;     /* Enable parity */   

              options.c_cflag &= ~PARODD;   /* 转换为偶效验*/    

              options.c_iflag |= INPCK;       /* Disnable parity checking */

              break;

       case 'S':

       case 's':  /*as no parity*/  

           options.c_cflag &= ~PARENB;

              options.c_cflag &= ~CSTOPB;break; 

       default:  

              fprintf(stderr,"Unsupported parity/n");   

              return (FALSE); 

       } 

/* 设置停止位*/ 

switch (stopbits)

{  

       case 1:   

              options.c_cflag &= ~CSTOPB; 

              break; 

       case 2:   

              options.c_cflag |= CSTOPB; 

          break;

       default:   

               fprintf(stderr,"Unsupported stop bits/n"); 

               return (FALSE);

}

/* Set input parity option */

if (parity != 'n')  

       options.c_iflag |= INPCK;

tcflush(fd,TCIFLUSH);

options.c_cc[VTIME] = 0; /* 设置超时0 seconds*/  

options.c_cc[VMIN] = 13; /* define the minimum bytes data to be readed*/

if (tcsetattr(fd,TCSANOW,&options) != 0)  

{

       perror("SetupSerial 3");  

       return (FALSE); 

}

return (TRUE); 

}

在上述代码中,有两句话特别重要:

options.c_cc[VTIME] = 0; /* 设置超时0 seconds*/  

options.c_cc[VMIN] = 13; /* define the minimum bytes data to be readed*/

这两句话决定了对串口读取的函数read()的一些功能。我将着重介绍一下他们对read()函数的影响。

       对串口操作的结构体是

Struct{

       tcflag_t   c_iflag;    /*输入模式标记*/

       tcflag_t   c_oflag;   /*输出模式标记*/

       tcflag_t   c_cflag;   /*控制模式标记*/

       tcflag_t   c_lflag;    /*本地模式标记*/

       cc_t        c_line;     /*线路规程*/

       cc_t        c_cc[NCCS];  /*控制符号*/

}

其中cc_t       c_line只有在一些特殊的系统程序(比如,设置通过tty设备来通信的网络协议)中才会用。在数组c_cc中有两个下标(VTIMEVMIN)对应的元素不是控制符,并且只是在原始模式下有效。只有在原始模式下,他们决定了read()函数在什么时候返回。在标准模式下,除非设置了O_NONBLOCK选项,否则只有当遇到文件结束符或各行的字符都已经编辑完毕后才返回。

控制符VTIMEVMIN之间有着复杂的关系。VTIME定义要求等待的零到几百毫秒的时间量(通常是一个8位的unsigned char变量,取值不能大于cc_t)VMIN定义了要求等待的最小字节数(不是要求读的字节数——read()的第三个参数才是指定要求读的最大字节数),这个字节数可能是0

l         如果VTIME0VMIN定义了要求等待读取的最小字节数。函数read()只有在读取了VMIN个字节的数据或者收到一个信号的时候才返回。

l         如果VMIN0VTIME定义了即使没有数据可以读取,read()函数返回前也要等待几百毫秒的时间量。这时,read()函数不需要像其通常情况那样要遇到一个文件结束标志才返回0

l         如果VTIMEVMIN都不取0VTIME定义的是当接收到第一个字节的数据后开始计算等待的时间量。如果当调用read函数时可以得到数据,计时器马上开始计时。如果当调用read函数时还没有任何数据可读,则等接收到第一个字节的数据后,计时器开始计时。函数read可能会在读取到VMIN个字节的数据后返回,也可能在计时完毕后返回,这主要取决于哪个条件首先实现。不过函数至少会读取到一个字节的数据,因为计时器是在读取到第一个数据时开始计时的。

l         如果VTIMEVMIN都取0,即使读取不到任何数据,函数read也会立即返回。同时,返回值0表示read函数不需要等待文件结束标志就返回了。

这就是这两个变量对read函数的影响。我使用的读卡器每次传送的数据是13个字节,一开始,我把它们设置成

options.c_cc[VTIME] = 150

options.c_cc[VMIN] = 0;

结果,每次读取的信息只有8个字节,剩下的5个字节要等到下一次打卡时才能收到。就是由于这个原因造成的。根据上面规则的第一条,我把VTIME0VMIN=13,也就是正好等于一次需要接收的字节数。这样就实现了一次读取13个字节值。同时,得出这样的结论,如果读卡器送出的数据为n个字节,那么就把VMIN=n,这样一次读取的信息正好为读卡器送出的信息,并且读取的时候不需要进行循环读取。

 

4.         读取数据

有了上面的函数后,我设置了串口的基本信息,根据我们自己的实际情况,设置了相应的参数,就可以读取数据了。

void getcardinfo(char *buff){

         int fd;

         int nread,count=0;

         char tempbuff[13];

         char *dev  = "/dev/ttyS0"; //串口1

         fd = OpenDev(dev);

         set_speed(fd,9600);

         if (set_Parity(fd,8,1,'N') == FALSE)  {

                   printf("Set Parity Error/n");

                   //return -1;

         }

         while (1) //循环读取数据

         {  

                   count=0;

                   //sleep(5000);

                   while(1)

                   {

                            if((nread = read(fd, tempbuff, 13))>0)

                            {

                            //printf("/nLen %d/n",nread);

                                     memcpy(&buff[count],tempbuff,nread);

                                     count+=nread;

                            }

                            if(count==13)

                            {

                                     buff[count+1] = '/0';  

                            //printf( "/n%s", buff);

                                     break;

                            }

                   }

                   //break;

         }

         //return buff;

         close(fd);

         pthread_exit(NULL);

         //close(fd); 

         // exit (0);

}

这是我原来的程序,其实把VMIN设置以后,可以改成:

void getcardinfo(char *buff){

       int fd;

       int nread,count=0;

       char tempbuff[13];

       char *dev  = "/dev/ttyS0"; //串口1

       fd = OpenDev(dev);

       set_speed(fd,9600);

       if (set_Parity(fd,8,1,'N') == FALSE)  {

              printf("Set Parity Error/n");

              //return -1;

       }

       nread = read(fd, buff, 13)

       close(fd);

}

 

5.         程序完整代码:

#include     <stdio.h>      /*标准输入输出定义*/

#include     <stdlib.h>     /*标准函数库定义*/

#include     <unistd.h>     /*Unix 标准函数定义*/

#include     <sys/types.h> 

#include     <sys/stat.h>  

#include     <fcntl.h>      /*文件控制定义*/

#include     <termios.h>    /*PPSIX 终端控制定义*/

#include     <errno.h>      /*错误号定义*/

 

#define FALSE  -1

#define TRUE   0

/**

*@brief  设置串口通信速率

*@param  fd     类型 int  打开串口的文件句柄

*@param  speed  类型 int  串口速度

*@return  void

*/

int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,

                   B38400, B19200, B9600, B4800, B2400, B1200, B300, };

int name_arr[] = {38400,  19200,  9600,  4800,  2400,  1200,  300, 38400, 

                            19200,  9600, 4800, 2400, 1200,  300, };

void set_speed(int fd, int speed){

         int   i;

         int   status;

         struct termios   Opt;

         tcgetattr(fd, &Opt);

         for ( i= 0;  i < sizeof(speed_arr) / sizeof(int);  i++) {

                   if  (speed == name_arr[i]) {    

                            tcflush(fd, TCIOFLUSH);    

                            cfsetispeed(&Opt, speed_arr[i]); 

                            cfsetospeed(&Opt, speed_arr[i]);  

                            status = tcsetattr(fd, TCSANOW, &Opt); 

                            if  (status != 0) {       

                                     perror("tcsetattr fd"); 

                                     return;    

                            }   

                            tcflush(fd,TCIOFLUSH);  

                   } 

         }

}

/**

*@brief   设置串口数据位,停止位和效验位

*@param  fd     类型  int  打开的串口文件句柄

*@param  databits 类型  int 数据位   取值 7 或者8

*@param  stopbits 类型  int 停止位   取值为 1 或者2

*@param  parity  类型  int  效验类型 取值为N,E,O,,S

*/

int set_Parity(int fd,int databits,int stopbits,int parity)

{

         struct termios options;

         if  ( tcgetattr( fd,&options)  !=  0) {

                   perror("SetupSerial 1");    

                   return(FALSE); 

         }

         options.c_cflag &= ~CSIZE;

         options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/

         options.c_oflag  &= ~OPOST;   /*Output*/

 

         switch (databits) /*设置数据位数*/

         {   

         case 7:                

                   options.c_cflag |= CS7;

                   break;

         case 8:    

                   options.c_cflag |= CS8;

                   break;  

         default:   

                   fprintf(stderr,"Unsupported data size/n"); return (FALSE); 

         }

switch (parity)

{  

         case 'n':

         case 'N':   

                   options.c_cflag &= ~PARENB;   /* Clear parity enable */

                   options.c_iflag &= ~INPCK;     /* Enable parity checking */

                   break; 

         case 'o':  

         case 'O':    

                   options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/ 

                   options.c_iflag |= INPCK;             /* Disnable parity checking */

                   break; 

         case 'e': 

         case 'E':  

                   options.c_cflag |= PARENB;     /* Enable parity */   

                   options.c_cflag &= ~PARODD;   /* 转换为偶效验*/    

                   options.c_iflag |= INPCK;       /* Disnable parity checking */

                   break;

         case 'S':

         case 's':  /*as no parity*/  

             options.c_cflag &= ~PARENB;

                   options.c_cflag &= ~CSTOPB;break; 

         default:  

                   fprintf(stderr,"Unsupported parity/n");   

                   return (FALSE); 

         } 

/* 设置停止位*/ 

switch (stopbits)

{  

         case 1:   

                   options.c_cflag &= ~CSTOPB; 

                   break; 

         case 2:   

                   options.c_cflag |= CSTOPB; 

            break;

         default:   

                    fprintf(stderr,"Unsupported stop bits/n"); 

                    return (FALSE);

}

/* Set input parity option */

if (parity != 'n')  

         options.c_iflag |= INPCK;

tcflush(fd,TCIFLUSH);

options.c_cc[VTIME] = 0; /* 设置超时15 seconds*/  

options.c_cc[VMIN] = 13; /* define the minimum bytes data to be readed*/

if (tcsetattr(fd,TCSANOW,&options) != 0)  

{

         perror("SetupSerial 3");  

         return (FALSE); 

}

return (TRUE); 

}

/**********************************************************************

代码说明:使用串口一测试的,发送的数据是字符,

但是没有发送字符串结束符号,所以接收到后,后面加上了结束符号

**********************************************************************/

 

/*********************************************************************/

int OpenDev(char *Dev)

{

         int     fd = open( Dev, O_RDWR );

        //| O_NOCTTY | O_NDELAY         

         if (-1 == fd)        

         {                        

                   perror("Can't Open Serial Port");

                   return -1;            

         }      

         else  

                   return fd;

}

void getcardinfo(char *buff){

         int fd;

         int nread,count=0;

         char tempbuff[13];

         char *dev  = "/dev/ttyS0"; //串口1

         fd = OpenDev(dev);

         set_speed(fd,9600);

         if (set_Parity(fd,8,1,'N') == FALSE)  {

                   printf("Set Parity Error/n");

                   //return -1;

         }

         while (1) //循环读取数据

         {  

                   count=0;

                   //sleep(5000);

                   while(1)

                   {

                            if((nread = read(fd, tempbuff, 13))>0)

                            {

                            //printf("/nLen %d/n",nread);

                                     memcpy(&buff[count],tempbuff,nread);

                                     count+=nread;

                            }

                            if(count==13)

                            {

                                     buff[count+1] = '/0';  

                            //printf( "/n%s", buff);

                                     break;

                            }

                   }

                   //break;

         }

         //return buff;

         close(fd);

         pthread_exit(NULL);

         //close(fd); 

         // exit (0);

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值