PDA

View Full Version : serial communication in linux,using c



lanmanck
28th September 2009, 15:46
hi guys:
my serial code works well,AND NOTwant to use QextSerialPort:


int main(void)
{
int fd,nread;
struct termios Opt;
char buff[512];
/*以读写方式打开串口*/
fd = open( "/dev/ttySAC2", O_RDWR|O_NONBLOCK);
if(-1 == fd)
{
perror("提示错误!");/* 不能打开串口一*/
return 1;
}
//获取属性
tcgetattr(fd, &Opt);
tcflush(fd, TCIOFLUSH);
//设置为19200Bps
cfsetispeed(&Opt,B115200);
cfsetospeed(&Opt,B115200);
//8位数据位
Opt.c_cflag &= ~CSIZE;
Opt.c_cflag |= CS8;
//无校验
Opt.c_cflag &= ~PARENB; /* Clear parity enable */
Opt.c_iflag &= ~INPCK;
//1停止位
Opt.c_cflag &= ~CSTOPB;
//
Opt.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
Opt.c_cc[VMIN] = 0; /* Update the options and do it NOW */

//设置属性
tcsetattr(fd,TCSANOW,&Opt);
tcflush(fd, TCIOFLUSH);

//
while(!quit)
{
while((nread = read(fd, buff, 512))>0)
{
buff[nread+1] = '\0';
write(fd,buff,nread);
}
}
printf("quit\n");
close(fd);
exit (0);
}

now i want to place it into a class ,inherited from QThread.
however,when i invoke close(fd), it report error.because close() is QT's default function to close the dialog.
how can i solve this problem?

lanmanck
28th September 2009, 15:59
i have fixed the error:
::close(fd);:p

lanmanck
29th September 2009, 03:27
another question:
this code seems not to run as expected.
i want read() a char and write() it back.
but now when i read() a char,the write() method has no effect.
that's to say:
it never go to:


buff[nread+1] = '\0';
write(fd,buff,nread);

HOWEVER,my serial terminal can receive the char i press!!!
what's wrong with this code? :(

wysota
29th September 2009, 10:13
How is this question related to Qt exactly?

lanmanck
29th September 2009, 14:14
well , later i will put the read() in a QThread, and use postEvent() to communicate with main dialog. hope you could help :)