Multiple MH-Z19 sensors in the same board

So, I have to measure CO2 from multiple MH-Z19 sensors simultaneously in the same board. But all the codes I found only measure from one.
I came up with this code, using two MH-Z19 sensors, and it obviously doesn't work.


#include <Arduino.h>
#include <MHZ19.h>
#include <SoftwareSerial.h>


#define RX_PIN1 10
#define TX_PIN1 11
#define RX_PIN2 8
#define TX_PIN2 9
#define BAUDRATE 9600                                      // Device to MH-Z19 Serial baudrate (should not be changed)

MHZ19 myMHZ191, myMHZ192;                                             // Constructor for library

SoftwareSerial mySerial1(RX_PIN1, TX_PIN1);                // (Uno example) create device to MH-Z19 serial
SoftwareSerial mySerial2(RX_PIN2, TX_PIN2);

void setup() {
    Serial.begin(9600);                                     // Device to serial monitor feedback
    mySerial1.begin(BAUDRATE);                               // (Uno example) device to MH-Z19 serial start
    myMHZ191.begin(mySerial1);                               // *Serial(Stream) refence must be passed to library begin().

    mySerial2.begin(BAUDRATE);                               // (Uno example) device to MH-Z19 serial start
    myMHZ192.begin(mySerial2);   
    
    myMHZ191.autoCalibration(false);                          // Turn auto calibration OFF (OFF autoCalibration(false))
    myMHZ192.autoCalibration(false);
}

void loop() {
    /* note: getCO2() default is command "CO2 Unlimited". This returns the correct CO2 reading even 
    if below background CO2 levels or above range (useful to validate sensor). You can use the 
    usual documented command with getCO2(false) */
    
    Serial.println(myMHZ191.getCO2());
    Serial.println(myMHZ192.getCO2());
    
    delay(5000);
}

Is this dumb or there is a way to make it work?

Thanks in advance

SoftwareSerial can only be used once, at least it can only have one object listening at the same time.
You can get your code working if you call the listen() method on the corresponding SoftwareSerial object before using a method on the MHZ19 object.

1 Like

Thanks!! Using the listen() method makes it work.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.