嵌入式串口操作

5 篇文章 0 订阅
1 篇文章 0 订阅

这是一个简易的嵌入式linux对多单片机的测试程序:

下位机如下工作:接收到正确的地址码,返回#? OKv否则什么也不返回

教训:上一个程序VMIN设置成6,当只有上下位机的时候,地址码错误,程序就会阻塞在那里。

一对多通信,VMIN必须为0,VTIME的单位是百毫秒,这里30就代表3秒。表示上位机最多等待三秒。若无任何响应,则返回。

如同http://bbs.csdn.net/topics/320133315这里所讲  我自己测试下来发现设置c_cc[VMIN] > 0后,不管open的时候带不带O_NODELY/O_NOBLOCK ,都为阻塞型了


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>

#define DEVICE "/dev/ttyS1"
/****globals****/
struct termios opt;
void OptTermi(struct termios*);
int fd, c ,res;
struct termios old;
char buf[7];
char sent;
char STOP =0;
/******************/

int main()
{
    fd =open(DEVICE,O_RDWR|O_NDELAY);
    if(fd>0)
        printf("Device Opened Successfully!\n");
    tcgetattr(fd,&old);
    bzero(&opt,sizeof(opt));
    OptTermi(&opt);
    fcntl(fd,F_SETFL,0);
    tcflush(fd,TCIFLUSH);
    if(tcsetattr(fd,TCSANOW,&opt)==0)
        printf("Init done......\n");

    do{
        memset(buf,0,7);
        printf("enter a char:\n");
        scanf("%c",&sent);
        if('q'==sent)
            STOP=1;
        write(fd,&sent,1);
        res =read(fd,buf,6);
        if(buf[5]=='v')
        {
            printf("incoming...\n");
            buf[6]=0;
            printf("%d\n",res);
            printf(":%s\n",buf);
        }
        if(buf[5]!='v')
            printf("NO device available.\n");
	tcflush(fd,TCIFLUSH);
    }while(STOP==0);


    tcsetattr(fd,TCSANOW,&old);
    close(fd);
}

void OptTermi(struct termios* termios_p)
{
    //set to RAW mode ,according to man page
        termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                           | INLCR | IGNCR | ICRNL | IXON);
           termios_p->c_oflag &= ~OPOST;
           termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
           termios_p->c_cflag &= ~(CSIZE | PARENB);
           termios_p->c_cflag |= CS8;
           //plus
           termios_p->c_iflag &= ~(IXON | IXOFF | IXANY);
    //parity setting: operations above has done something ,more to go
    //no input parity checking
    termios_p->c_iflag &=~INPCK;
    //1 stop bit
    termios_p->c_cflag &=~CSTOPB;
    /* Enable the receiver and set local mode...*/
    termios_p->c_cflag |= (CLOCAL | CREAD);
    //set standard speed
    cfsetispeed(termios_p,B9600);
    cfsetospeed(termios_p,B9600);
    //
    termios_p->c_cc[VTIME]=30;
    termios_p->c_cc[VMIN]=0;

}



http://bbs.ednchina.com/BLOG_ARTICLE_1809186.HTM


http://wenku.baidu.com/view/56467805cc175527072208bc.html


http://blog.csdn.net/wushihua/article/details/5733790

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值