CTBot Telegram bot not working after 2-3 msg

Hi Dear Friends, I am now creating a ESP32 based NTP clock with facility of message display to the MAX7219 led matrix whenever a person send message through the BOT that I have Created... Every thing works fine. But after reading 2-3 message from Telegram, the display didnot show any further message and jump to next switch condition.
In this project, I am using CTBot version 2.1.13 (latest), ArduinoJson version 6.19.4.

The Code is here under:

#include <WiFiClientSecure.h>
#include "CTBot.h"
#include <ArduinoJson.h>
#define BOTtoken "707859XXXX:AAHSWfgsOiTKEV5FC9gTG2EMnD79J2XXXXX";
WiFiClientSecure client;
CTBot myBot;


#include <WiFi.h>
#include <time.h>
#include "Font_Data.h"
#include <MD_Parola.h>
#include <MD_MAX72xx.h>

#define ThermistorPin 35
#define buzzer 2
#define NUM_ZONES 3
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define DATA_PIN 13    // pin connection in esp32
#define CLK_PIN 14     // pin connection in esp32
#define CS_PIN 12      // pin connection in esp32
#define MAX_DEVICES 4  //maximum max7219 module connected in chain
MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

#define SPEED_TIME 50  // Speed of the transition
#define PAUSE_TIME 1000


unsigned long previousMillis = 0;
// Global variables
float temp = 0;
char message[20] = "";
char szMesg[150] = "";
uint8_t degC[] = { 6, 3, 3, 28, 34, 34, 34 };  // Deg C
uint8_t clear = 0x00;
bool isPM;

char second[3], minute[3], hour[3], day[10], date[3], month[10], year[5];
const char* ssid = "HomeFiber_4g";      // SSID of local network
const char* password = "Hima@nilu123";  //Password of wifi

String myssid(ssid);
String mypass(password);
String token = "7078596485:AAHSWfgsOiTKEV5FC9gTG2EMnD79J2j087Q";  // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN


const char* ntpServer = "pool.ntp.org";  //NTP server for getting time
const long gmtOffset_sec = 19800;        //Set your timezone in second, Here I used for India(GMT+ 5.30hr)
const int daylightOffset_sec = 0;        //Daylight saving is off here for India


const long intervalo = 1000;  //Time interval between checking messages (in milliseconds)
int lastMinute = -1;
//getting time from NTP Server
void printLocalTime() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    getError(szMesg);
    return;
  }
  strftime(day, sizeof(day), "%A", &timeinfo);
  strftime(month, sizeof(month), "%B", &timeinfo);
  strftime(date, sizeof(date), "%d", &timeinfo);
  strftime(year, sizeof(year), "%Y", &timeinfo);
  strftime(hour, sizeof(hour), "%H", &timeinfo);
  strftime(minute, sizeof(minute), "%M", &timeinfo);
  strftime(second, sizeof(second), "%S", &timeinfo);
}

void getError(char* psz) {
  const char* err = "error";
  sprintf(psz, "%s", err);
  Serial.println(psz);
}
void getTime(char* psz, bool f = true) {
  int hourInt = atoi(hour);
  int hour12 = hourInt % 12;
  if (hour12 == 0) {
    hour12 = 12;
  }
  isPM = hourInt >= 12;
  sprintf(psz, "%02d%c%02d", hour12, (f ? ':' : ' '), atoi(minute));
}


void setup() {
  pinMode(buzzer, OUTPUT);
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);  // Connect to Wi-Fi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    myBot.wifiConnect(myssid, mypass);
    myBot.setTelegramToken(token);  // set the telegram bot token
    if (myBot.testConnection())
      Serial.println("\ntestConnection OK");
    else
      Serial.println("\ntestConnection NOK");
  }
  Serial.println("WiFi connected.");
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  delay(5000);
  printLocalTime();
  P.begin(NUM_ZONES);
  P.setZone(0, 0, 3);
  P.setIntensity(0);
  P.addChar('$', degC);
  P.displayZoneText(0, szMesg, PA_CENTER, SPEED_TIME, 0, PA_PRINT, PA_NO_EFFECT);
}


void loop() {

  getTemperature();
  printLocalTime();
  static uint32_t lastTime = 0;  // millis() memory
  static uint8_t display = 0;    // Current display mode
  static bool flasher = false;   // Seconds passing flasher

  if (atoi(second) == 0 && lastMinute != 0) {
    digitalWrite(buzzer, HIGH);
    delay(100);
    digitalWrite(buzzer, LOW);
  }
  lastMinute = atoi(second);
  P.displayAnimate();

  if (P.getZoneStatus(0)) {
    switch (display) {
      case 0:  // Temperature deg Celsius
        P.setFont(0, nullptr);
        P.setPause(0, 5000);
        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_UP);
        display++;
        dtostrf(temp, 3, 1, szMesg);
        strcat(szMesg, "$");
        Serial.print("Temperature: ");
        Serial.println(temp);
        break;

      case 1:  // Clock
        P.setFont(0, numeric7Seg);
        P.setTextEffect(0, PA_PRINT, PA_NO_EFFECT);
        P.setPause(0, 0);
        if ((millis() - lastTime) >= 500) {
          lastTime = millis();
          getTime(szMesg, flasher);
          Serial.println(szMesg);
          flasher = !flasher;
        }
        if ((atoi(second) == 5) && (atoi(second) <= 30)) {
          P.setTextEffect(0, PA_PRINT, PA_WIPE_CURSOR);
          display++;
        }
        break;

      case 2:  // Calendar
        P.setFont(0, nullptr);
        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        display++;
        getDays(szMesg);
        P.setPause(0, 3000);
        break;
      case 3:
        TBMessage msg;
        if (myBot.getNewMessage(msg, 0))  //Check if any message arrived
        {
         // blinker(1000, 3);
          msg.text.toCharArray(szMesg, 20);
          //Serial.println(msg.text);
          myBot.sendMessage(msg.sender.id, "Hello, " + msg.sender.firstName + msg.sender.lastName + ", Your Message: \n" + msg.text + "\ndisplayed on system...\n");
          P.setFont(0, nullptr);
          P.displayZoneText(0, szMesg, PA_CENTER, SPEED_TIME, 0, PA_PRINT, PA_SCROLL_LEFT);
          P.setPause(0, 2000);
        }
        display = 0;
        break;
    }
    P.displayReset(0);
  }
}

float getTemperature() {
  float R1 = 9950;  // value of R1 on board
  float logR2, R2;
  //steinhart-hart coeficients for thermistor
  float c1 = 0.001129148, c2 = 0.000234125, c3 = 0.0000000876741;
  long ADC_Value = analogRead(ThermistorPin);
  R2 = R1 * (4096.0 / (float)ADC_Value - 1.0);  //calculate resistance on thermistor
  logR2 = log(R2);
  temp = (1.0 / (c1 + c2 * logR2 + c3 * logR2 * logR2 * logR2));  // temperature in Kelvin
  temp = temp - 273.15;                                           //convert Kelvin to Celcius
  return temp;
}

void getDays(char* psz) {
  String dayStr = String(day);
  String monthStr = String(month);
  String subStr1 = dayStr.substring(0, 3);
  String subStr2 = monthStr.substring(0, 3);
  strcpy(szMesg, subStr2.c_str());
  strcat(szMesg, " ");
  strcat(szMesg, subStr1.c_str());
  strcat(szMesg, " ");
  strcat(szMesg, date);
  Serial.println(szMesg);
}

void blinker(long interval, int maxBlinks) {
   unsigned long currentMillis = millis();
  int blinkCount = 0;       // Counter to keep track of blinks
   // Number of LED state changes (2 blinks = 4 state changes)

  if (blinkCount < (maxBlinks*2) && currentMillis - previousMillis >= interval) {
    // Save the last time you blinked the LED
    previousMillis = currentMillis;

    // Toggle the LED state
    int buzzerState = digitalRead(buzzer);
    digitalWrite(buzzer, !buzzerState);

    // Increment the blink counter
    blinkCount++;
  }
}


The above Diagram i am using.

declaring a var inside a case will break the case..
try moving the declaration of msg to before the switch..
allot of code but that sticks out too me..

good luck.. ~q

1 Like

Not getting the solution by putting TBMessage msg; in void loop() first line and deleting from case 3. Further, the after the Case 3, it should have reteurn to Case 0, but in this case the loop Case 2 appear. and after some time Case0 appear. pls another solution.

try adding some serial prints and print out the value of display..
just before you enter the switch and just after you leave the switch..
i only see changes to display inside of the switch..

could try making display a global var..
maybe try a more unique variable name, something like myDisplay..

good luck.. ~q

with the enable of debut mode I can now see the problem as:
In the 1st 2-3 text the Debut message shows as:

ESP32 with https verification
Connected using DNS
--->sendCommand  : Free heap memory: 195780 / 198188 - 207 ms
{
  "ok": true,
  "result": {
    "id": 70785XXXXX,
    "is_bot": true,
    "first_name": "IoTCXXXXX",
    "username": "IoTXXXXX_bot",
    "can_join_groups": true,
    "can_read_all_group_messages": false,
    "supports_inline_queries": true,
    "can_connect_to_business": false,
    "has_main_web_app": false
  }
}



But after then the Error message shows as:

ESP32 with https verification
Unable to connect to Telegram server
getNewMessage error: ArduinoJson deserialization error code: EmptyInput

This might be problem with HEAP memory.

I can't figured out what to do.. My project is pending since 1months.
Anyone please help

Sorry for the late reply..
very busy myself as of late..

the error indicates a connection issue to the telegram server, maybe the wifi disconnected??

what I meant by adding Serial prints was to help figure out why the switch was breaking down..

 if (P.getZoneStatus(0)) {
  Serial.print("Entering Switch display:");
  Serial.println(display);
    switch (display) {

then just after the switch..

   } //end of switch
  Serial.print("Exiting Switch display:");
   Serial.println(display);
    P.displayReset(0);

could be a conflict with one of the display libs??
maybe try taking screen code out temporarily and just Serial print the values..

wifi disconnects can happen, does the bot auto reconnect or do you need to check for this and reconnect it yourself??

and yes, increasing the debug level may help as well, problem could be elsewhere and just so happens to crush the switch..

good luck.. ~q

The bot auto reconnect and show the above error in DEBUT mode.
Recently, I google again and found it may be error with HEAP memory..
I think problem is anywhere not in the Display library.. Why then only 2-3 message display fine. then TELEGRM stopped.

I got the Solution. I just downgrade the ES32 board to very early verison to 1.0.4.

AdurinoJson verison to 6.15.2
CTBot verison to 2.1.13

Thats it.. Thank you all..

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