Quantcast
Channel: Arduino Forum - Latest topics
Viewing all articles
Browse latest Browse all 15971

Making IoT with ESP32 to control lamps brightness

$
0
0

I would greatly apreciate some help.

I have a school assignment/project. It needs me to make an IoT project using 2 ESP32.
here's the case:

-Control 8 lamps (connected with the first ESP32), each lamp is controlled by a push button (a total of 8 push buttons on second ESP32).

-If button 1 is pressed once then lamp 1 lights up at 50% brightness, if the button is
pressed again then the light turns on 100%. When the button is pressed for the 3rd time the light turns off. This applies the same to other lights.

-The two ESP32 devices communicate with each other using MQTT (laptop as MQTT
broker), the first ESP32 as subscriber, the second ESP32 as publisher. Will be better
if you use JSON format.

-Illustrate in schematic and Arduino programming code (publisher and subscriber).

I've made the code but I'm still looking for a way to stimulate it since i don't have the hardware.

Anyway, here's the programming code that I made, please kindly revise it.

First ESP32 (Subscriber) :

#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

const char* ssid = "SSID";
const char* password = "Password";
const char* mqtt_server = "Laptop IP Address"; // IP laptop as MQTT broker
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

const int NUM_LAMPS = 8;
int lampBrightness[NUM_LAMPS];

// Pin for the lamps
const int lampPins[NUM_LAMPS] = {2, 3, 4, 5, 6, 7, 8, 9};

void setup_wifi() {
  delay(10);
  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 callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");

  // Parsing pesan JSON
  StaticJsonDocument<200> doc;
  DeserializationError error = deserializeJson(doc, message, length);
  if (error) {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return;
  }
  
  int lamp_number = doc["lamp_number"];
  int brightness = doc["brightness"];
  lampBrightness[lamp_number - 1] = brightness;

  // Atur kecerahan lampu
  analogWrite(lampPins[lamp_number - 1], brightness * 2.55); // convert (0-100) to (0-255)
  
  Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32_Subscriber")) {
      Serial.println("connected");
      for (int i = 0; i < NUM_LAMPS; i++) {
        client.subscribe(("lamp/" + String(i + 1)).c_str());
      }
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  
  // Setup pin for lamps
  for (int i = 0; i < NUM_LAMPS; i++) {
    pinMode(lampPins[i], OUTPUT);
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

Second ESP32 (Publisher):

#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

const char* ssid = "SSID";
const char* password = "Password";
const char* mqtt_server = "Laptop IP Address"; // IP laptop as MQTT broker
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

#define NUM_BUTTONS 8
#define BUTTON_PINS {10, 11, 12, 13, 14, 15, 16, 17} // Pin for buttons

int buttonPins[NUM_BUTTONS] = BUTTON_PINS;
bool lastButtonStates[NUM_BUTTONS];
int lampBrightness[NUM_BUTTONS];

void setup_wifi() {
  delay(10);
  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 setup_mqtt() {
  client.setServer(mqtt_server, mqtt_port);
}

void setup_buttons() {
  for (int i = 0; i < NUM_BUTTONS; i++) {
    pinMode(buttonPins[i], INPUT);
    lastButtonStates[i] = LOW;
  }
}

void publish_message(int lamp_number, int brightness) {

  StaticJsonDocument<200> doc;
  doc["lamp_number"] = lamp_number;
  doc["brightness"] = brightness;

  // convert object JSON as string
  char messageBuffer[512];
  serializeJson(doc, messageBuffer);

  // send messages to broker MQTT
  client.publish(("lamp/" + String(lamp_number)).c_str(), messageBuffer);
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  setup_mqtt();
  setup_buttons();
}

void loop() {
  if (!client.connected()) {
    setup_mqtt();
  }

  for (int i = 0; i < NUM_BUTTONS; i++) {
    int buttonState = digitalRead(buttonPins[i]);
    if (buttonState != lastButtonStates[i]) {
      if (buttonState == HIGH) {
        // Tombol ditekan
        lampBrightness[i] += 50;
        if (lampBrightness[i] > 100) {
          lampBrightness[i] = 0;
        }
        publish_message(i + 1, lampBrightness[i]);
      }
      lastButtonStates[i] = buttonState;
      delay(50); // Debouncing
    }
  }
}

2 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 15971

Latest Images

Trending Articles



Latest Images