问题是:我不知道该在哪里打开串口,若在主线程main中打开,则双方的读线程都收到乱码,同时也可以检测出写线程发出去的字符也有异常;若读写线程各自单独打开关闭串口,则写线程可以发出字符,但读线程始终无法读到数据。难道是我的线程有问题?
目前本人正处于非常苦恼之中,清各位大侠帮忙,贴出我的代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define NUM 20
int fd;
void writeThread(void* arg);
void readThread(void* arg);
/*
int openport(void)
{
// int fd;
struct termios options;
if((fd=open("/dev/tts/0",O_RDWR|O_NOCTTY|O_NONBLOCK|O_NDELAY))==-1)
{
perror("Can't open serial1 port.");
return -1;
}
/* tcgetattr(fd,&options);
cfsetispeed(&options,B9600);
cfsetospeed(&options,B9600);
options.c_cflag|=(CLOCAL|CREAD); //忽略控制信号线和使能读功能
options.c_cflag|=PARENB; //奇偶检验
options.c_cflag&=~PARODD; //偶校验
options.c_iflag |= (INPCK | ISTRIP);
options.c_cflag|=CSTOPB; //两个停止位
options.c_cflag&=~CSIZE;
options.c_cflag|=CS8; //8个数据位
options.c_lflag&=~(ICANON|ECHO|ISIG); //原始输入模式
options.c_oflag&=~OPOST; //原始输出
options.c_cc[VMIN]=0;
options.c_cc[VTIME]=0;
tcsetattr(fd,TCSANOW,&options);
printf("\nfd = %d\n",fd);
return fd;
}
*/
int
main(int argc, char* argv[])
{
int iret;
pthread_t id1, id2;
if((fd=open("/dev/tts/0",O_RDWR|O_NOCTTY|O_NONBLOCK|O_NDELAY))==-1)
{
perror("Can't open serial1 port.");
return -1;
}
iret = pthread_create(&id1, NULL, (void*)readThread, NULL);
if(iret != 0) {
printf("\nthread1_create is failed!\n");
}
iret = pthread_create(&id2, NULL, (void*)writeThread, NULL);
if(iret != 0) {
printf("\nthread1_create is failed!\n");
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
close(fd);
return 0;
}
void readThread(void* arg)
{
int nread, i;
int rcount = 0;
unsigned char buf[21];
while(1) {
sleep(1);
printf("\nnow it begain to read words.\n");
// printf("\nbefore reading, the words inf buf are %s\n",buf);
nread = read(fd, buf, 20);
if(nread == 20) {
printf("\nnread=%d", nread);
for(i = 0; i < 20; i++) {
printf("%c ", buf[1]);
}
rcount++;
printf("\nreceive packets: %d\n", rcount);
}
}
}
void writeThread(void* arg)
{
int i,j;
int fd;
unsigned char k = 'a';
int m;
int nwrite;
int scount = 0;
unsigned char serialTest[NUM] = {0};
for(m= 0;m
serialTest[m] = k++;
}
/* open serial port */
while(1) {
sleep(1);
fd=open("/dev/tts/0",O_RDWR|O_NOCTTY|O_NONBLOCK|O_NDELAY);
nwrite = write(fd, serialTest, NUM);
write(fd, "\n", 1);
if(nwrite == 20) {
printf("\nwriteRadioFramewriteRadioFramewriteRadioFramewriteRadioFrame\n");
printf("\nnwrite = %d\n", nwrite);
for(j = 0; j< NUM; j++) {
printf("%c ",serialTest[j]);
}
scount++;
printf("\nsend packets: %d \n", scount++);
printf("\nwriteRadioFramewriteRadioFramewriteRadioFramewriteRadioFrame\n");
}
close(fd);
}
}


mg271603433 于 2011-01-05 18:25:53发表:
顶一个。
feng3436 于 2010-11-29 11:49:00发表:
之前用两个线程读写串口出现的问题:在写串口后不能再读串口的问题解决了,
方法是:把线程改为两个进程,分别读写
不过线程读写的方法还是没搞通,估计是因为线程共享数据,在读线程运行后,破坏了回到写线程所要求满足的条件。
谁要搞好了,在这我分享一下哦
feng3436 于 2010-11-28 20:03:08发表:
我也用两线程进行读写串口,也遇到同样的问题,若将程序单独读写都正常,先读后写也正常,但在写了一次后就不能再读串口了