资源简介
先在命令行运行make编译,生成串口读写共享库,然后运行gcc -s -shared -fPIC test.c -lSetupSerialPort -o test.so,编译串口读写测试程序。
文件说明:
SetupSerialPort.h //串口读写库头文件
SetupSerialPort.c //串口读写库实现文件
Makefile //编译串口读写共享库
test.c //调用串口读写共享库例程
还有Linux下Socket通讯开发例程及Firefox浏览器插件开发例程,有空时会一起整理出来贡献给大家
代码片段和文件信息
#include /* tcgetattr tcsetattr */
#include /* perror printf puts fprintf fputs */
#include /* read write close */
#include /* open */
#include /* bzero */
#include “SetupSerialPort.h“
/*
* Decription for TIMEOUT_SEC(buflenbaud);
* baud bits per second buflen bytes to send.
* buflen*20 (20 means sending an octect-bit data by use of the maxim bits 20)
* eg. 9600bps baudrate buflen=1024B then TIMEOUT_SEC = 1024*20/9600+1 = 3
* don‘t change the two lines below unless you do know what you are doing.
*/
#define TIMEOUT_SEC(buflen baud) (buflen * 20 / baud + 2)
#define TIMEOUT_USEC 0
static struct termios termios_old termios_new;
int OpenComPort (int ComPort int baudrate int databit const char *stopbit char parity)
{
char *pComPort;
int fd; //File descriptor for the port
int retval;
switch (ComPort) {
case 0:
pComPort = “/dev/ttyS0“;
break;
case 1:
pComPort = “/dev/ttyS1“;
break;
case 2:
pComPort = “/dev/ttyS2“;
break;
case 3:
pComPort = “/dev/ttyS3“;
break;
case 4:
pComPort = “/dev/ttyS4“;
break;
case 5:
pComPort = “/dev/ttyS5“;
break;
case 6:
pComPort = “/dev/ttyS6“;
break;
case 7:
pComPort = “/dev/ttyS7“;
break;
default:
pComPort = “/dev/ttyS0“;
break;
}
fd = open (pComPort O_RDWR | O_NOCTTY | O_NONBLOCK);
if (-1 == fd)
return (-1);
tcgetattr (fd &termios_old); /* save old termios value */
/* 0 on success -1 on failure */
retval = SetPortAttr (fd baudrate databit stopbit parity);
if (-1 == retval)
return -1;
return (fd);
}
void CloseComPort (int fd)
{
/* flush output data before close and restore old attribute */
tcsetattr (fd TCSADRAIN &termios_old);
close (fd);
}
int ReadComPort (int fd void *data int datalength)
{
fd_set fs_read;
struct timeval tv_timeout;
int retval = 0;
FD_ZERO (&fs_read);
FD_SET (fd &fs_read);
tv_timeout.tv_sec = TIMEOUT_SEC (datalength GetBaudrate ());
tv_timeout.tv_usec = TIMEOUT_USEC;
retval = select (fd + 1 &fs_read NULL NULL &tv_timeout);
if (retval)
return (read (fd data datalength));
else
return (-1);
}
int WriteComPort (int fd
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 225 2009-07-17 14:44 SetupSerialPort\Makefile
文件 9167 2009-07-17 14:44 SetupSerialPort\SetupSerialPort.c
文件 681 2009-07-17 14:44 SetupSerialPort\SetupSerialPort.h
文件 376 2009-07-26 17:49 SetupSerialPort\test.c
文件 132 2009-07-26 17:54 SetupSerialPort\说明.txt
目录 0 2009-07-26 17:52 SetupSerialPort
----------- --------- ---------- ----- ----
10581 6
评论
共有 条评论