免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1750 | 回复: 1
打印 上一主题 下一主题

linux 串口编程 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-22 12:00 |只看该作者 |倒序浏览
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>

#define BUFSIZE 1024

int
read_and_print(int fd, int sec, int usec)
{
    int         rc,l,i;
    char        buf[BUFSIZE+1];
    fd_set      set;
    struct timeval  tv;
   
    if (sec || usec) {
    FD_ZERO(&set);
    FD_SET(fd,&set);
    tv.tv_sec  = sec;

    tv.tv_usec = usec;
   // if (0 == select(fd+1,&set,NULL,NULL,&tv))
  //     return -1;
    }
   
    switch (rc = read(fd,buf,BUFSIZE)) { //rc值一直是-1,为什么?
    case 0:
    printf("EOF");
    exit(0);
    break;
    case -1:
    perror("read");
    exit(1);
    default:
    for (l = 0; l < rc; l+= 16) {
        printf("%04x  ",l);
        for (i = l; i < l+16; i++) {
        if (i < rc)
            printf("%02x ",buf[i]);
        else
            printf("-- ");
        if ((i%4) == 3)
            printf(" ");
        }
        for (i = l; i < l+16; i++) {

        if (i < rc)
            printf("%c",isalnum(buf[i]) ? buf[i] : '.');
        }
        printf("\n");
    }
    break;
    }
    return rc;
}

void
setlines(int fd, int rts, int dtr)
{
    int lines = 0;

    if (rts) lines |= TIOCM_RTS;
    if (dtr) lines |= TIOCM_DTR;
   
    ioctl(fd,TIOCMSET,&lines);
}

int main(int argc, char *argv[])
{
    int         ser,i;
    struct termios      saved_attributes,tattr;
    struct winsize      win;
    char        buf[16];
   
    if (-1 == (ser = open("/dev/ttyS1",O_RDWR))) {

    perror("open /dev/ttyS1");
    exit(1);
    }
   
    /* Set the terminal mode */
    tcgetattr (ser, &tattr);
    cfmakeraw (&tattr);
    cfsetospeed (&tattr,B9600);
    cfsetispeed (&tattr,B9600);
    tcsetattr (ser, 0, &tattr);
   
    setlines(ser,0,0);
#if 0
    tcsendbreak(ser,0);
#endif

    /* main loop */
    fprintf(stderr,"setup done\n");
    while (-1 != read_and_print(ser,30,0)) {
    usleep(100000);
    }
   
    return 0;
}

为什么一直输出read INput/output error
就是第一个函数中的rc值返回的是-1;

论坛徽章:
0
2 [报告]
发表于 2006-08-22 12:06 |只看该作者
补充一下:
    我用水木行的红外适配器连接comm1,在fedora4下试验的这段程序。运行前加载了串口驱动serial_cs.ko
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP