linux 串口出不来数据,双线程读写串口数据,出现的问题是,一直向串口写数据,却读不出数据。下面是设计的代码...

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值