Advertisement
webtronico

Arduino - Stazione Meteo e Dati su Telegram

May 19th, 2024 (edited)
719
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.16 KB | Software | 0 0
  1. #include <BME280.h>
  2. #include <WiFi.h>
  3. #include <PubSubClient.h>
  4.  
  5. const char* ssid = "NOME_RETE_WIFI"; // Sostituire con il nome della tua rete WiFi
  6. const char* password = "PASSWORD_RETE_WIFI"; // Sostituire con la password della tua rete WiFi
  7. const char* botToken = "BOT_TOKEN"; // Sostituire con il token del tuo bot Telegram
  8. const char* chatId = "ID_CHAT"; // Sostituire con l'ID della chat Telegram a cui inviare i dati
  9.  
  10. WiFiClient espClient;
  11. PubSubClient client(espClient);
  12.  
  13. BME280 sensor;
  14.  
  15. void setup() {
  16.   Serial.begin(115200);
  17.  
  18.   sensor.begin(0x76);
  19.  
  20.   WiFi.begin(ssid, password);
  21.   while (WiFi.status() != WL_CONNECTED) {
  22.     delay(500);
  23.     Serial.print(".");
  24.   }
  25.   Serial.println("");
  26.   Serial.println("WiFi connected!");
  27.  
  28.   client.setServer("mqqt.telegram.org", 1883);
  29.   client.setCallback(callback);
  30. }
  31.  
  32. void loop() {
  33.   if (!client.connected()) {
  34.     reconnect();
  35.   }
  36.  
  37.   float temperature = sensor.readTemperatureC();
  38.   float humidity = sensor.readHumidity();
  39.   float pressure = sensor.readPressurePa();
  40.  
  41.   String message = "Temperatura: " + String(temperature) + "°C\n" +
  42.                 "Umidità: " + String(humidity) + "%RH\n" +
  43.                 "Pressione: " + String(pressure) + "hPa";
  44.  
  45.   client.publish(chatId, message.c_str());
  46.  
  47.   delay(10000); // Inviare i dati ogni 10 secondi
  48. }
  49.  
  50. void callback(char* topic, byte* payload, unsigned int length) {
  51.   Serial.print("Message arrived on topic: ");
  52.   Serial.print(topic);
  53.   Serial.print(". Message: ");
  54.   for (int i = 0; i < length; i++) {
  55.     Serial.print((char)payload[i]);
  56.   }
  57.   Serial.println();
  58. }
  59.  
  60. void reconnect() {
  61.   // Loop until we connect
  62.   while (!client.connected()) {
  63.     Serial.print("Attempting MQTT connection...");
  64.     // Create a random client ID
  65.     String clientId = "ESP8266Client-";
  66.     clientId += String(random(0xFFFFFF));
  67.  
  68.     if (client.connect(clientId.c_str())) {
  69.       Serial.println("connected");
  70.       // Once connected, subscribe to our topic
  71.       client.subscribe(chatId);
  72.     } else {
  73.       Serial.print("failed, rc=");
  74.       Serial.print(client.state());
  75.       Serial.println(" try again in 5 seconds");
  76.       delay(5000);
  77.     }
  78.   }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement