这里有一个简单的 ESP32 程序来测试 UniversalTelegrambBot。 它可以毫无问题地连接到 wifi(使用外部机密文件)。 它从安装程序发送启动消息,但从不从循环发送虚拟字符串数据。 循环正在运行并打印出应发送的值,但 bot.sendMessage 在每个循环周期都返回 false。 如果我注释掉启动消息,则循环发送第一个值,此后不再发送。
使用 Arduino v 1.8.1、UniversalTelegrambot v 1.3.0、ArduinoJson v 6.19.4 和 Adafruit Huzzah ESP32。
/****************************************************************
*
* Sends dummy temperature value string to Telegram account
* once ever N minutes
*
*
* HARDWARE:
* Adafruit Huzzah ESP32
*
* SOFTWARE:
* Arduino v 1.8.19
* UniversalTelegramBot v 1.3.0
* ArduinoJson v 6.19.
*
* THIS CODE ONLY SENDS THE FIRST VALUE THEN FAILS TO SEND THE REST
* WHY?
*
* To program ESP32:
Hold GPIO0 button down
Press/release Reset button
Release GPIO0 button
When programming finishes, toggle reset button
*****************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiMulti.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include "Credentials.h"
WiFiMulti wifiMulti;
#define VER "TelegramBotDemo_v2"
// Turn on debugging
#define MY_DEBUG
// ************** Print to serial only when MY_DEBUG is defined *****************
#ifdef MY_DEBUG
#define DEBUG_PRINTF(x) Serial.print (x)
#define DEBUG_PRINTLNF(x) Serial.println (x)
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTDEC(x) Serial.print (x, DEC)
#define DEBUG_PRINTLN(x) Serial.println (x)
#define DEBUG_PRINTHEX(x) Serial.print(x,HEX)
#else
#define DEBUG_PRINTF(x)
#define DEBUG_PRINTLNF(x)
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTHEX(x)
#endif
bool wifiFound = false;
// Set GPIOs for LED and IO_PIN
const int BUILTIN_LED_PIN = 13; //optional
const int IO_PIN = 0;
float temp = 49.9;
bool state;
String TempState = "NONE";
bool firstTime = true;
unsigned long previousMillis = 0;
const long TIMER_INTERVAL = 1; // mins (set to 1 for test otherwise 60)
#define LED_ON HIGH
#define LED_OFF LOW
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOTtoken, secured_client);
/**********************************************
Round float to places places, return as string
***********************************************/
String rndS(float value, byte places)
{
//Storage for displaying float converted to char array
char valueChar[10];
dtostrf(value, 5, places, valueChar); //convert float to char array
String s = (String)valueChar;
s.trim(); //remove whitespace
return s ;
}
/************************************
* Connect to wifi and display stats
************************************/
boolean wifiConnect()
{
DEBUG_PRINTLN();
WiFi.mode(WIFI_STA);
uint32_t looptime = millis();
uint8_t loopCount = 0;
while (wifiMulti.run() != WL_CONNECTED)
{
while (millis() - looptime < 500L) yield(); // use this and not delay()
looptime = millis();
DEBUG_PRINT(".");
if(++loopCount >= 20){
DEBUG_PRINTLN("Timed out waiting for wiFi");
return false;
}
}
DEBUG_PRINTLN("");
// DEBUG_PRINT(F("SSID:"));
// DEBUG_PRINTLN(WiFi.SSID());
// DEBUG_PRINT(F("MAC:"));
// DEBUG_PRINTLN(WiFi.macAddress());
DEBUG_PRINT(F("IP address:"));
DEBUG_PRINTLN(WiFi.localIP());
DEBUG_PRINT(F("RSSI:"));
DEBUG_PRINTLN(WiFi.RSSI());
DEBUG_PRINTLN("WiFi Connected");
DEBUG_PRINTLN("");
return true;
}
/****************** SETUP ***************************/
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
Serial.println(VER);
// Set RED LED off (LOW)
pinMode(BUILTIN_LED_PIN, OUTPUT);
digitalWrite(BUILTIN_LED_PIN, LED_OFF);
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
// add multiple WAPs; it will pick the strongest
wifiMulti.addAP(ssid1, pass1);
wifiMulti.addAP(ssid2, pass2);
wifiMulti.addAP(ssid3, pass3);
if(wifiConnect()){
delay(500);
wifiFound = true; // not used
}
else
exit(0);
WiFi.setSleep(false);
// Send startup message (this always works)
if(bot.sendMessage(CHAT_ID, "Bot started up", ""))
DEBUG_PRINTLN("Startup Message sent");
else
DEBUG_PRINTLN("Startup Message NOT sent");
unsigned long previousMillis = millis();
} // END OF SETUP
/****************** LOOP ***************************/
void loop() {
if(millis() - previousMillis >= TIMER_INTERVAL*60000UL || firstTime) {
previousMillis = millis();
firstTime = false;
digitalWrite(BUILTIN_LED_PIN, LED_ON); // Flash RED LED
delay(200);
digitalWrite(BUILTIN_LED_PIN,LED_OFF);
TempState = String(rndS(temp,1));
DEBUG_PRINTLN(TempState);
if (WiFi.status() == WL_CONNECTED) {
//Send dummy string value ( this never works unless I comment out
// the startup message, then it works only once )
if(bot.sendMessage(CHAT_ID, "Temp: " + TempState, ""))
DEBUG_PRINTLN("Message sent");
else
DEBUG_PRINTLN("Message NOT sent");
}
else
DEBUG_PRINTLN("WiFi NOT connected");
} // END interval timer
} // END LOOP
解决了。 我放弃了 UTB,转而使用 CTBot 2.1.9,效果很好。
其实我也有同样的问题。我正在创建一个带有温度传感器的 NTP 时钟,并在 MAX7219 LED 上显示电报消息。但电报消息在 2 条消息显示后停止显示。我正在使用 ArduinoJson v 6.19.4 和 CTBot 版本 2.1.13... 请帮忙。
#include <WiFiClientSecure.h>
#include "CTBot.h"
#include <ArduinoJson.h>
#define BOTtoken "7078596485:AAHSWfgsOiTKEV5FC9gTG2EMnD79J2j087Q";
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 positivePin 33
#define negativePin 32
#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 = "70785XXXXX:AAHSWfgsOiTKEV5FC9gTG2EMnD79J2XXXXX"; //
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);
pinMode(positivePin, OUTPUT);
pinMode(negativePin, OUTPUT);
digitalWrite(positivePin, HIGH);
digitalWrite(negativePin, LOW);
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++;
}
}