crisap94 / MHZ19

MH-Z19 CO2 sensor library for ESP8266 or Arduino
Other
68 stars 24 forks source link

Unusual code #19

Closed MikeyMoMo closed 2 years ago

MikeyMoMo commented 2 years ago

Looking at this code in the get PWM pin reading with PulseIn, "th + tl - 4" is always going to be 1000. So that routine could read:

switch (PWM_DATA_SELECT) {
case MHZ19_PWM_DATA::CALC_2000_PPM:
return (pulseIn((_pwm_pin, HIGH, 1004000) / 1000 - 2) / 500);  // Return the value for setting 2000
break;
case MHZ19_PWM_DATA::CALC_5000_PPM:  // or say default
return (pulseIn((_pwm_pin, HIGH, 1004000) / 1000 - 2) / 200);  // Return the value for setting 5000
break;
}

For the 5000 setting, the 500 becomes 200. No need for th, tl or ppm variables at all.

Am I missing something here?

The pulse length, in ms is just about 1/2 the reading you want to display. Not sure why the -2 in there but maybe the hardware requires a 2 µs adjustment. And that is what your routine returns -- pulse length in ms multiplied by 2 or 5. It is a complex way to multiply by 2 or 5.


               th = pulseIn(_pwm_pin, HIGH, 1004000) / 1000;  // Convert µs to ms
        tl = 1004 - th;                                                     // Create useless variable
        switch (PWM_DATA_SELECT)
        {
        case MHZ19_PWM_DATA::CALC_2000_PPM:
            ppm = 2000 * (th - 2) / (th + tl - 4);
            break;
        case MHZ19_PWM_DATA::CALC_5000_PPM:
            ppm = 5000 * (th - 2) / (th + tl - 4);
            break;
MikeyMoMo commented 2 years ago

OK, crappy code left and will always be there. Calculate 1000 then divide it back down to what was used to create it. Just a waste of time! But no interest by the author so closing this now.