手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网站运营>建站经验>列表

简单RS232通信程式

来源:互联网 作者:west263.com 时间:2008-04-16
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

return (FALSE);
}
return (TRUE);
}

/**打开串口
* dev 串口设备名
* mode 打开方式
**/

int opendev(char *dev,mode_t mode)
{
int fd;
fd = open(dev, mode);
if (-1 == fd){
perror("Can't Open Serial Port");
return -1;
}
else{
fcntl(fd, F_SETFL, FNDELAY);
return fd;
}
}
/********************************** input232.c 写串口********************************/

#include "rs232.h"
#define RSDEV_NAME "/dev/ttyS1"

int main(void)
{

int rsfd = 0;
int nwrite;
char input_buf[64];
rsfd = opendev(RSDEV_NAME,O_RDWR | O_NOCTTY | O_NDELAY);
if(rsfd < 0){
printf("open error:\n");
exit(-1);
}
set_speed(rsfd,9600); /*配置速率B9600*/
if (set_parity(rsfd,8,1,'N') == FALSE){ /*8位数据位,一位停止位*/
printf("Set Parity Error\n");
exit (-1);
}
while(1) {
fgets(input_buf,sizeof(input_buf),stdin);
printf("input_buf = %s", input_buf);
nwrite = write(rsfd, input_buf, strlen(input_buf));
if ( nwrite == -1 ) {
perror("ERROR!");
exit(1);
}else {
printf("ret=%d\n", nwrite);
}
}
}
/********************************** read232.c 读串口********************************/

#include "rs232.h"
#define RSDEV_NAME "/dev/ttyS1"
int read_rs232(int rsfd);
int main(void)
{

int rsfd = 0;
int nwrite;
fd_set fdR;
struct timeval timev;
int n = 0;
char input_buf[64];
rsfd = opendev(RSDEV_NAME,O_RDWR | O_NOCTTY | O_NDELAY);
if(rsfd < 0){
printf("open error:\n");
exit(-1);
}
set_speed(rsfd,9600); /*配置速率B9600*/
if (set_parity(rsfd,8,1,'N') == FALSE){ /*8位数据位,一位停止位*/
printf("Set Parity Error\n");
exit (-1);
}
while(1) {
FD_ZERO(&fdR);
FD_SET(rsfd, &fdR);
timev.tv_sec = 0;
timev.tv_usec = 100000;
n = select(rsfd 1, &fdR, NULL, NULL, &timev);
if(n <= 0)
continue;
if (FD_ISSET(rsfd,&fdR)) {
printf("rs232 recv\n");
read_rs232(rsfd);
}
}
}
int read_rs232(int rsfd)
{
int retbytes = 0,nread = 0;
int all_bytes = 0;
struct net2net_buf netbuf;
int i;
memset(&netbuf,0,sizeof(netbuf));
while((nread = read(rsfd, &netbuf.buf[retbytes], 512))>0)
{
printf("nread:%d\n",nread);
retbytes = nread;
all_bytes = nread;
}
return all_bytes;
}


文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!