加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Linux 下串口中断和查询两种方式读取串口的程序Demo写法

(2014-04-10 09:10:00)
标签:

it

分类: 飞凌嵌入式
我个人觉得如果是单片机来说中断和查询的写法可能会让单片机在效率上有些不同,毕竟单片机的资源有限,但是对于上位机的PC监控来说呢,查询的消耗并没有消耗多少(这儿是相对于中断来说的),但是如果严谨些,是应该用中断来代替查询的,这儿分别列出中断和查询在linux上的不同写法,以区分出来,以下是示例代码:




#include
#include
#include
#include
#include
#include
#include
#include

int tty_mode(int how)
{
static struct termios original_mode;
if(how==0)
tcgetattr(0,&original_mode);
else return tcsetattr(0,TCSANOW,&original_mode);
}
void set_crmode()
{
struct termios ttystate;
tcgetattr(0,&ttystate);
ttystate.c_lflag &= ~ICANON;
ttystate.c_lflag &=~ECHO;
ttystate.c_cc[VMIN]=1;
tcsetattr(0,TCSANOW,&ttystate);
}

int signal_io(int sig)
{
static char buf[128],ch=0;
static int len=0;
//memset(buf,0,sizeof(buf));
//printf("aaaa\n");
if(read(0,&ch,1)==1)
{
if(ch!=127)
{
printf("%c",ch);
buf[len++]=ch;
}
else {
        if(len>0)
        buf[--len]=0;
        printf("\b \b");
        }
}
//perror(NULL);
//printf("%d\n",ch);
fflush(stdout);
}
int main()
{
int flag=0;
tty_mode(0);
set_crmode();
signal(SIGIO,signal_io);
fcntl(0,F_SETOWN,getpid());
flag=fcntl(0,F_GETFL);
fcntl(0,F_SETFL,flag|O_ASYNC);
while(1)
pause();
tty_mode(1);
}



下面贴出串口查询的代码:





#include
#include
#include
#include
#include
#include
#include
#include 'math.h'
#define max_buffer_size 100      


int fd,s;
int open_serial(int k)

{
  if (k=0)
  {
    int fd=open("/dev/ttys0",O_RDWR|O_NOCTTY);
    perror("open /dev/ttys0");
  }
  else
  {
    fd=open("/dev/ttys1",O_RDWR|O_NOCTTY);
    perror("open /dev/ttys1");
  }
  if(fd==-1)
    return -1;
  else
    return 0;

}




int main()
{
char hd[max_buffer_size],*rbuf;
int flag_close, retv,i,ncount=0;
struct termios opt;
int realdata=0;


open_serial(0);


tcgetattr(fd,&opt);
cfmakeraw(&opt);


cfsetispeed(&opt,B9600);
cfsetospeed(&opt,B9600);


tcsetattr(fd,TCSANOW,&opt);
rbuf=hd;
printf("ready for receiving data...\n");
retv=read(fd,rbuf,1);
if(retv==-1)
{
  perror("read");
}


while(*rbuf!='\n')
    {
ncount+=1;
rbuf++;
retv=read(fd,rbuf,1);
if(retv==-1)
{
perror("read");
}
}

printf("The data received is:\n");
for(i=0;i
{
printf("%c",hd[i]);
}
printf("\n");
flag_close =close(fd);
if(flag_close ==-1)
printf("Close the Device failur!\n");
return 0;
}


转自:http://www.justwinit.cn/post/2810/

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有