#include
#include
#include
#include
#include
#include
#include
#define DEV "/dev/ttyS0"
int OpenDev(char *name)
{
int fd;
fd = open(DEV, O_RDWR);
if(fd == -1)
{
perror("Can't Open Serial Port!\n");
return -1;
}
else
{
printf("fd=%d\n",fd);
return fd;
}
}
int set_speed(int fd)
{
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, B9600);
cfsetospeed(&Opt, B9600);
status = tcsetattr(fd, TCSANOW, &Opt);
if(status != 0)
{
perror("Can't Set Speed!\n");
return -1;
}
tcflush(fd, TCIOFLUSH);
return 0;
}
int set_Parity(int fd, int databits, int stopbits, int parity)
{
struct termios options;
if(tcgetattr(fd, &options) != 0)
{
perror("Set Parity error!\n");
return 0;
}
options.c_cflag &= ~CSIZE;
switch(databits)
{
case 7:
options .c_cflag |= CS7;
break;
case 8:
options .c_cflag |= CS8;
break;
default:
printf("Unsupported data size\n");
return 0;
}
switch(parity)
{
case 'n':
case 'N':
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB);
options.c_iflag |=INPCK;
break;
case 'e':
case 'E':
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_iflag |=INPCK;
break;
case 's':
case 'S':
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
default:
printf("Unsupported parity\n");
return 0;
}
switch(stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
printf("Unsupported stop bits\n");
return 0;
}
if(parity != 'n' || parity != 'N')
{
options.c_iflag |= INPCK;
options.c_cc[VTIME] = 50;
options.c_cc[VMIN] = 0;
tcflush(fd, TCIOFLUSH);
if(tcsetattr(fd, TCSANOW, &options) != 0)
{
perror("Set parity error\n");
return 0;
}
return 1;
}
}
int send_cmd(int ftty,char * str)
{
int result;
result = write(ftty,str,strlen(str));/*argv[4], strlen(argv[4]));*/
if (result < 0)
{
printf("Write command:%s to VC312 failed\n",str);
close(ftty);
exit(1);
}
}
int main(int argc, char *argv[])
{
int fdd,nread;
char buff[512];
int i;
int g;
char cmd[10];
cmd[0]=0xff;cmd[1]=0xe1;cmd[2]=0x58;cmd[3]=0x58;cmd[4]=0x66;cmd[5]=0x66;cmd[6]=0;
fdd=OpenDev(DEV);
set_speed(fdd);
set_Parity(fdd,8,1,'N');
while(1)
{
g=getchar();
if(g==0x61)
{
send_cmd(fdd,cmd);
g=0;
}
while((nread = read(fdd,buff,512))>0)
{
printf("\nLen %d\n",nread);
buff[nread+1]='\0';
for(i=0;i
}
nread=0;
}
}
但while(1)循环总是停在while((nread = read(fdd,buff,512))>0)这一行,无法往下执行,哪位高手指点下。问提在哪里?
wen198111 于 2009-04-15 23:24:53发表:
555555555555555555555
maxwell_lee 于 2009-04-15 08:34:17发表:
学习了。
kaishui 于 2009-04-14 14:20:54发表:
fd = open(DEV, O_RDWR);默认是阻塞读取,
可以改成fd = open(DEV, O_RDWR|O_NOCTTY | O_NONBLOCK);
hacker47 于 2009-01-16 09:25:23发表:
阻塞喽!
tkfly0324 于 2008-12-30 13:50:43发表:
使用非阻塞打开方式怎么样呢
gq_gq831 于 2008-12-26 16:16:58发表:
谢谢大家我解决了使用了线成函数
techxuan 于 2008-12-24 21:12:22发表:
read(fdd,buff,512)是一个同步线程,程序运行到这里,进行读取数据。也就有数据在串口传输时,才会进入循环体内,如果没有数据传输时,当然只能停在read这里啦。
Digiman 于 2008-12-15 16:14:22发表:
Read函数有问题.不知道你的Read是作什么用的.