Déclaration de variables

Bonjour, je suis novice la dedans.

J'ai un arduino nano ESP 32 et un capteur SCD40 (température, humidité et CO2)

J'ai le code " DFRobot_SCD4X" qui me permet de lire les valeurs du capteur.

Je souhaiterais pouvoir utilisé la valeur de co2 pour mettre par exemple une sortie a 1

Une idée de comment faire ?

#include <DFRobot_SCD4X.h>

/**
 * @brief Constructor
 * @param pWire - Wire object is defined in Wire.h, so just use &Wire and the methods in Wire can be pointed to and used
 * @param i2cAddr - SCD4X I2C address.
 */
DFRobot_SCD4X SCD4X(&Wire, /*i2cAddr = */SCD4X_I2C_ADDR);

void setup(void)
{
  Serial.begin(115200);

  // Init the sensor
  while( !SCD4X.begin() ){
    Serial.println("Communication with device failed, please check connection");
    delay(3000);
  }
  Serial.println("Begin ok!");

  /**
   * @brief set periodic measurement mode
   * @param mode - periodic measurement mode:
   * @n       SCD4X_START_PERIODIC_MEASURE : start periodic measurement, signal update interval is 5 seconds.
   * @n       SCD4X_STOP_PERIODIC_MEASURE : stop periodic measurement command
   * @n       SCD4X_START_LOW_POWER_MEASURE :  start low power periodic measurement, signal update interval is approximately 30 seconds.
   * @return None
   * @note The measurement mode must be disabled when configuring the sensor; after giving the stop_periodic_measurement command, the sensor needs to wait 500ms before responding to other commands.
   */
  SCD4X.enablePeriodMeasure(SCD4X_STOP_PERIODIC_MEASURE);

  /**
   * @brief set temperature offset
   * @details T(offset_actual) = T(SCD4X) - T(reference) + T(offset_previous)
   * @n T(offset_actual): the calculated actual temperature offset that is required
   * @n T(SCD4X): the temperature measured by the sensor (wait for a period of time to get steady readings)
   * @n T(reference): the standard reference value of the current ambient temperature
   * @n T(offset_previous): the previously set temperature offset
   * @n For example : 32(T(SCD4X)) - 30(T(reference)) + 2(T(offset_previous)) = 4(T(offset_actual))
   * @param tempComp - temperature offset value, unit ℃
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  SCD4X.setTempComp(4.0);

  /**
   * @brief get temperature offset
   * @return The current set temp compensation value, unit ℃
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  float temp = 0;
  temp = SCD4X.getTempComp();
  Serial.print("The current temperature compensation value : ");
  Serial.print(temp);
  Serial.println(" C");

  /**
   * @brief set sensor altitude
   * @param altitude - the current ambient altitude, unit m
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  SCD4X.setSensorAltitude(540);

  /**
   * @brief get sensor altitude
   * @return The current set ambient altitude, unit m
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  uint16_t altitude = 0;
  altitude = SCD4X.getSensorAltitude();
  Serial.print("Set the current environment altitude : ");
  Serial.print(altitude);
  Serial.println(" m");

  /**
   * @brief set automatic self calibration enabled
   * @param mode - automatic self-calibration mode:
   * @n       true : enable automatic self-calibration
   * @n       false : disable automatic self-calibration
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  // SCD4X.setAutoCalibMode(true);

  /**
   * @brief get automatic self calibration enabled
   * @return Automatic self-calibration mode:
   * @n        true : enable automatic self-calibration
   * @n        false : disable automatic self-calibration
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  // if(SCD4X.getAutoCalibMode()) {
  //   Serial.println("Automatic calibration on!");
  // } else {
  //   Serial.println("Automatic calibration off!");
  // }

  /**
   * @brief persist settings
   * @details Configuration settings such as the temperature offset, sensor altitude and the ASC enabled/disabled 
   * @n  parameter are by default stored in the volatile memory (RAM) only and will be lost after a power-cycle.
   * @return None
   * @note To avoid unnecessary wear of the EEPROM, the persist_settings command should only be sent 
   * @n  when persistence is required and if actual changes to the configuration have been made. 
   * @n  The EEPROM is guaranteed to endure at least 2000 write cycles before failure.
   * @note Command execution time : 800 ms
   * @n When executing the command, the sensor can't be in period measurement mode
   */
  // SCD4X.persistSettings();

  /**
   * @brief reinit reinit
   * @details  The reinit command reinitializes the sensor by reloading user settings from EEPROM.
   * @return None
   * @note Before sending the reinit command, the stop measurement command must be issued.
   * @n  If the reinit command does not trigger the desired re-initialization, 
   * @n  a power-cycle should be applied to the SCD4x.
   * @n  Command execution time : 20 ms
   * @n When executing the command, the sensor can't be in period measurement mode
   */
  //SCD4X.moduleReinit();

  /**
   * @brief set periodic measurement mode
   * @param mode - periodic measurement mode:
   * @n       SCD4X_START_PERIODIC_MEASURE : start periodic measurement, signal update interval is 5 seconds.
   * @n       SCD4X_STOP_PERIODIC_MEASURE : stop periodic measurement command
   * @n       SCD4X_START_LOW_POWER_MEASURE :  start low power periodic measurement, signal update interval is approximately 30 seconds.
   * @return None
   * @note The measurement mode must be disabled when changing the sensor settings; after giving the stop_periodic_measurement command, the sensor needs to wait 500ms before responding to other commands.
   */
  SCD4X.enablePeriodMeasure(SCD4X_START_PERIODIC_MEASURE);

  Serial.println();
}

void loop()
{
  /**
   * @brief get data ready status
   * @return data ready status:
   * @n        true : data ready
   * @n        false : data not ready
   */
  if(SCD4X.getDataReadyStatus()) {
    /**
     * @brief set ambient pressure
     * @param ambientPressure - the current ambient pressure, unit Pa
     * @return None
     */
    // SCD4X.setAmbientPressure(96000);

    /**
     * @brief Read the measured data
     * @param data - sSensorMeasurement_t, the values measured by the sensor, including CO2 concentration (ppm), temperature (℃) and humidity (RH)
     * @n  typedef struct {
     * @n    uint16_t   CO2ppm;
     * @n    float   temp;
     * @n    float   humidity;
     * @n  } sSensorMeasurement_t;
     * @return None
     * @note CO2 measurement range: 0~40000 ppm; temperature measurement range: -10~60 ℃; humidity measurement range: 0~100 %RH.
     */
    DFRobot_SCD4X::sSensorMeasurement_t data;
    SCD4X.readMeasurement(&data);

    Serial.print("Carbon dioxide concentration : ");
    Serial.print(data.CO2ppm);
    Serial.println(" ppm");

    Serial.print("Environment temperature : ");
    Serial.print(data.temp);
    Serial.println(" C");

    Serial.print("Relative humidity : ");
    Serial.print(data.humidity);
    Serial.println(" RH");

    Serial.println();
  }
  delay(1000);
}

Bonjour lucafrm13

Pour ce faire, il faut déclarer une pin de l'ESP32 en sortie:
const int co2HautPin = 15; // Pin de signalisation CO2 haut
et
pinMode(co2HautPin, OUTPUT); // Initialisation pin CO2 haut
pour l'exemple, la pin 15 à toi d'ajuster à ton montage.

ensuite déclarer une valeur limite:
const int co2HautSeuil = 1200; // Seuil d'alerte CO2

Dans la boucle, comparer la valeur de CO2:

	if (data.CO2ppm >= co2HautSeuil)
	{
		digitalWrite(co2HautPin, !co2HautEtatOn); // Alarme ON
	} 
	else
	{
		digitalWrite(co2HautPin, co2HautEtatOn); // Alarme OFF
	}

Ton programme modifié:

#include <DFRobot_SCD4X.h>

const int co2HautPin = 15; // Pin de signalisation CO2 haut
const int co2HautEtatOn = HIGH; // Pin de signalisation état de signal quand ON
const int co2HautSeuil = 1200; // Seuil d'alerte CO2	

/**
 * @brief Constructor
 * @param pWire - Wire object is defined in Wire.h, so just use &Wire and the methods in Wire can be pointed to and used
 * @param i2cAddr - SCD4X I2C address.
 */
DFRobot_SCD4X SCD4X(&Wire, /*i2cAddr = */SCD4X_I2C_ADDR);

void setup(void)
{
  Serial.begin(115200);
  pinMode(co2HautPin, OUTPUT); // Initialisation pin CO2 haut
  digitalWrite(co2HautPin, !co2HautEtatOn); // Alarme OFF

  // Init the sensor
  while( !SCD4X.begin() ){
    Serial.println("Communication with device failed, please check connection");
    delay(3000);
  }
  Serial.println("Begin ok!");

  /**
   * @brief set periodic measurement mode
   * @param mode - periodic measurement mode:
   * @n       SCD4X_START_PERIODIC_MEASURE : start periodic measurement, signal update interval is 5 seconds.
   * @n       SCD4X_STOP_PERIODIC_MEASURE : stop periodic measurement command
   * @n       SCD4X_START_LOW_POWER_MEASURE :  start low power periodic measurement, signal update interval is approximately 30 seconds.
   * @return None
   * @note The measurement mode must be disabled when configuring the sensor; after giving the stop_periodic_measurement command, the sensor needs to wait 500ms before responding to other commands.
   */
  SCD4X.enablePeriodMeasure(SCD4X_STOP_PERIODIC_MEASURE);

  /**
   * @brief set temperature offset
   * @details T(offset_actual) = T(SCD4X) - T(reference) + T(offset_previous)
   * @n T(offset_actual): the calculated actual temperature offset that is required
   * @n T(SCD4X): the temperature measured by the sensor (wait for a period of time to get steady readings)
   * @n T(reference): the standard reference value of the current ambient temperature
   * @n T(offset_previous): the previously set temperature offset
   * @n For example : 32(T(SCD4X)) - 30(T(reference)) + 2(T(offset_previous)) = 4(T(offset_actual))
   * @param tempComp - temperature offset value, unit ℃
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  SCD4X.setTempComp(4.0);

  /**
   * @brief get temperature offset
   * @return The current set temp compensation value, unit ℃
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  float temp = 0;
  temp = SCD4X.getTempComp();
  Serial.print("The current temperature compensation value : ");
  Serial.print(temp);
  Serial.println(" C");

  /**
   * @brief set sensor altitude
   * @param altitude - the current ambient altitude, unit m
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  SCD4X.setSensorAltitude(540);

  /**
   * @brief get sensor altitude
   * @return The current set ambient altitude, unit m
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  uint16_t altitude = 0;
  altitude = SCD4X.getSensorAltitude();
  Serial.print("Set the current environment altitude : ");
  Serial.print(altitude);
  Serial.println(" m");

  /**
   * @brief set automatic self calibration enabled
   * @param mode - automatic self-calibration mode:
   * @n       true : enable automatic self-calibration
   * @n       false : disable automatic self-calibration
   * @return None
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  // SCD4X.setAutoCalibMode(true);

  /**
   * @brief get automatic self calibration enabled
   * @return Automatic self-calibration mode:
   * @n        true : enable automatic self-calibration
   * @n        false : disable automatic self-calibration
   * @note When executing the command, the sensor can't be in period measurement mode
   */
  // if(SCD4X.getAutoCalibMode()) {
  //   Serial.println("Automatic calibration on!");
  // } else {
  //   Serial.println("Automatic calibration off!");
  // }

  /**
   * @brief persist settings
   * @details Configuration settings such as the temperature offset, sensor altitude and the ASC enabled/disabled 
   * @n  parameter are by default stored in the volatile memory (RAM) only and will be lost after a power-cycle.
   * @return None
   * @note To avoid unnecessary wear of the EEPROM, the persist_settings command should only be sent 
   * @n  when persistence is required and if actual changes to the configuration have been made. 
   * @n  The EEPROM is guaranteed to endure at least 2000 write cycles before failure.
   * @note Command execution time : 800 ms
   * @n When executing the command, the sensor can't be in period measurement mode
   */
  // SCD4X.persistSettings();

  /**
   * @brief reinit reinit
   * @details  The reinit command reinitializes the sensor by reloading user settings from EEPROM.
   * @return None
   * @note Before sending the reinit command, the stop measurement command must be issued.
   * @n  If the reinit command does not trigger the desired re-initialization, 
   * @n  a power-cycle should be applied to the SCD4x.
   * @n  Command execution time : 20 ms
   * @n When executing the command, the sensor can't be in period measurement mode
   */
  //SCD4X.moduleReinit();

  /**
   * @brief set periodic measurement mode
   * @param mode - periodic measurement mode:
   * @n       SCD4X_START_PERIODIC_MEASURE : start periodic measurement, signal update interval is 5 seconds.
   * @n       SCD4X_STOP_PERIODIC_MEASURE : stop periodic measurement command
   * @n       SCD4X_START_LOW_POWER_MEASURE :  start low power periodic measurement, signal update interval is approximately 30 seconds.
   * @return None
   * @note The measurement mode must be disabled when changing the sensor settings; after giving the stop_periodic_measurement command, the sensor needs to wait 500ms before responding to other commands.
   */
  SCD4X.enablePeriodMeasure(SCD4X_START_PERIODIC_MEASURE);

  Serial.println();
}

void loop()
{
  /**
   * @brief get data ready status
   * @return data ready status:
   * @n        true : data ready
   * @n        false : data not ready
   */
  if(SCD4X.getDataReadyStatus()) {
    /**
     * @brief set ambient pressure
     * @param ambientPressure - the current ambient pressure, unit Pa
     * @return None
     */
    // SCD4X.setAmbientPressure(96000);

    /**
     * @brief Read the measured data
     * @param data - sSensorMeasurement_t, the values measured by the sensor, including CO2 concentration (ppm), temperature (℃) and humidity (RH)
     * @n  typedef struct {
     * @n    uint16_t   CO2ppm;
     * @n    float   temp;
     * @n    float   humidity;
     * @n  } sSensorMeasurement_t;
     * @return None
     * @note CO2 measurement range: 0~40000 ppm; temperature measurement range: -10~60 ℃; humidity measurement range: 0~100 %RH.
     */
    DFRobot_SCD4X::sSensorMeasurement_t data;
    SCD4X.readMeasurement(&data);

    Serial.print("Carbon dioxide concentration : ");
    Serial.print(data.CO2ppm);
    Serial.println(" ppm");
	if (data.CO2ppm >= co2HautSeuil)
	{
		digitalWrite(co2HautPin, !co2HautEtatOn); // Alarme ON
	} 
	else
	{
		digitalWrite(co2HautPin, co2HautEtatOn); // Alarme OFF
	}
	
    Serial.print("Environment temperature : ");
    Serial.print(data.temp);
    Serial.println(" C");

    Serial.print("Relative humidity : ");
    Serial.print(data.humidity);
    Serial.println(" RH");

    Serial.println();
  }
  delay(1000);
}

J'ai ajouté, tout ce qui débute par co2Haut.

A+
Cordialement
jpbbricole

Merci beaucoup pour votre réponse.

#include <DFRobot_SCD4X.h>
#include <ESP32Servo.h>

DFRobot_SCD4X SCD4X(&Wire, SCD4X_I2C_ADDR);

Servo myservo;  // Créer un objet Servo pour contrôler le servo
int pos = 0;     // Variable pour stocker la position du servo
int servoPin = 9;  // Pin à laquelle le servo est connecté (par exemple, GPIO 18 pour ESP32)

const int CO2ThresholdHigh = 1500;  // Seuil CO2 pour activer le servo
const int CO2ThresholdLow = 1000;    // Seuil CO2 pour désactiver le servo

// Nouvelle variable pour indiquer si le seuil de CO2 est dépassé
bool CO2High = false;
bool CO2ok = true;  // Initialiser à true pour que le servo soit actif au départ

void setup() {
  Serial.begin(115200);  // Initialiser la communication série

  // Initialiser le capteur SCD4X
  while (!SCD4X.begin()) {
    Serial.println("Communication avec le capteur échouée. Vérifiez la connexion.");
    delay(3000);
  }
  Serial.println("Initialisation OK!");

  // Initialiser le servo
  myservo.setPeriodHertz(50);  // fréquence standard de 50 Hz pour le servo
  myservo.attach(servoPin, 1000, 2000);  // Attache le servo à la pin spécifiée avec la plage de 1000 à 2000 microsecondes

  // Arrêter la mesure périodique pour configurer le capteur
  SCD4X.enablePeriodMeasure(SCD4X_STOP_PERIODIC_MEASURE);

  // Configurations supplémentaires du capteur ici...
  SCD4X.setTempComp(4.0);
  SCD4X.setSensorAltitude(100);
  
  // Démarrer la mesure périodique
  SCD4X.enablePeriodMeasure(SCD4X_START_PERIODIC_MEASURE);
}

void loop() {
  if (SCD4X.getDataReadyStatus()) {
    // Lire les données mesurées par le capteur
    DFRobot_SCD4X::sSensorMeasurement_t data;
    SCD4X.readMeasurement(&data);
    
    // Affichage des données de CO2, température et humidité dans le Serial Monitor
    Serial.print("Concentration de CO2 : ");
    Serial.print(data.CO2ppm);
    Serial.println(" ppm");

    Serial.print("Température : ");
    Serial.print(data.temp);
    Serial.println(" C");

    Serial.print("Humidité : ");
    Serial.print(data.humidity);
    Serial.println(" %RH");

    // Afficher les variables de seuils et d'état
    Serial.print("CO2ThresholdHigh : ");
    Serial.println(CO2ThresholdHigh);
    Serial.print("CO2ThresholdLow : ");
    Serial.println(CO2ThresholdLow);
    Serial.print("CO2High : ");
    Serial.println(CO2High ? "true" : "false");  // Affiche "true" ou "false"
    Serial.print("CO2ok : ");
    Serial.println(CO2ok ? "true" : "false");    // Affiche "true" ou "false"

    // Contrôler le servo en fonction des seuils de CO2
    if (data.CO2ppm > CO2ThresholdHigh && !CO2High) {
      CO2High = true;  // Le seuil de CO2 est dépassé
      CO2ok = false;   // Désactiver l'activation du servo
      myservo.writeMicroseconds(2000);  // Position 180° (2000 µs)
      delay(1200);
      
    } 
    if (data.CO2ppm < CO2ThresholdLow && !CO2ok) {
      CO2ok = true;    // Réactiver l'activation du servo
      CO2High = false; // Le seuil de CO2 est revenu en dessous du seuil bas
      myservo.writeMicroseconds(1000);  // Position 0° (1000 µs)
      delay(1200);
      
    }

    Serial.println();  // Ligne vide pour mieux séparer les lectures dans le Serial Monitor
  }
  delay(5000);  // Attendre 1 seconde avant la prochaine lecture
}

J'en suis arrivé à la, je souhaite que au delà d'un seuil haut mon servomoteur fasse une rotation de 180° puis s'arrête et quand les ppm repassent en dessous d'un seuil bas le moteur retourne à 0°

Cependant mon moteur tourne en permanence… Il change bien de sens quand on repasse le seuil bas mais sans jamais s'arrêter.

Merci d'avance pour toutes futures aides

Bonjour lucafrm13

Qu'entends tu par tourne en permanence? tu veux dire qu'il tourne à 360°?
Dans ce cas tu n'as pas le bon type de servo.

Autrement, ta "mécanique de réglage" du servo fonctionne.

A+
Cordialement
jpbbricole

bonjour !

Alors oui le servo est en rotation en permanence ( il change de sens en fonction des seuils quand même )

Ma première idée c’était que mes conditions dans les if soit toujours vrai, ce qui répéterait le mouvements en permanence ? mais pour moi ces conditions sont ok et permettent de faire ce que je veux…

C’est un servomoteur SG90-9G acheter sur aliexpress.

Bonjour lucafrm13

Tu n'est pas le premier à "te faire avoir", dans ces servo il est très difficile de voir que c'est des 360°, 360° veux dire rotation continue.
Il faut voir, dans la description, l'angle comme 60°, 180° voir 270°.

Cordialement
jpbbricole

Oh ok ! merci beaucoup en effet j’avais le choix entre 360* ou 180* sur aliexpress.

Donc un servomoteur avec la mention 180degres va me permettre de faire du positionnement ?

En tous cas merci beaucoup !

Oui.