主题 : 求救!自己编写的串口程序,可以接受到数据,但是却发送不出去! 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 76037
精华: 0
发帖: 14
金钱: 70 两
威望: 14 点
综合积分: 28 分
注册时间: 2012-08-17
最后登录: 2012-10-25
楼主  发表于: 2012-08-18 23:31

 求救!自己编写的串口程序,可以接受到数据,但是却发送不出去!

我在tiny6410 linux环境下编写了一个串口通信的程序,但是板子可以接受到数据,却发送不出去!求高人指点!源程序如下:
# include <stdio.h>
# include <stdlib.h>
# include <termio.h>
# include <unistd.h>
# include <fcntl.h>
# include <getopt.h>
# include <time.h>
# include <errno.h>
# include <string.h>

int main(int argc, char *argv[])
{
    int com_fd;
    struct termios opt;
    
    const char *DeviceName = "/dev/ttySAC1";
    int DeviceSpeed = B115200;
    int TtySpeed = B115200;
    int ByteBits = CS8;

    char buff[512];
    int num;

    com_fd = open(DeviceName,O_RDWR,0);//打开串口设备
    if(com_fd < 0)
    {
        fprintf(stderr,"can't open serial port!\n");
        return -1;
    }

    //恢复串口未阻塞状态
    if (fcntl(com_fd, F_SETFL, O_NONBLOCK) < 0)
    {
        fprintf(stderr,"fcntl failed!\n");
        exit(0);
    }
    //初始化内存
    memset(&opt,0,sizeof(struct termios));

    if(tcgetattr(com_fd, &opt) < 0)//函数用于获取与终端相关的参数。参数fd为终端的文件描述符,返回的结果保存在termios结构体中
    {
        fprintf(stderr,"Unable to get comm port\n");
        return -1;
    }
    //tcflush(com_fd,TCIOFLUSH);
    cfsetispeed(&opt,B115200);
    cfsetospeed(&opt,B115200);

    if (tcsetattr(com_fd, TCSANOW, &opt) < 0)
    {
        fprintf(stderr,"Unable to set comm port\n");
        return -1;
    }

    //opt.c_iflag = IGNPAR;
    //opt.c_oflag &= ~(OPOST);
    opt.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
    opt.c_oflag  &= ~OPOST;   /*Output*/
    opt.c_cflag = DeviceSpeed | HUPCL | ByteBits | CREAD | CLOCAL | CRTSCTS;
    opt.c_cc[VMIN] = 1;

    tcflush(com_fd,TCIOFLUSH);

    if (tcsetattr(com_fd, TCSANOW, &opt) < 0)
    {
        fprintf(stderr,"Unable to set comm port\n");
        return -1;
    }

    fprintf(stderr,"I'm OK!\n");
    write(com_fd,"hello",5);
    while(1)
    {
        if((num = read(com_fd,buff,512)) > 0)
        {
            buff[num] = '\0';
            //fprintf(stderr,buff);
            //fprintf(stderr,"\n");
            write(com_fd,buff,num);
            //write(com_fd,"hello",5);
        }
    }
    return 0;
}
级别: 新手上路
UID: 70325
精华: 0
发帖: 34
金钱: 170 两
威望: 34 点
综合积分: 68 分
注册时间: 2012-05-18
最后登录: 2012-10-26
1楼  发表于: 2012-08-19 00:43
read和write要写在不同线程的吧,一个发一个收。
级别: 新手上路
UID: 76037
精华: 0
发帖: 14
金钱: 70 两
威望: 14 点
综合积分: 28 分
注册时间: 2012-08-17
最后登录: 2012-10-25
2楼  发表于: 2012-08-19 08:33

 回 1楼(bottles) 的帖子

不是吧?我觉得不是那个问题!同一个线程也可以呀!