免费注册 查看新帖 |

Chinaunix

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

linux一个串口写数据的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-05-04 08:20 |只看该作者 |倒序浏览
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#define max_buffer_size 100 /*定义缓冲区最大宽度*/
/*******************************************/
int fd; /*定义设备文件描述符*/
int flag_close;
int open_serial(int k)
{
    if(k==0) /*串口选择*/
    {
        fd = open("/dev/ttyUSB0",O_RDWR|O_NOCTTY); /*读写方式打开串口*/
        perror("open /dev/ttyUSB0");
    }
    else
    {
        fd = open("/dev/ttyS1",O_RDWR|O_NOCTTY);
        perror("open /dev/ttyS1");
    }
    if(fd == -1) /*打开失败*/
        return -1;
    else
        return 0;
}
/********************************************************************/
int main(int argc, char *argv[ ] )
{
    char sbuf[]={"Hello,this is a Serial_Port test!"};
    int sfd,retv,i;
    struct termios options;
    int length=sizeof(sbuf);/*发送缓冲区数据宽度*/

    /*******************************************************************/
    open_serial(0); /*打开串口1*/
    /*******************************************************************/
    printf("ready for sending data...\n"); /*准备开始发送数据*/
    bzero(&options,sizeof(options));
    tcgetattr(fd,&options);
    //cfmakeraw(&options);
    /*****************************************************************/
    options.c_cflag|=CLOCAL|CREAD;
    options.c_cflag &= ~CSIZE;
    cfsetispeed(&options,B9600); /*波特率设置为9600bps*/
    cfsetospeed(&options,B9600);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CS8;
    options.c_cc[VMIN]=0;
    options.c_cc[VTIME]=0;
    /*******************************************************************/
    tcflush(fd,TCIFLUSH);
    tcsetattr(fd,TCSANOW,&options);
    while(1)
    retv=write(fd,sbuf,length); /*接收数据*/
    if(retv==-1)
    {
        perror("write");
    }
    printf("the number of char sent is %d\n",retv);
    flag_close =close(fd);
    if(flag_close==-1) /*判断是否成功关闭文件*/
        printf("Close the Device failur!\n");
    return 0;
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP