uwezi

20230114_pehr_01.cpp

Jan 14th, 2023
1,343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <SPI.h>
  4. #include <WiFiClient.h>
  5. #include <PubSubClient.h>
  6. #include <MAX6675.h>
  7.  
  8. // WiFi settings
  9. const char* ssid = "";
  10. const char* password = "";
  11.  
  12. // MQTT settings
  13. const char* mqttServer = "192.168.1.15";
  14. const int mqttPort = 1883;
  15. const char* mqttUser = "";
  16. const char* mqttPassword = "";
  17.  
  18. // MAX6675 settings
  19. int thermoDO = D6;
  20. int thermoCS = D7;
  21. int thermoCLK = D8;
  22. MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
  23.  
  24. // MQTT client
  25. WiFiClient wifiClient;
  26. PubSubClient client(wifiClient);
  27.  
  28. // Variables to keep track of temperature readings
  29. unsigned long previousMillis = 0;       // will store last time temperature was read
  30. const long interval = 10000;           // interval at which to read temperature (milliseconds)
  31.  
  32. unsigned int avgSamples = 4;           // take a running average over n values
  33. double avgTemperature;
  34.  
  35. void setup() {
  36.   // Start WiFi and connect to network
  37.   WiFi.begin(ssid, password);
  38.   while (WiFi.status() != WL_CONNECTED) {
  39.     delay(1000);
  40.     Serial.println("Connecting to WiFi...");
  41.   }
  42.   Serial.println("Connected to WiFi");
  43.  
  44.   // Start MQTT client
  45.   client.setServer(mqttServer, mqttPort);
  46.   client.connect("Arduino MAX6675");
  47.  
  48.   avgTemperature = thermocouple.readCelsius();
  49. }
  50.  
  51. void loop() {
  52.   // Read temperature from MAX6675 and update total temperature
  53.   unsigned long currentMillis = millis();
  54.   if (currentMillis - previousMillis >= interval) {
  55.     // save the last time temperature was read
  56.     previousMillis = currentMillis;
  57.  
  58.     // read temperature
  59.     double temperature = thermocouple.readCelsius();
  60.     avgTemperature = ((avgSamples-1)*avgTemperature + temperature)/avgSamples;
  61.  
  62.     // calculate and publish average temperature
  63.     client.publish("temperature", String(avgTemperature).c_str());
  64.   }
  65.  
  66.   // Keep MQTT connection alive
  67.   client.loop();
  68. }
Advertisement
Add Comment
Please, Sign In to add comment