MQTT и кнопки

Вы про эти строки?:
char *ssid = “RT-WiFi_17CB”; // Имя вайфай точки доступа
const char *password = “SJRJCJEJ”; // Пароль от точки доступа

const char *mqtt_server = “m5.wqtt.ru”; // Имя сервера MQTT Cluster
const int mqtt_port = 12346; // Порт для подключения к серверу MQTT
const char *mqtt_user = “u_WZIJ1V”; // Логин от сервер
const char *mqtt_pass = “FzoLDUAp”; // Пароль от сервера

Так это же превратится в текст…

Что это значит? У тебя пишет invalid UTF-8, если не будет символов а ошибка останется значит проблема не в строках.

или в тыкву.

2 лайка

Проблему с UTF-8 поборол откатив IDE до 2.3.2
Дошел до этого:

#include <MQTT.h>
#include <MQTTClient.h>
#include <PubSubClient.h>
#include <WiFi.h>

int button1 = 2; // указываем пин для первой кнопки
int button2 = 3; // указываем пин для второй кнопки
int button3 = 4; // указываем пин для третьей кнопки


char *ssid = "RT-WiFi_17CB";              // Имя вайфай точки доступа
char *password = "SJRJCJEJ";       // Пароль от точки доступа
const char *mqtt_server = "m5.wqtt.ru";  // Имя сервера MQTT Cluster
const int mqtt_port = 12346;             // Порт для подключения к серверу MQTT
const char *mqtt_user = "u_WZIJ1V";      // Логин от сервер
const char *mqtt_pass = "FzoLDUAp";      // Пароль от сервера

#define BUFFER_SIZE 100

WiFiClient wclient;
PubSubClient client(wclient);
//(wclient, mqtt_server, mqtt_port);

void setup() {
  // подключаемся к wi-fi
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to");
    Serial.print(ssid);
    Serial.println("...");
    WiFi.begin(ssid, password);

   if (WiFi.status() != WL_CONNECTED)
    return;
    Serial.println("WiFi connected");
  }

  // подключаемся к MQTT серверу
  if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
      Serial.println("Connecting to MQTT server");
      if (client.connect(MQTT::Connect("arduinoClient2")
                           .set_auth(mqtt_user, mqtt_pass))) {
        Serial.println("Connected to MQTT server");
        client.subscribe("BTN1");  // подписывааемся на топик с данными для 1-ой кнопки btn1
        client.subscribe("BTN2");  // подписывааемся на топик с данными для 2-ой кнопки btn2
        client.subscribe("BTN3");  // подписывааемся на топик с данными для 3-ой кнопки btn3
      } else {
        Serial.println("Could not connect to MQTT server");
      }
    }

    if (client.connected()) {
     client.loop();
    }
  }
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
}
//конец основного цикла

void loop() {
  if (digitalRead(button1) == LOW) {
    client.publish("BTN1", "pressed");
    Serial.println(1);
  }
  if (digitalRead(button2) == LOW) {
    client.publish("BTN2", "pressed");
    Serial.println(2);
  }
  if (digitalRead(button3) == LOW) {
    client.publish("BTN3", "pressed");
    Serial.println(3);
  }
  delay(100);
}

Ошибки:

C:\Users\3ЛТП\Documents\Arduino\MP_V01_copy_20241218094852_copy_20241218195939\MP_V01_copy_20241218094852_copy_20241218195939.ino:11:14: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
C:\Users\3ЛТП\Documents\Arduino\MP_V01_copy_20241218094852_copy_20241218195939\MP_V01_copy_20241218094852_copy_20241218195939.ino:12:18: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
C:\Users\3ЛТП\Documents\Arduino\MP_V01_copy_20241218094852_copy_20241218195939\MP_V01_copy_20241218094852_copy_20241218195939.ino: In function ‘void setup()’:
C:\Users\3ЛТП\Documents\Arduino\MP_V01_copy_20241218094852_copy_20241218195939\MP_V01_copy_20241218094852_copy_20241218195939.ino:41:26: error: ‘MQTT’ has not been declared

exit status 1

Compilation error: ‘MQTT’ has not been declared

Ссылается на 41 строку. Что в ней не так?

Выложи сюда MQTT.h и MQTTClient.h
Можно еще и пабсабклиент.хэ тоже

если я вас правильно понял, ПабСАб:

/*
 PubSubClient.h - A simple client for MQTT.
  Nick O'Leary
  http://knolleary.net
*/

#ifndef PubSubClient_h
#define PubSubClient_h

#include <Arduino.h>
#include "IPAddress.h"
#include "Client.h"
#include "Stream.h"

#define MQTT_VERSION_3_1      3
#define MQTT_VERSION_3_1_1    4

// MQTT_VERSION : Pick the version
//#define MQTT_VERSION MQTT_VERSION_3_1
#ifndef MQTT_VERSION
#define MQTT_VERSION MQTT_VERSION_3_1_1
#endif

// MQTT_MAX_PACKET_SIZE : Maximum packet size. Override with setBufferSize().
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 256
#endif

// MQTT_KEEPALIVE : keepAlive interval in Seconds. Override with setKeepAlive()
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 15
#endif

// MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds. Override with setSocketTimeout()
#ifndef MQTT_SOCKET_TIMEOUT
#define MQTT_SOCKET_TIMEOUT 15
#endif

// MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client
//  in each write call. Needed for the Arduino Wifi Shield. Leave undefined to
//  pass the entire MQTT packet in each write call.
//#define MQTT_MAX_TRANSFER_SIZE 80

// Possible values for client.state()
#define MQTT_CONNECTION_TIMEOUT     -4
#define MQTT_CONNECTION_LOST        -3
#define MQTT_CONNECT_FAILED         -2
#define MQTT_DISCONNECTED           -1
#define MQTT_CONNECTED               0
#define MQTT_CONNECT_BAD_PROTOCOL    1
#define MQTT_CONNECT_BAD_CLIENT_ID   2
#define MQTT_CONNECT_UNAVAILABLE     3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED    5

#define MQTTCONNECT     1 << 4  // Client request to connect to Server
#define MQTTCONNACK     2 << 4  // Connect Acknowledgment
#define MQTTPUBLISH     3 << 4  // Publish message
#define MQTTPUBACK      4 << 4  // Publish Acknowledgment
#define MQTTPUBREC      5 << 4  // Publish Received (assured delivery part 1)
#define MQTTPUBREL      6 << 4  // Publish Release (assured delivery part 2)
#define MQTTPUBCOMP     7 << 4  // Publish Complete (assured delivery part 3)
#define MQTTSUBSCRIBE   8 << 4  // Client Subscribe request
#define MQTTSUBACK      9 << 4  // Subscribe Acknowledgment
#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request
#define MQTTUNSUBACK    11 << 4 // Unsubscribe Acknowledgment
#define MQTTPINGREQ     12 << 4 // PING Request
#define MQTTPINGRESP    13 << 4 // PING Response
#define MQTTDISCONNECT  14 << 4 // Client is Disconnecting
#define MQTTReserved    15 << 4 // Reserved

#define MQTTQOS0        (0 << 1)
#define MQTTQOS1        (1 << 1)
#define MQTTQOS2        (2 << 1)

// Maximum size of fixed header and variable length size header
#define MQTT_MAX_HEADER_SIZE 5

#if defined(ESP8266) || defined(ESP32)
#include <functional>
#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback
#else
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)
#endif

#define CHECK_STRING_LENGTH(l,s) if (l+2+strnlen(s, this->bufferSize) > this->bufferSize) {_client->stop();return false;}

class PubSubClient : public Print {
private:
   Client* _client;
   uint8_t* buffer;
   uint16_t bufferSize;
   uint16_t keepAlive;
   uint16_t socketTimeout;
   uint16_t nextMsgId;
   unsigned long lastOutActivity;
   unsigned long lastInActivity;
   bool pingOutstanding;
   MQTT_CALLBACK_SIGNATURE;
   uint32_t readPacket(uint8_t*);
   boolean readByte(uint8_t * result);
   boolean readByte(uint8_t * result, uint16_t * index);
   boolean write(uint8_t header, uint8_t* buf, uint16_t length);
   uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos);
   // Build up the header ready to send
   // Returns the size of the header
   // Note: the header is built at the end of the first MQTT_MAX_HEADER_SIZE bytes, so will start
   //       (MQTT_MAX_HEADER_SIZE - <returned size>) bytes into the buffer
   size_t buildHeader(uint8_t header, uint8_t* buf, uint16_t length);
   IPAddress ip;
   const char* domain;
   uint16_t port;
   Stream* stream;
   int _state;
public:
   PubSubClient();
   PubSubClient(Client& client);
   PubSubClient(IPAddress, uint16_t, Client& client);
   PubSubClient(IPAddress, uint16_t, Client& client, Stream&);
   PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
   PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);
   PubSubClient(uint8_t *, uint16_t, Client& client);
   PubSubClient(uint8_t *, uint16_t, Client& client, Stream&);
   PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
   PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);
   PubSubClient(const char*, uint16_t, Client& client);
   PubSubClient(const char*, uint16_t, Client& client, Stream&);
   PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client);
   PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&);

   ~PubSubClient();

   PubSubClient& setServer(IPAddress ip, uint16_t port);
   PubSubClient& setServer(uint8_t * ip, uint16_t port);
   PubSubClient& setServer(const char * domain, uint16_t port);
   PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE);
   PubSubClient& setClient(Client& client);
   PubSubClient& setStream(Stream& stream);
   PubSubClient& setKeepAlive(uint16_t keepAlive);
   PubSubClient& setSocketTimeout(uint16_t timeout);

   boolean setBufferSize(uint16_t size);
   uint16_t getBufferSize();

   boolean connect(const char* id);
   boolean connect(const char* id, const char* user, const char* pass);
   boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
   boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
   boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession);
   void disconnect();
   boolean publish(const char* topic, const char* payload);
   boolean publish(const char* topic, const char* payload, boolean retained);
   boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
   boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
   boolean publish_P(const char* topic, const char* payload, boolean retained);
   boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
   // Start to publish a message.
   // This API:
   //   beginPublish(...)
   //   one or more calls to write(...)
   //   endPublish()
   // Allows for arbitrarily large payloads to be sent without them having to be copied into
   // a new buffer and held in memory at one time
   // Returns 1 if the message was started successfully, 0 if there was an error
   boolean beginPublish(const char* topic, unsigned int plength, boolean retained);
   // Finish off this publish message (started with beginPublish)
   // Returns 1 if the packet was sent successfully, 0 if there was an error
   int endPublish();
   // Write a single byte of payload (only to be used with beginPublish/endPublish)
   virtual size_t write(uint8_t);
   // Write size bytes from buffer into the payload (only to be used with beginPublish/endPublish)
   // Returns the number of bytes written
   virtual size_t write(const uint8_t *buffer, size_t size);
   boolean subscribe(const char* topic);
   boolean subscribe(const char* topic, uint8_t qos);
   boolean unsubscribe(const char* topic);
   boolean loop();
   boolean connected();
   int state();

};

#endif

#ifndef MQTT_H
#define MQTT_H

#include “MQTTClient.h”

#endif

#ifndef MQTT_CLIENT_H
#define MQTT_CLIENT_H

// include functional API if possible. remove min and max macros for some
// platforms as they will be defined again by Arduino later
#if defined(ESP8266) || (defined ESP32)
#include
#define MQTT_HAS_FUNCTIONAL 1
#elif defined(__has_include)
#if __has_include()
#if defined(min)
#undef min
#endif
#if defined(max)
#undef max
#endif
#include
#define MQTT_HAS_FUNCTIONAL 1
#else
#define MQTT_HAS_FUNCTIONAL 0
#endif
#else
#define MQTT_HAS_FUNCTIONAL 0
#endif

#include <Arduino.h>
#include <Client.h>
#include <Stream.h>

extern “C” {
#include “lwmqtt/lwmqtt.h”
}

typedef uint32_t (*MQTTClientClockSource)();

typedef struct {
uint32_t start;
uint32_t timeout;
MQTTClientClockSource millis;
} lwmqtt_arduino_timer_t;

typedef struct {
Client *client;
} lwmqtt_arduino_network_t;

class MQTTClient;

typedef void (*MQTTClientCallbackSimple)(String &topic, String &payload);
typedef void (*MQTTClientCallbackAdvanced)(MQTTClient *client, char topic, char bytes, int length);
#if MQTT_HAS_FUNCTIONAL
typedef std::function<void(String &topic, String &payload)> MQTTClientCallbackSimpleFunction;
typedef std::function<void(MQTTClient *client, char topic, char bytes, int length)>
MQTTClientCallbackAdvancedFunction;
#endif

typedef struct {
MQTTClient *client = nullptr;
MQTTClientCallbackSimple simple = nullptr;
MQTTClientCallbackAdvanced advanced = nullptr;
#if MQTT_HAS_FUNCTIONAL
MQTTClientCallbackSimpleFunction functionSimple = nullptr;
MQTTClientCallbackAdvancedFunction functionAdvanced = nullptr;
#endif
} MQTTClientCallback;

class MQTTClient {
private:
size_t readBufSize = 0;
size_t writeBufSize = 0;
uint8_t *readBuf = nullptr;
uint8_t *writeBuf = nullptr;

uint16_t keepAlive = 10;
bool cleanSession = true;
uint32_t timeout = 1000;
bool _sessionPresent = false;

Client *netClient = nullptr;
const char *hostname = nullptr;
IPAddress address;
int port = 0;
lwmqtt_will_t *will = nullptr;
MQTTClientCallback callback;

lwmqtt_arduino_network_t network = {nullptr};
lwmqtt_arduino_timer_t timer1 = {0, 0, nullptr};
lwmqtt_arduino_timer_t timer2 = {0, 0, nullptr};
lwmqtt_client_t client = lwmqtt_client_t();

bool _connected = false;
uint16_t nextDupPacketID = 0;
lwmqtt_return_code_t _returnCode = (lwmqtt_return_code_t)0;
lwmqtt_err_t _lastError = (lwmqtt_err_t)0;
uint32_t _droppedMessages = 0;

public:
void *ref = nullptr;

explicit MQTTClient(int bufSize = 128) : MQTTClient(bufSize, bufSize) {}
MQTTClient(int readSize, int writeBufSize);

~MQTTClient();

void begin(Client &_client);
void begin(const char _hostname, Client &_client) { this->begin(_hostname, 1883, _client); }
void begin(const char _hostname, int _port, Client &_client) {
this->begin(_client);
this->setHost(_hostname, _port);
}
void begin(IPAddress _address, Client &_client) { this->begin(_address, 1883, _client); }
void begin(IPAddress _address, int _port, Client &_client) {
this->begin(_client);
this->setHost(_address, _port);
}

void onMessage(MQTTClientCallbackSimple cb);
void onMessageAdvanced(MQTTClientCallbackAdvanced cb);
#if MQTT_HAS_FUNCTIONAL
void onMessage(MQTTClientCallbackSimpleFunction cb);
void onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb);
#endif

void setClockSource(MQTTClientClockSource cb);

void setHost(const char _hostname) { this->setHost(_hostname, 1883); }
void setHost(const char hostname, int port);
void setHost(IPAddress _address) { this->setHost(_address, 1883); }
void setHost(IPAddress _address, int port);

void setWill(const char topic) { this->setWill(topic, “”); }
void setWill(const char topic, const char payload) { this->setWill(topic, payload, false, 0); }
void setWill(const char topic, const char payload, bool retained, int qos);
void clearWill();

void setKeepAlive(int keepAlive);
void setCleanSession(bool cleanSession);
void setTimeout(int timeout);
void setOptions(int _keepAlive, bool _cleanSession, int _timeout) {
this->setKeepAlive(_keepAlive);
this->setCleanSession(_cleanSession);
this->setTimeout(_timeout);
}

void dropOverflow(bool enabled);
uint32_t droppedMessages() { return this->_droppedMessages; }

bool connect(const char clientId, bool skip = false) { return this->connect(clientId, nullptr, nullptr, skip); }
bool connect(const char clientId, const char username, bool skip = false) {
return this->connect(clientId, username, nullptr, skip);
}
bool connect(const char clientID, const char username, const char password, bool skip = false);

bool publish(const String &topic) { return this->publish(topic.c_str(), “”); }
bool publish(const char topic) { return this->publish(topic, “”); }
bool publish(const String &topic, const String &payload) { return this->publish(topic.c_str(), payload.c_str()); }
bool publish(const String &topic, const String &payload, bool retained, int qos) {
return this->publish(topic.c_str(), payload.c_str(), retained, qos);
}
bool publish(const char topic, const String &payload) { return this->publish(topic, payload.c_str()); }
bool publish(const char topic, const String &payload, bool retained, int qos) {
return this->publish(topic, payload.c_str(), retained, qos);
}
bool publish(const char topic, const char payload) {
return this->publish(topic, (char *)payload, (int)strlen(payload));
}
bool publish(const char topic, const char payload, bool retained, int qos) {
return this->publish(topic, (char *)payload, (int)strlen(payload), retained, qos);
}
bool publish(const char topic, const char payload, int length) {
return this->publish(topic, payload, length, false, 0);
}
bool publish(const char topic, const char payload, int length, bool retained, int qos);

uint16_t lastPacketID();
void prepareDuplicate(uint16_t packetID);

bool subscribe(const String &topic) { return this->subscribe(topic.c_str()); }
bool subscribe(const String &topic, int qos) { return this->subscribe(topic.c_str(), qos); }
bool subscribe(const char topic) { return this->subscribe(topic, 0); }
bool subscribe(const char topic, int qos);

bool unsubscribe(const String &topic) { return this->unsubscribe(topic.c_str()); }
bool unsubscribe(const char topic);

bool loop();
bool connected();
bool sessionPresent() { return this->_sessionPresent; }

lwmqtt_err_t lastError() { return this->_lastError; }
lwmqtt_return_code_t returnCode() { return this->_returnCode; }

bool disconnect();

private:
void close();
};

#endif

Ну я не сильно внимательно смотрел, поэтому мог просмотреть. Однако.
Для метода boolean connect(const char* id); нужны строковые данные.

Может быть ты не от той библиотеки скетч взял?

Возможно я ошибся

ПабСаб:
/*
PubSubClient.h - A simple client for MQTT.
Nicholas O’Leary
http://knolleary.net
*/

#ifndef PubSubClient_h
#define PubSubClient_h

#ifdef ESP8266
#include
#include <pgmspace.h>
#endif

#include <Arduino.h>

#include “MQTT.h”

//! Main do-everything class that sketches will use
class PubSubClient {
public:
#ifdef _GLIBCXX_FUNCTIONAL
typedef std::function<void(const MQTT::Publish&)> callback_t;
#else
typedef void(*callback_t)(const MQTT::Publish&);
#endif

private:
IPAddress server_ip;
String server_hostname;
uint16_t server_port;
callback_t _callback;

Client *_client;
uint16_t nextMsgId, keepalive;
uint8_t _max_retries;
unsigned long lastOutActivity;
unsigned long lastInActivity;
bool pingOutstanding;

//! Receive a message from the client
/*!
\return Pointer to message object, NULL if no message has been received
/
MQTT::Message
_recv_message(void);

//! Send a message and wait for its response message (if it has one)
/*!
\param msg The message to send
\param need_reply Do we wait for the reply message?
*/
bool _send_message(MQTT::Message& msg, bool need_reply = false);

//! Process incoming messages
/*!
- Calls the callback function when a PUBLISH message comes in
- Handles the handshake for PUBLISH when qos > 0
- Handles ping requests and responses
\param msg Message to process
/
void _process_message(MQTT::Message
msg);

//! Wait for a certain type of packet to come back, optionally check its packet id
/*!
Other packets are handed over to _process_message()
\param wait_type Message type to match on
\param wait_pid Message packet id to match on
\return True if we received the packet we wanted
*/
bool _wait_for(MQTT::message_type wait_type, uint16_t wait_pid = 0);

//! Return the next packet id
uint16_t _next_packet_id(void) {
nextMsgId++;
if (nextMsgId == 0) nextMsgId = 1;
return nextMsgId;
}

public:
//! Simple constructor
/*!
Use set_server() before connect()
*/
PubSubClient(Client& c);

//! Constructor with the server ip address
PubSubClient(Client& c, IPAddress &ip, uint16_t port = 1883);
//! Constructors with the host name
PubSubClient(Client& c, String hostname, uint16_t port = 1883);

//! Set the server ip address
PubSubClient& set_server(IPAddress &ip, uint16_t port = 1883);
//! Set the server host name
PubSubClient& set_server(String hostname, uint16_t port = 1883);

//! Get the callback function
callback_t callback(void) const { return _callback; }
//! Set the callback function
PubSubClient& set_callback(callback_t cb) { _callback = cb; return *this; }
//! Unset the callback function
PubSubClient& unset_callback(void) { _callback = NULL; return * this; }

//! Set the maximum number of retries when waiting for response packets
PubSubClient& set_max_retries(uint8_t mr) { _max_retries = mr; return *this; }

//! Connect to the server with a client id
/*!
\param id Client id for this device
*/
bool connect(String id);

//! Connect to the server with a client id and “will” parameters
/*!
The “will” is a message that is published when this client unexpectantly
disconnects from the broker i.e without sending a DISCONNECT message.
\param id Client id for this device
\param willTopic Topic of the “will” message
\param willQos QoS level of the “will” message
\param willRetain Retain setting of the “will” message
\param willMessage Content (payload) of the “will” message
*/
bool connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage);

//! Disconnect from the server
void disconnect(void);

//! Publish a string payload
/*!
\param topic Topic of the message
\param payload String text of the message
*/
bool publish(String topic, String payload);

//! Publish an arbitrary data payload
/*!
\param topic Topic of the message
\param payload Pointer to contents of the message
\param plength Length of the message (pointed to by payload) in bytes
\param retained If true, this message will be stored on the server and
supplied to any future subscribers whose subscriptions match its topic
name.
*/
bool publish(String topic, const uint8_t *payload, uint32_t plength, bool retained = false);

//! Publish an arbitrary data payload from a callback
/*!
\param topic Topic of this message
\param pcb A callback function that writes the payload directly to the network Client object
\param length The length of the data that ‘pcb’ will send
*/
bool publish(String topic, MQTT::payload_callback_t pcb, uint32_t length, bool retained = false);

//! Publish an arbitrary data payload stored in “program” memory
/*!
\param topic Topic of the message
\param payload Pointer to contents of the message, stored in “program” memory
\param plength Length of the message (pointed to by payload) in bytes
\param retained If true, this message will be stored on the server and
supplied to any future subscribers whose subscriptions match its topic
name.
*/
bool publish_P(String topic, PGM_P payload, uint32_t plength, bool retained = false);

//! Subscribe to a topic
/*!
\param topic Topic filter
\param qos QoS value. 0 => no handshake, 1 => single handshake, 2 => two-way handshake
*/
bool subscribe(String topic, uint8_t qos = 0);

//! Unsubscribe from a topic
bool unsubscribe(String topic);

//! Wait for packets to come in, processing them
/*!
Also periodically pings the server
*/
bool loop();

//! Are we connected?
bool connected();

//! Connect with a pre-constructed MQTT message object
bool connect(MQTT::Connect &conn);
//! Publish with a pre-constructed MQTT message object
bool publish(MQTT::Publish &pub);
//! Subscribe with a pre-constructed MQTT message object
bool subscribe(MQTT::Subscribe &sub);
//! Unsubscribe with a pre-constructed MQTT message object
bool unsubscribe(MQTT::Unsubscribe &unsub);
};

#endif

теперь ошибки такие:
C:\Users\3ЛТП\Documents\Arduino\MP_V01_copy_20241218094852_copy_20241218195939\MP_V01_copy_20241218094852_copy_20241218195939.ino:14:14: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
c:\Users\3���\Documents\Arduino\libraries\PubSubClient\src\MQTT.cpp: In member function ‘virtual MQTT::message_type MQTT::Publish::response_type() const’:
c:\Users\3���\Documents\Arduino\libraries\PubSubClient\src\MQTT.cpp:474:3: error: control reaches end of non-void function [-Werror=return-type]
474 | }
| ^
cc1plus.exe: some warnings being treated as errors

exit status 1

Compilation error: exit status 1

Вставь код по правильному, как строки считать предлагаешь?

Сорян, тороплюсь

/*
PubSubClient.h - A simple client for MQTT.
Nicholas O’Leary
http://knolleary.net
*/

#ifndef PubSubClient_h
#define PubSubClient_h

#ifdef ESP8266
#include
#include <pgmspace.h>
#endif

#include <Arduino.h>

#include “MQTT.h”

//! Main do-everything class that sketches will use
class PubSubClient {
public:
#ifdef _GLIBCXX_FUNCTIONAL
typedef std::function<void(const MQTT::Publish&)> callback_t;
#else
typedef void(*callback_t)(const MQTT::Publish&);
#endif

private:
IPAddress server_ip;
String server_hostname;
uint16_t server_port;
callback_t _callback;

Client *_client;
uint16_t nextMsgId, keepalive;
uint8_t _max_retries;
unsigned long lastOutActivity;
unsigned long lastInActivity;
bool pingOutstanding;

//! Receive a message from the client
/*!
\return Pointer to message object, NULL if no message has been received
/
MQTT::Message _recv_message(void);

//! Send a message and wait for its response message (if it has one)
/*!
\param msg The message to send
\param need_reply Do we wait for the reply message?
*/
bool _send_message(MQTT::Message& msg, bool need_reply = false);

//! Process incoming messages
/*!
- Calls the callback function when a PUBLISH message comes in
- Handles the handshake for PUBLISH when qos > 0
- Handles ping requests and responses
\param msg Message to process
/
void _process_message(MQTT::Message msg);

//! Wait for a certain type of packet to come back, optionally check its packet id
/*!
Other packets are handed over to _process_message()
\param wait_type Message type to match on
\param wait_pid Message packet id to match on
\return True if we received the packet we wanted
*/
bool _wait_for(MQTT::message_type wait_type, uint16_t wait_pid = 0);

//! Return the next packet id
uint16_t _next_packet_id(void) {
nextMsgId++;
if (nextMsgId == 0) nextMsgId = 1;
return nextMsgId;
}

public:
//! Simple constructor
/*!
Use set_server() before connect()
*/
PubSubClient(Client& c);

//! Constructor with the server ip address
PubSubClient(Client& c, IPAddress &ip, uint16_t port = 1883);
//! Constructors with the host name
PubSubClient(Client& c, String hostname, uint16_t port = 1883);

//! Set the server ip address
PubSubClient& set_server(IPAddress &ip, uint16_t port = 1883);
//! Set the server host name
PubSubClient& set_server(String hostname, uint16_t port = 1883);

//! Get the callback function
callback_t callback(void) const { return _callback; }
//! Set the callback function
PubSubClient& set_callback(callback_t cb) { _callback = cb; return *this; }
//! Unset the callback function
PubSubClient& unset_callback(void) { _callback = NULL; return * this; }

//! Set the maximum number of retries when waiting for response packets
PubSubClient& set_max_retries(uint8_t mr) { _max_retries = mr; return *this; }

//! Connect to the server with a client id
/*!
\param id Client id for this device
*/
bool connect(String id);

//! Connect to the server with a client id and “will” parameters
/*!
The “will” is a message that is published when this client unexpectantly
disconnects from the broker i.e without sending a DISCONNECT message.
\param id Client id for this device
\param willTopic Topic of the “will” message
\param willQos QoS level of the “will” message
\param willRetain Retain setting of the “will” message
\param willMessage Content (payload) of the “will” message
*/
bool connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage);

//! Disconnect from the server
void disconnect(void);

//! Publish a string payload
/*!
\param topic Topic of the message
\param payload String text of the message
*/
bool publish(String topic, String payload);

//! Publish an arbitrary data payload
/*!
\param topic Topic of the message
\param payload Pointer to contents of the message
\param plength Length of the message (pointed to by payload) in bytes
\param retained If true, this message will be stored on the server and
supplied to any future subscribers whose subscriptions match its topic
name.
*/
bool publish(String topic, const uint8_t *payload, uint32_t plength, bool retained = false);

//! Publish an arbitrary data payload from a callback
/*!
\param topic Topic of this message
\param pcb A callback function that writes the payload directly to the network Client object
\param length The length of the data that ‘pcb’ will send
*/
bool publish(String topic, MQTT::payload_callback_t pcb, uint32_t length, bool retained = false);

//! Publish an arbitrary data payload stored in “program” memory
/*!
\param topic Topic of the message
\param payload Pointer to contents of the message, stored in “program” memory
\param plength Length of the message (pointed to by payload) in bytes
\param retained If true, this message will be stored on the server and
supplied to any future subscribers whose subscriptions match its topic
name.
*/
bool publish_P(String topic, PGM_P payload, uint32_t plength, bool retained = false);

//! Subscribe to a topic
/*!
\param topic Topic filter
\param qos QoS value. 0 => no handshake, 1 => single handshake, 2 => two-way handshake
*/
bool subscribe(String topic, uint8_t qos = 0);

//! Unsubscribe from a topic
bool unsubscribe(String topic);

//! Wait for packets to come in, processing them
/*!
Also periodically pings the server
*/
bool loop();

//! Are we connected?
bool connected();

//! Connect with a pre-constructed MQTT message object
bool connect(MQTT::Connect &conn);
//! Publish with a pre-constructed MQTT message object
bool publish(MQTT::Publish &pub);
//! Subscribe with a pre-constructed MQTT message object
bool subscribe(MQTT::Subscribe &sub);
//! Unsubscribe with a pre-constructed MQTT message object
bool unsubscribe(MQTT::Unsubscribe &unsub);
};

#endif

А есть какая-то возможность в файлах библиотеки посмотреть её версию?

Так посмотри, если вверху что-то написано - расскажи.

Ну мне с планшета не удобно, может быть кто с компьютера еще посмотрит. Но куда не плюнь - нужно смотреть исходники библиотек. Откуда ты их брал?

скачал архив. В нем библиотеки и скетч. Из него удалил всё что касается сервы и термодатчика, а также получение данных из MQTT, т.к. они мне не нужны.
Про версию я может не так выразился. Я вот скинул библиотеку, но в ней не вижу намёка на указание версии. Так понимаю, какая версия можно увидеть только в IDE в разделе библиотеки.

Самый простой способ - в папке с библиотекой должен быть файлик library.properties, а в нем параметр version

name=Ds1302
version=1.1.0
.............................

Если автор не забил на этот файл, то версия в нем будет соответствовать реальной

не слишком ли борзо для человека, который второй день программирует?

Я бы посоветовал вернуться к оригинальному коду, и попробовать собрать проект, НИЧЕГО НЕ УДАЛЯЯ. Если соберется - значит все библиотеки правильных версий

Ну, я туп в программировании, но не настолько чтоб не видеть явного. Код не большой, подключение сервы и темп датчика, отправка /принятие подписок вполне видны.
За совет спасибо. Попробую.

Исходный код (как я думаю, оставил только подключение к wi-fi и MQTT)^

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
//#include <DallasTemperature.h>
//#include "BMP280.h"
#include "Wire.h"
//#include <Servo.h>

//Servo myservo;
//BMP280 bmp;

//#define GREEN_LED 16
//#define Blue_LED 14

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
//DallasTemperature sensors(&oneWire);

const char *ssid = "DIR-615";    // Имя вайфай точки доступа
const char *pass = "forfrends";  // Пароль от точки доступа

const char *mqtt_server = "m21.cloudmqtt.com";  // Имя сервера MQTT
const int mqtt_port = 10646;                    // Порт для подключения к серверу MQTT
const char *mqtt_user = "euqacrkv";             // Логин от сервер
const char *mqtt_pass = "smRc4-c4luFs";         // Пароль от сервера

#define BUFFER_SIZE 100

////bool LedState = false;
//int tm=300;
//float temp=0;



//void callback(const MQTT::Publish& pub)     // Функция получения данных от сервера
//{
//    Serial.print(pub.topic());                // выводим в сериал порт название топика
//    Serial.print(" => ");
//    Serial.println(pub.payload_string());     // выводим в сериал порт значение полученных данных

//    String payload = pub.payload_string();

//    if(String(pub.topic()) == "test/Gled")    //  проверяем из нужного ли нам топика пришли данные
//    {
//        int stledG = payload.toInt();         //  преобразуем полученные данные в тип integer
//        digitalWrite(GREEN_LED, stledG);       //  включаем или выключаем светодиод в зависимоти от полученных значений данных
//    }

//    if(String(pub.topic()) == "test/Bled")    //  проверяем из нужного ли нам топика пришли данные
//    {
//        int stledB = payload.toInt();         //  преобразуем полученные данные в тип integer
//        digitalWrite(Blue_LED, stledB);        //  включаем или выключаем светодиод в зависимоти от полученных значений данных
//    }

//    if(String(pub.topic()) == "test/Servo")   // проверяем из нужного ли нам топика пришли данные
//    {
//        int pos = payload.toInt();            //  преобразуем полученные данные в тип integer
//        myservo.write(pos);                   //  поворачиваем сервопривод
//    }
//}



WiFiClient wclient;
PubSubClient client(wclient, mqtt_server, mqtt_port);

//void setup() {
//    Serial.begin(115200);
//    delay(10);

//    if(!bmp.begin(4,5)){
//        Serial.println("BMP init failed!");
//        while(1);
//    }else Serial.println("BMP init success!");
//    bmp.setOversampling(4);

//    myservo.attach(0);
//    sensors.begin();

//    Serial.println();
//    Serial.println();
//    pinMode(GREEN_LED, OUTPUT);
//    pinMode(Blue_LED, OUTPUT);
//}

void loop() {
  // подключаемся к wi-fi
  if (WiFi.status() != WL_CONNECTED) {
    Serial.print("Connecting to ");
    Serial.print(ssid);
    Serial.println("...");
    WiFi.begin(ssid, pass);

    if (WiFi.waitForConnectResult() != WL_CONNECTED)
      return;
    Serial.println("WiFi connected");
  }

  // подключаемся к MQTT серверу
  if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
      Serial.println("Connecting to MQTT server");
      if (client.connect(MQTT::Connect("arduinoClient2")
                           .set_auth(mqtt_user, mqtt_pass))) {
        Serial.println("Connected to MQTT server");
        //                client.set_callback(callback);
        client.subscribe("test/Gled");   // подписывааемся по топик с данными для светодиода
        client.subscribe("test/Bled");   // подписывааемся по топик с данными для светодиода
        client.subscribe("test/Servo");  // подписывааемся по топик с данными для Сервопривода
      } else {
        Serial.println("Could not connect to MQTT server");
      }
    }

    if (client.connected()) {
      client.loop();
      //            TempSend();
    }
  }
}  // конец основного цикла


// Функция отправки показаний с термодатчика
//void TempSend(){
//    if (tm==0)
//    {
//        sensors.requestTemperatures();   // от датчика получаем значение температуры
//        float temp = sensors.getTempCByIndex(0);
//        client.publish("test/temp", String(temp)); // отправляем в топик для термодатчика значение температуры
//Serial.println(temp);
//        Serial.print("T = \t");Serial.print(temp,2); Serial.println(" C\t");

//        double T,Pressure;
//        char result = bmp.startMeasurment();
//        if(result != 0){
//            delay(result);
//            result = bmp.getTemperatureAndPressure(T,Pressure);
//            if(result!=0)
//            {
//                Serial.print("P = \t");Serial.print(Pressure,2); Serial.println(" mBar\t");
//            }
//            else {
//                Serial.println("Error.");
//            }
//        }
//        else {
//            Serial.println("Error.");
//        }
//        client.publish("test/pressure", String(Pressure));

//        tm = 1000;  // пауза меду отправками значений температуры  коло 3 секунд
//    }
//    tm--;
//    delay(10);
//}

Всё одно ошибка на библиотеку и на 474 строку в ней, на скобку:

c:\Users\3���\Documents\Arduino\libraries\PubSubClient\src\MQTT.cpp: In member function ‘virtual MQTT::message_type MQTT::Publish::response_type() const’:
c:\Users\3���\Documents\Arduino\libraries\PubSubClient\src\MQTT.cpp:474:3: error: control reaches end of non-void function [-Werror=return-type]
474 | }
| ^
cc1plus.exe: some warnings being treated as errors

exit status 1

Compilation error: exit status 1

Вроде оператор этот на месте…

Может есть у кого рабочий пример с MQTT и нормальной библиотекой? :sneezing_face: