RaspberrPi project source code
guowenxue
2 days ago 98766aaabcb1fa74123247a52e72a453b6da59f8
Update TSL2561 to sample for 5 times
2 files modified
65 ■■■■■ changed files
project/lightd/hal/tsl2561.c 61 ●●●●● patch | view | raw | blame | history
project/lightd/lightd.c 4 ●●●● patch | view | raw | blame | history
project/lightd/hal/tsl2561.c
@@ -142,7 +142,7 @@
    return 0;
}
int tsl2561_get_lux(float *lux)
int tsl2561_sample_lux(float *lux)
{
    int                 i, fd;
    int                 rv = 0;
@@ -223,3 +223,62 @@
    close(fd);
    return rv;
}
/**
 * @brief 采样TSL2561光照强度数据
 * @param lux 输出参数,存储计算后的光照强度值
 * @return int 0成功,-1失败
 */
#define SAMPLE_COUNT 5
int tsl2561_get_lux(float *lux)
{
    float       samples[SAMPLE_COUNT];
    float       current_lux, temp;
    int         valid_samples = 0;
    int         i,j;
    if (!lux) {
        log_error("Invalid input argument\n");
        return -1;
    }
    /* 采样N次数据 */
    for (i=0; i<SAMPLE_COUNT; i++)
    {
        if (tsl2561_sample_lux(&current_lux) == 0) {
            samples[valid_samples++] = current_lux;
        }
        if (i < SAMPLE_COUNT-1) {
            msleep(100);
        }
    }
    if (valid_samples == 0)
    {
        log_error("All TSL2561 samples failed\n");
        return -2;
    }
    /* 只有一个有效采样,直接使用 */
    if (valid_samples == 1)
    {
        *lux = samples[0];
        return 0;
    }
    /* 对采样值进行排序 */
    for (i=0; i<valid_samples-1; i++) {
        for (j = i + 1; j < valid_samples; j++) {
            if (samples[i] > samples[j]) {
                temp = samples[i];
                samples[i] = samples[j];
                samples[j] = temp;
            }
        }
    }
    /* 取中位数 */
    *lux = samples[valid_samples / 2];
    return 0;
}
project/lightd/lightd.c
@@ -142,8 +142,8 @@
    log_info("Auto light control thread start\n");
    while( ! g_signal.stop )
    {
        /* TSL2561 update lux in every 5 minutes  */
        if(check_timeout(&last_time, 300))
        /* TSL2561 update lux in every 10 minutes  */
        if(check_timeout(&last_time, 600))
        {
            /* The TSL2561 sensor is not present, do not turn on the light */
            if( !hwinfo->tsl2561 )