void *thread_write(){
char sendData[8] = {0x03, 0x04, 0x00, 0x10, 0x00, 0x0C,0xF0, 0x28};
pthread_mutex_lock(&mut); //考虑到485是半双工,读的时候不能写,写的时候不能读,故加锁控制
sendCmdToSerial(sendData, sizeof(sendData)); //写线程,功能是给串口写数据,并加锁;
pthread_mutex_unlock(&mut);
pthread_exit(NULL);
}
void *thread_read(){
char rxData[40];
pthread_mutex_lock(&mut);
readcom(rxData, 30, 1); //读线程,
pthread_mutex_unlock(&mut);
pthread_exit(NULL);
}
----------------------------------------------------------------------------------------------------------------------------------
int readcom(char* buffer, int len, int timeout) //读读线程中,用来读数据的函数
{
int ret, len2;
fd_set RFds, wfds;
unsigned char buf[30];
unsigned char *p_buf = buf;
struct timeval tmout;
int i;
FD_ZERO(&rfds);
FD_SET(g_fd,&rfds);
for(;;){
timeout *= 1000; //timeout传递的值为1
tmout.tv_sec = timeout/1000;
tmout.tv_usec = 1000*(timeout%1000);
ret = select(g_fd+1, &rfds, NULL, NULL, &tmout);
IF(ret < 0){
printf("ret = %d\n", ret);
break;
} else if(ret == 0) {
printf("Timeout !\nret = %d\n", ret);
continue;
} else {
printf("ret = %d select is OK!\n", ret);
if(FD_ISSET(g_fd,&rfds)) {
bzero(buf, 30);
while(1) {
len2 = read(g_fd, p_buf, READ_SIZE); //向串口写入数据
buf[len2] = '\0';
printf("**************** read content begin ****************\n");
printf("read data is:");
for(i = 0; i < len2; i++) printf("%02x ",buf[i]);
printf("\n**************** read content end ****************\n");
}
} else {printf("FD_ISSET_read wrong\n"); continue;}
}
}
return len2;
}
------------------------------------------------------------------------------------------------------------------------
int sendCmdToSerial(char* cmd, int cmdLen) //写线程中用来发送数据的函数
{
static char g_writeBuff[20] = {0};
memcpy(g_writeBuff, cmd, cmdLen);
g_writeBuff[cmdLen]='\0';
while(1) {
ret = write(g_fd, g_writeBuff, 8); //读取串口数据
printf("**************** write content begin ****************\n");
printf("write data is:");
for(i=0; i<8; i++) {
printf("%02x ", g_writeBuff[i]);
}
printf("\n*************** write content end ****************\n");
if(-1 == ret) {
printf("write fiaLED\n");
tcflush(g_fd, TCOFLUSH);
}
sleep(3); //控制循环的时间,每个3秒向串口发送一次数据
}
return 0;
}