Project related to FreeRTOS

Hello Every one!
I’m a new learner learn FreeRTOS
I want to build a project with 5 task:

  1. Read Data From DHT11 Sensor every 10s
  2. Display on OLED Screen. every 2s
  3. Connect ESP32 to local Wifi
  4. Connect to HiveMQ MQTT
  5. Send to HiveMQ every 20s.

Now I am confusing that I am going on right way.
Sometimes, My code is bocked I don’t know why, All the things I know is change the Stack Size when create newTask in Setup functions.

If you know about project in freeRTOS, would you like to help me
understand what I built was true or wrong?

Thank you very much!

This is task ReadDH


THis is task Connect to wifi

this is task display OLED screen?

Hello @QuocvuSw,

Although your project uses FreeRTOS, you don’t make clear that the problem is related to the OS.

For a reviewer, screen shorts are very hard to work with, they’re pictures, not text.

All I can recommend is: start debugging your project, task by task. Start with a simple task that you can step through and that produces logging.

And report back here when you have a specific question about FreeRTOS.

Good luck

Thank you very much!
I just want to know if the way I’m creating and calling the tasks is correct because I create all
the tasks in setup function and each task has priority on its own. I’m wondering whether this approach is efficient when multiple tasks are running.

Here is main.cpp

#include <Arduino.h>
#include "../include/Wifi/wifi_connection.h"
#include "../include/Sensor/dht11.h"
#include "../include/Oled/oled96.h"

#include "../include/Mqtt/mqtt.h"

#define LED_PIN 2
#define LED_WIFI 4

void setup() {
  Serial.begin(115200);
  initOled();
  connectWifi();
  mqttInit();
  xTaskCreate(WifiMonitorTask, "ReconnectWifi", 4096, NULL,2,NULL);
   xTaskCreate(MqttMonitorTask, "ConnectMQTT", 8192, NULL,1, NULL);
  xTaskCreate(TaskTemperature, "ReadDHT11", 2048, NULL,1,NULL);
  xTaskCreate(TaskDisplayOled,"Oled",2048, NULL,1,NULL );
}


void loop() {
  
    
}

Here is MQTT.cpp

#include "../include/Mqtt/mqtt.h"


const char* mqtt_server = "85833738f7d240b29144c046a83534f0.s1.eu.hivemq.cloud";
const char* mqtt_username = "iot_home";
const char* mqtt_password = "Quocvu2002@";
const int  mqtt_port = 8883;

const char* root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIB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A1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";


PubSubClient client(espclient);

unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

/**INIT  MQTTT */
void mqttInit() {
    pinMode(LED_T, OUTPUT);
    espclient.setCACert(root_ca);
    client.setServer(mqtt_server,8883);
    client.setCallback(callback);

}

bool isMqttConnected() {
  return client.connected() == true;
}

/**CALLBACK MESSAGE*/
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  /** LED TEST */
  if ((char)payload[0] == '1') {
    digitalWrite(LED_T, LOW);   // Turn the LED on (Note that LOW is the voltage level

  } else {
    digitalWrite(LED_T, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

/*CONNECT TO MQTT */
void reconnect() {
  while (!isMqttConnected()) {
    Serial.print("reconnect...");
    String clientId = "device1";
    clientId += String(random(0xffff), HEX);
    printf("\nClientID: %s", clientId);
    if(client.connect(clientId.c_str(),mqtt_username, mqtt_password)) {
      Serial.println("\nMQTTconnected");
      /* subscribe to temp topic */
      client.subscribe("home/temperature");

    } else {
      Serial.println(WiFi.localIP());
      Serial.print("failed, rc=");
      Serial.print(client.state());
      vTaskDelay(5000/portTICK_PERIOD_MS);
    }
  }
}
/* RECONNECT WHEN NEEDED*/
void reconnectIfNeed() {
  if(!isMqttConnected()) {
    reconnect();
  }
}
/**PUBLIC MESSAGE */
void publicMessage(const char* topic, String payload,boolean retained) {
  if(client.publish(topic, payload.c_str(),true)) {
    Serial.println("Public success to topic[" + String(topic) + "]: " +payload);
  }
}

/**MQTT TASK */
void MqttMonitorTask(void *pvParameter) {
  while(true) {
    reconnectIfNeed();
    client.loop();
    vTaskDelay(5000/portTICK_PERIOD_MS); // keep alive with MQTT
  }
}

Wifi.cpp

#include "../include/Wifi/wifi_connection.h"

WiFiClientSecure espclient;

const char* host = "esp32";
const char* ssid = "DATN";
const char* password = "12345678";

void connectWifi() {
    WiFi.begin(ssid, password);
  // Wait for connection
  Serial.print("Connecting to WiFi");
  int retries = 0;
  while (WiFi.status() != WL_CONNECTED && retries < 20) {
    Serial.print(".");
    vTaskDelay(500 / portTICK_PERIOD_MS);
    retries++;
  }
   if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected!");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("");
    Serial.println("WiFi connection failed.");
  }
}
bool isWifiConnected() {
    return WiFi.status() == WL_CONNECTED;
}
void reconnectIfNeeded() {
    if(!isWifiConnected()) {
        Serial.println("WiFi disconnected. Reconnecting...");
        connectWifi();
    }
}
/** WIFI CONNECT */
void WifiMonitorTask(void *pvParameter){
    while (true)
    {
        reconnectIfNeeded();
         vTaskDelay(10000 / portTICK_PERIOD_MS); // check wifi every 10s
    }
}

read dht11.cpp

#include "../include/Sensor/dht11.h"


DHT dht(DHTPIN, DHTTYPE);
float temperature = 0;
float humidity = 0;

void readDHT11(){
    dht.begin();
    temperature= dht.readTemperature();
    humidity = dht.readHumidity();

    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(temperature)) {
        Serial.println(F("Failed to read from DHT sensor!"));
        return;
    }
    Serial.print(F("%\nTemperature: "));
    Serial.print(temperature);
    Serial.print(F("\nHumidity: "));
    Serial.print(humidity);

}
/** READ DHT11 SENSOR */
void TaskTemperature(void *pvParameters) {
    while (true)
    {
        readDHT11();
        vTaskDelay(10000/portTICK_PERIOD_MS);
    }
    
}

oled.cpp

#include "../include/Oled/oled96.h"
#include "../include/Sensor/dht11.h"

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
SemaphoreHandle_t xMutex = xSemaphoreCreateMutex();

/**INIT OLEd */
void initOled(){
     if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
      Serial.println(F("SSD1306 allocation failed"));
      for(;;); // Don't proceed, loop forever
    }
      display.clearDisplay();
      display.setTextSize(1); // Draw 1X-scale text
      display.setTextColor(SSD1306_WHITE);
}

/** Display Data */
void displayTemperature() {
    if(xSemaphoreTake(xMutex, portMAX_DELAY)) {
        float temp = temperature;
        float hum = humidity;

        xSemaphoreGive(xMutex);
        
        display.clearDisplay();                

        display.setCursor(0, 0);
        display.print(F("Nhiet do: "));
        display.print(temp);
        display.println(" C");

        display.setCursor(0, 10);              
        display.print(F("Do am   : "));
        display.print(hum);
        display.println(" %");

        display.display();    
    }                  
}

/* Task display */
void TaskDisplayOled(void *pvParameter) {
    while (true)
    {
        displayTemperature();
        vTaskDelay(2000/portTICK_PERIOD_MS);
    }
    
}

The task creation seems correct. You should check the return value of xTaskCreate to ensure that tasks are getting created successfully. You should also check with the authors of the libraries you are using to ensure that these libraries are designed to be used with FreeRTOS.