Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <BME280.h>
- #include <WiFi.h>
- #include <PubSubClient.h>
- const char* ssid = "NOME_RETE_WIFI"; // Sostituire con il nome della tua rete WiFi
- const char* password = "PASSWORD_RETE_WIFI"; // Sostituire con la password della tua rete WiFi
- const char* botToken = "BOT_TOKEN"; // Sostituire con il token del tuo bot Telegram
- const char* chatId = "ID_CHAT"; // Sostituire con l'ID della chat Telegram a cui inviare i dati
- WiFiClient espClient;
- PubSubClient client(espClient);
- BME280 sensor;
- void setup() {
- Serial.begin(115200);
- sensor.begin(0x76);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected!");
- client.setServer("mqqt.telegram.org", 1883);
- client.setCallback(callback);
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- float temperature = sensor.readTemperatureC();
- float humidity = sensor.readHumidity();
- float pressure = sensor.readPressurePa();
- String message = "Temperatura: " + String(temperature) + "°C\n" +
- "Umidità: " + String(humidity) + "%RH\n" +
- "Pressione: " + String(pressure) + "hPa";
- client.publish(chatId, message.c_str());
- delay(10000); // Inviare i dati ogni 10 secondi
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived on topic: ");
- Serial.print(topic);
- Serial.print(". Message: ");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- }
- void reconnect() {
- // Loop until we connect
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Create a random client ID
- String clientId = "ESP8266Client-";
- clientId += String(random(0xFFFFFF));
- if (client.connect(clientId.c_str())) {
- Serial.println("connected");
- // Once connected, subscribe to our topic
- client.subscribe(chatId);
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement