Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <DHT.h>
- #include <PubSubClient.h>
- #define DHTTYPE DHT11
- #define DHTPIN 2
- #define GASPIN A0
- #define BUZZERPIN 3
- #define mqtt_server "broker.mqttdashboard.com"
- #define mqtt_user "karlo"
- #define mqtt_password "123456789"
- #define humidity_topic "sensor/humidity"
- #define temperature_topic "sensor/temperature"
- const char* ssid = "HUAWEI_P9lite_A4A2";
- const char* password = "123456789";
- float humidity, temp_f;
- int smokeLevel;
- unsigned long previousMillis = 0;
- const long interval = 2000;
- const int smoke = 500;
- DHT dht(DHTPIN, DHTTYPE, 11);
- WiFiClient espClient;
- PubSubClient mqtt_client(espClient);
- void setup() {
- Serial.begin(115200);
- dht.begin();
- setup_wifi();
- mqtt_client.setServer(mqtt_server, 1883);
- pinMode(GASPIN, INPUT);
- pinMode(BUZZERPIN, OUTPUT);
- }
- void loop() {
- if (!mqtt_client.connected()) {
- reconnect();
- }
- mqtt_client.loop();
- getTemperature();
- mqtt_client.publish(temperature_topic, String(temp_f).c_str(), true);
- mqtt_client.publish(humidity_topic, String(humidity).c_str(),true);
- }
- void readGasLevel(){
- smokeLevel = analogRead(GASPIN);
- Serial.print("Pin A0: ");
- Serial.println(smokeLevel);
- if(smokeLevel > smoke){
- }
- }
- void getTemperature() {
- unsigned long currentMillis = millis();
- if(currentMillis - previousMillis >= interval) {
- // save the last time you read the sensor
- previousMillis = currentMillis;
- humidity = dht.readHumidity(); // Read humidity (percent)
- temp_f = dht.readTemperature(false); // Read temperature as Fahrenheit
- if (isnan(humidity) || isnan(temp_f)) {
- Serial.println("Failed to read from DHT sensor!");
- return;
- }
- }
- }
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!mqtt_client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- // If you do not want to use a username and password, change next line to
- if (mqtt_client.connect("clientId-jXYJCabq7T")) {
- //if (mqtt_client.connect("clientId-eVYR0oBFnB", mqtt_user, mqtt_password)) {
- Serial.println("connected");
- } else {
- Serial.print("failed, rc=");
- Serial.print(mqtt_client.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment