经 byte[] 与 int 数据转换,于 Android 环境获取传感器实际测量值

传感器硬件: HTU31DF , BH1750 光照度传感器,ADP5092 太阳能微能量采集模块

ADC : Nordic nRF52840 12位 ADC 单端采集

软件环境: Android Java


        // 电池电压计算
        // 单端电压检测电阻分压阻值为: 1500,180欧姆,ADC 转换公式:ADC值 = (Vp-Vn)*GAIN/REFERENCE * 2^(RESOLUTION-m), GAIN=1,REFERENCE=0.6,RESOLUTION=12,m=0,Vn=0V,Vp=检测电阻端实际电压值
        int     valueOfVoltageADC   = 0;
        float   measurement_offset  = 0.06f;
        float   voltageOfBattery    = 0.0f;
        valueOfVoltageADC           = ((data_of_measurement[8] & 0x000000FF) << 8) + (data_of_measurement[9] & 0x000000FF);
        valueOfVoltageADC           &= 0x0000FFFF;
        voltageOfBattery            = (float) (((float) valueOfVoltageADC / 1.0 / 4096.0 * 0.6 - 0.0) * (1500.0 + 180.0) / 180.0 - measurement_offset);

        // 计算 HTU21DF SENSOR 的温度测量值
        int iTempValue      = 0;
        iTempValue          = ( (data_of_measurement[10] & 0x000000FF) << 8 ) + (data_of_measurement[11] & 0x000000FF);
        iTempValue          &= 0x0000FFFC;
        float fTempValue    = 0.0f;
        fTempValue          = (float)((float) iTempValue / 65536.0); 					//2^16 = 65536
        fTempValue          = (float) (-46.85 + (175.72 * fTempValue));

        // 计算 HTU21DF SENSOR 的湿度测量值

        int iRHValue    = 0;
        iRHValue        = ( (data_of_measurement[12] & 0x000000FF) << 8 )  +  (data_of_measurement[13] & 0x000000FF);
        iRHValue        &= 0x0000FFFC;
        float fRHValue = 0.0f;
        fRHValue        =  (float)((float)iRHValue / 65536.0); 					//2^16 = 65536
        fRHValue        = (float)(-6.0 + (125.0 * fRHValue));
        if (fRHValue < 0.0f)    fRHValue = 0.0f;
        if (fRHValue > 100.0f)  fRHValue = 100.0f;

//  BH1750 光照度值
        int iIlluValue  = 0;
        iIlluValue      = ( (data_of_measurement[14] & 0x000000FF) << 8 ) + (data_of_measurement[15] & 0x000000FF);
        iIlluValue      &= 0x0000FFFC;

注意: 

JAVA int 数据类型为 4 字节有符号数, 故 byte[] 数据操作前,先用 & 0x000000FF 进行处理,以避免单字节 byte[] 在运算时,被系统转换为有符号数,而导致错误!

你可能感兴趣的:(Android)