您的位置:首页 > 产品设计 > 产品经理

基于dragonboard410c 家庭智能环保卫士之PM2.5模块代码分析

2017-03-09 13:45 471 查看
前言:

#include     <stdio.h>
#include     <stdlib.h>
#include     <unistd.h>
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <fcntl.h>
#include     <termios.h>
#include     <errno.h>
#include 	 <sys/poll.h>
#include     <sys/ioctl.h>
#include     <string.h>

#define UART_DEVICE_NAME "/dev/tty96B0"
#define BUF_LEN  256

static int fd = -1;

//设置串口通信速率9600 设置串口数据位8,停止位1 和 效验位无
static int open_dev(char *dev_name)
{
struct termios opt;

fd = open(dev_name, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd < 0)
{
perror("open");
return fd;
}

tcgetattr(fd, &opt);
cfsetispeed(&opt, B9600);
cfsetospeed(&opt, B9600);

if(tcsetattr(fd, TCSANOW, &opt) != 0 )
{
perror("tcsetattr error");
return -1;
}

opt.c_cflag &= ~CSIZE;
opt.c_cflag |= CS8;
opt.c_cflag &= ~CSTOPB;
opt.c_cflag &= ~PARENB;
opt.c_cflag &= ~INPCK;
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
opt.c_oflag &= ~OPOST;
opt.c_oflag &= ~(ONLCR | OCRNL);    //添加的
opt.c_iflag &= ~(ICRNL | INLCR);
opt.c_iflag &= ~(IXON | IXOFF | IXANY);    //添加的
opt.c_cc[VTIME] = 0;
opt.c_cc[VMIN] = 0;
tcflush(fd, TCIOFLUSH);
printf("configure complete\n");
if(tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("serial error");
return -1;
}
return fd;
}

int main(int argc,char *argv[])
{
int fd;
int i;
int len;
int n = 0;
char buf_uart[BUF_LEN],grade;
int iRet = 0;
float pm_value = 0;

fd  = open_dev(UART_DEVICE_NAME);//init uart and open uart
if(fd == -1)
{
perror("open serial error\n");
exit(0);
}

printf("start send and receive data\n");

#if 1
struct pollfd read_poll[2];
read_poll[0].fd = fd;      /* fd_uart */
read_poll[0].events = POLLIN;
read_poll[0].revents = 0;

read_poll[1].fd = 0;      /* stdin */
read_poll[1].events = POLLIN;
read_poll[1].revents = 0;

while (1)
{
printf("waitting...\n");
iRet = poll(read_poll, 2, -1);
if(iRet <= 0)
{
printf("nothing come\n");
continue;
}
//printf("comming a new input!\n");

if (read_poll[0].revents & POLLIN)
{
bzero(buf_uart, BUF_LEN);
len = read(fd, buf_uart, BUF_LEN);
buf_uart[len] = '\0';
if(len < 0)
{
perror("read");
exit(1);
}
pm_value = (int)buf_uart[3]+(int)buf_uart[4]*0.01;
switch((int)pm_value/2)
{
case 0:
grade = 'a';
break;
case 1:
grade = 'b';
break;
case 2:
grade = 'c';
break;
case 4:
grade = 'd';
break;
}
printf(" 当前空气质量: %4.2f %%  %c \n", pm_value,grade);
}

}//while(1)
kk_exit : close(fd);
return 0;
#endif
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息