|
我起了两个线程来操作串口:一个用于读数据,一个用于写数据。该程序用于两个arm9之间的串口全双工通信:即用一根串口线将两块板子连接起来。
问题是:我不知道该在哪里打开串口,若在主线程main中打开,则双方的读线程都收到乱码,同时也可以检测出写线程发出去的字符也有异常;若读写线程各自单独打开关闭串口,则写线程可以发出字符,但读线程始终无法读到数据。难道是我的线程有问题?
目前本人正处于非常苦恼之中,清各位大侠帮忙,贴出我的代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <termios.h>
#include <pthread.h>
#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 <NUM;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);
}
} |
|