#项目实现相关# | Linux、C | Ubuntu环境下select多路复用串口读写
目录
体温
结果图
代码
/*
体温
*/
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <termios.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
int set_opt(int ,int , int , char , int );
void main()
{
int fd,nByte,len=0;
unsigned char uartBodyTemperature[]={0XFF,0XC9,0X03,0XA3,0XA0}; //体温
char *uart = "/dev/ttyUSB1";
fd_set recv_fd;
struct timeval tv;
unsigned char buff[513];
unsigned char *c;
c = &buff;
int i = 0,j=0;
int res = 0;
int cnt = 0;//发送计数
int recv_flag=0;
int CKSUM = 0;
double temperature = 0;
double temp_value[16];
unsigned char temp_buf[16];
//打开串口设备
if((fd=open(uart,O_RDWR|O_NONBLOCK|O_NOCTTY))<0)
{
printf("open error\n");
}else
{
printf("%s open success!",uart);
//设置波特率等参数
set_opt(fd,115200,8,'N',1);
tv.tv_sec = 1;
tv.tv_usec = 0;
//进行写启动命令,仅一次即可
if( (res = write(fd,uartBodyTemperature,sizeof(uartBodyTemperature)))<0) {
perror("write:");
}
printf("write uartBodyTemperature command success!\n");
printf("write %d bytes.\n", res);
//大循环读取数据
while(1){
FD_ZERO(&recv_fd);
FD_SET(fd, &recv_fd);
while(FD_ISSET(fd, &recv_fd)){
if(select(fd+1, &recv_fd, NULL, NULL, NULL) < 0 ){
printf("select error\n");
}else{
read(fd,c,1);
printf("%02X %02d ",*c,len);
buff[len] = *c;
if (len > 7)
{
//判断是否接受到正确数据帧
if ((buff[len-2]==0xFF)&& (buff[len-1]==0xC9)&&(buff[len]==0x05) )
{
// printf("%02X%02X%02X ",buff[len-2],buff[len-1],buff[len]);
// // printf("uartBodyTemperature ");
recv_flag = 1;
CKSUM = buff[len];
printf("\nrecv_flag=%d ",recv_flag);
}
//开始接受具体参数
if (recv_flag == 1)
{
temp_buf[j] = buff[len];