ESP32-Controlled RFT Indicator Lights Not Updating Correctly – Need Help with Code & Hardware!

Hi everyone,

Requirement:
In my bags manufacturing company, over each sewing Line, RFT (Right First Time) lights are installed for visual management of hourly RFT values (Hourly Actual Output in comparison with Target Output).

Right now, workers manually Turn ON/OFF lights with respect to RFT values.

Red Light will be turned ON, when RFT value is below 90.
Yellow Light will be turned ON, when RFT value is from 91 to 95.
Green Light will be turned ON, when RFT value is above 95.
The blue bulb is for Changeover indication. QCOC (Quick Changeover Crew)
If QCOC =1 , Blue Bulb ON , If QCOC=0, Blue Bulb OFF

IT department has designed a web portal, in which data of RFT values is stored on hourly basis and is displayed on screens over each line. I want to link RFT lights (red, yellow, green, blue) with that web portal so that lights should automatically turn ON and OFF as per RFT values.
For this: I'm working on 220V AC operated RFT quality Lights (Red, Yellow, Green, Blue) with ESP 32 Wroom 32d, 5V adapter to power ESP 32 and pair of 2 channel 5V relays each connected with lights.



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

// Define relay pins
const int relay1 = 5; // Pin connected to IN1 of Relay 1 (Green Bulb)
const int relay2 = 18; // Pin connected to IN2 of Relay 2 (Yellow Bulb)
const int relay3 = 19; // Pin connected to IN3 of Relay 3 (Red Bulb)
const int relay4 = 17; // Pin connected to IN3 of Relay 3 (Red Bulb)
const int wifiLED = 2; // Pin connected to Wi-Fi status LED

// Wi-Fi credentials
const char* ssid = "USERNAME";
const char* password = "PASSWORD";

// Other declarations
StaticJsonDocument<200> doc;
String host_or_IPv4 = "http://125.209.66.227:60002/";
String Destination = "";
String URL_Server = "";
String getData = "";
String payloadGet = "";
HTTPClient http;
WiFiClient client;

// Setup
void setup() {
  Serial.begin(115200);

  // Initialize Wi-Fi LED pin as output
  pinMode(wifiLED, OUTPUT);

  // Set relay pins as outputs
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

  // Initialize relays and Wi-Fi LED to OFF state
  digitalWrite(relay1, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  digitalWrite(wifiLED, LOW);

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    // Turn Wi-Fi LED ON upon successful connection
  digitalWrite(wifiLED, HIGH);
  }
  Serial.println("");
  Serial.print("Successfully connected to : ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Main loop
void loop() {
  // Check Wi-Fi status and update Wi-Fi LED
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(wifiLED, HIGH);
  } else {
    digitalWrite(wifiLED, LOW);
  }

  // Existing code logic remains unchanged
  int id = 0; //--> ID in Database 
  getData = "ID=" + String(id);
  Destination = "api/Production/GetRetriveRFT?LineNumber=1&type=json";
  URL_Server = host_or_IPv4 + Destination;
  Serial.println("----------------Connect to Server-----------------");
  Serial.println("Get LED Status from Server or Database");
  Serial.print("Request Link : ");
  Serial.println(URL_Server);
  http.begin(client, URL_Server); //--> Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
  int httpCodeGet = http.GET(); //--> Send the request
  payloadGet = http.getString(); //--> Get the response payload from server
  Serial.println(payloadGet); //--> Print request response payload
  Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
  Serial.println(httpCodeGet); //--> Print HTTP return code
  Serial.print("Returned data from Server : ");
  Serial.println(payloadGet); //--> Print request response payload
  DeserializationError error = deserializeJson(doc, payloadGet);
  double RFT = doc["DefectPercentage"];
  double QCOC = doc["QCOC"];
  Serial.println(RFT); 
  Serial.println(QCOC); 

  if (RFT > 0) {
    double inputValue = RFT; // Read input value from serial monitor

    // Turn off all bulbs first
    digitalWrite(relay1, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);

    Serial.println(RFT);  
  if (RFT < 95) {
    digitalWrite(relay3, LOW);
    Serial.println("Red Bulb ON");
  }
  else if(RFT >= 95 && RFT < 97){
    digitalWrite(relay2, LOW);
    Serial.println("Yellow Bulb ON");
  }
  else if (RFT >= 97) {
    digitalWrite(relay1, LOW); // Relay LOW means ON
    Serial.println("Green Bulb ON");
  }

  if (QCOC = 1) {
    digitalWrite(relay1, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);
    digitalWrite(relay4, LOW);
    Serial.println("Blue Bulb ON");
  }
  else
  {
    digitalWrite(relay4, HIGH);
    Serial.println("Blue Bulb OFF");
  }

    Serial.println("----------------Closing Connection----------------");
  http.end(); //--> Close connection
  Serial.println();
  Serial.println("Please wait 10 seconds for the next connection.");
  Serial.println();
  }
}

Problem:
The problem that I'm facing is: lights don't turn ON and OFF as per changing RFT values. For example: If RFT value is 90, Red will turn ON and if RFT value changed to 98, Red bulb stays ON, Same happens with other bulbs. There is no accuracy in implementation. I don't know where's the problem. Am I missing something in hardware or programming.

That's a problem.

what change should I make in it.

Seriously?

Try turning your warning level up to ALL and recompiling if you can't see it.

Ok, Let me try it.

Maybe your 5V adapter cannot provide enough current to power the ESP and energise all 4 relays at the same time

Have you written some simple code to show that you have full control over the lights, without any of the other code?

Tom.... :smiley: :+1: :coffee: :australia:

@van_der_decken I have tried it by updating code:

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

// Define relay pins
const int relay1 = 17; // Pin connected to IN1 of Relay 1 (Red Bulb)
const int relay2 = 25; // Pin connected to IN2 of Relay 2 (Yellow Bulb)
const int relay3 = 19; // Pin connected to IN3 of Relay 3 (Green Bulb)
const int relay4 = 14; // Pin connected to IN4 of Relay 4 (Blue Bulb)
const int wifiLED = 2; // Pin connected to Wi-Fi status LED

// Wi-Fi credentials
const char* ssid = "Manzar";
const char* password = "kirmani110";

// API and server settings
const String host_or_IPv4 = "http://125.209.66.227:60002/";
const unsigned long REQUEST_INTERVAL = 10000; // 10 seconds between requests
unsigned long lastRequestTime = 0;

// Track previous states to avoid unnecessary relay switching
double lastRFT = -1;
int lastQCOC = -1;

// Other declarations
JsonDocument doc; // Updated from deprecated StaticJsonDocument
String Destination = "";
String URL_Server = "";
String payloadGet = "";
HTTPClient http;
WiFiClient client;

// Setup
void setup() {
  Serial.begin(115200);
  Serial.println("\nRFT Light Control System Starting...");

  // Initialize Wi-Fi LED pin as output
  pinMode(wifiLED, OUTPUT);

  // Set relay pins as outputs
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

  // Initialize relays to OFF state (HIGH = OFF for relay modules)
  digitalWrite(relay1, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  
  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  
  int connectionAttempts = 0;
  while (WiFi.status() != WL_CONNECTED && connectionAttempts < 20) {
    delay(500);
    Serial.print(".");
    connectionAttempts++;
  }
  
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.print("Successfully connected to: ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    digitalWrite(wifiLED, HIGH);
  } else {
    Serial.println("");
    Serial.println("Failed to connect to WiFi. Will retry in the main loop.");
  }
}

// Main loop
void loop() {
  // Update WiFi status LED
  digitalWrite(wifiLED, WiFi.status() == WL_CONNECTED ? HIGH : LOW);
  
  // If WiFi is disconnected, attempt to reconnect
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi disconnected. Attempting to reconnect...");
    WiFi.reconnect();
    delay(5000); // Wait 5 seconds before continuing
    return;
  }
  
  // Only make requests at the specified interval
  unsigned long currentMillis = millis();
  if (currentMillis - lastRequestTime >= REQUEST_INTERVAL) {
    lastRequestTime = currentMillis;
    
    // Prepare API request
    Destination = "api/Production/GetRetriveRFT?LineNumber=1&type=json";
    URL_Server = host_or_IPv4 + Destination;
    
    Serial.println("\n----------------Connect to Server-----------------");
    Serial.println("Getting RFT data from server");
    
    // Send HTTP request
    http.begin(client, URL_Server);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    int httpCode = http.GET();
    
    // Check response code
    if (httpCode > 0) {
      Serial.print("Response Code: ");
      Serial.println(httpCode);
      
      if (httpCode == HTTP_CODE_OK) {
        payloadGet = http.getString();
        Serial.print("Returned data: ");
        Serial.println(payloadGet);
        
        // Parse JSON data
        DeserializationError error = deserializeJson(doc, payloadGet);
        
        // Handle JSON parsing error
        if (error) {
          Serial.print("JSON parsing failed! Error: ");
          Serial.println(error.c_str());
        } else {
          // Extract values with explicit type conversion and bounds checking
          double RFT = 0;
          int QCOC = 0;
          
          // Safely extract RFT value
          if (doc.containsKey("DefectPercentage")) {
            RFT = doc["DefectPercentage"].as<double>();
          } else {
            Serial.println("WARNING: DefectPercentage field missing in JSON response");
          }
          
          // Safely extract QCOC value with explicit conversion to ensure it's either 0 or 1
          if (doc.containsKey("QCOC")) {
            QCOC = doc["QCOC"].as<int>();
            // Ensure QCOC is only 0 or 1
            QCOC = (QCOC == 1) ? 1 : 0;
          } else {
            Serial.println("WARNING: QCOC field missing in JSON response");
          }
          
          Serial.print("RFT value: ");
          Serial.println(RFT, 2);
          Serial.print("QCOC value (normalized): ");
          Serial.println(QCOC);
          
          // CRITICAL FIX: Turn off all lights first regardless of previous state
          digitalWrite(relay1, HIGH); // Turn OFF red
          digitalWrite(relay2, HIGH); // Turn OFF yellow
          digitalWrite(relay3, HIGH); // Turn OFF green
          digitalWrite(relay4, HIGH); // Turn OFF blue
          delay(200); // Ensure relays have time to reset
          
          // Only process valid RFT values
          if (RFT > 0) {
            // Handle QCOC with strict boolean logic - separate branches completely
            if (QCOC == 1) {
              // CHANGEOVER MODE - ONLY Blue light should be on
              Serial.println("CHANGEOVER MODE ACTIVE - Only Blue light should be ON");
              digitalWrite(relay4, LOW); // Turn ON blue light ONLY
            } else {
              // NORMAL OPERATION MODE - RFT lights only
              Serial.println("NORMAL OPERATION MODE - No changeover");
              
              // Set appropriate RFT light based on thresholds
              if (RFT < 97) {
                digitalWrite(relay1, LOW); // Turn ON red
                Serial.println("Red Bulb ON - RFT below 97%");
              } else if (RFT >= 97 && RFT <= 98) {
                digitalWrite(relay2, LOW); // Turn ON yellow
                Serial.println("Yellow Bulb ON - RFT between 97-98%");
              } else if (RFT > 98) {
                digitalWrite(relay3, LOW); // Turn ON green
                Serial.println("Green Bulb ON - RFT above 98%");
              }
              
              // Explicitly ensure blue is OFF in normal mode
              digitalWrite(relay4, HIGH);
            }
          } else {
            Serial.println("Invalid RFT value received - all lights kept OFF");
          }
          
          // Log the current state of all lights after changes
          Serial.println("Current light states after update:");
          Serial.print("Red: ");
          Serial.println(digitalRead(relay1) == LOW ? "ON" : "OFF");
          Serial.print("Yellow: ");
          Serial.println(digitalRead(relay2) == LOW ? "ON" : "OFF");
          Serial.print("Green: ");
          Serial.println(digitalRead(relay3) == LOW ? "ON" : "OFF");
          Serial.print("Blue: ");
          Serial.println(digitalRead(relay4) == LOW ? "ON" : "OFF");
        }
      } else {
        Serial.println("Server error or invalid response");
      }
    } else {
      Serial.print("HTTP request failed, error: ");
      Serial.println(http.errorToString(httpCode).c_str());
    }
    
    // Close connection
    http.end();
    Serial.println("----------------Connection Closed----------------");
  }
}

But the issue is now: If RFT is 97, yellow bulb turns on but simultaneously blue bulb and blue relay also turn ON. why blue bulb and relay are turning On. What should I do now? :frowning:

I'm not sure; perhaps you could start my learning to say thank you when someone helps you out rather than skipping that step and going right to "it still doesn't work".

Good manners count for a lot. Good-bye.

Paul, Should I use a regulator or high voltage adapter. But let me be sure first about it.

By "high voltage adapter" do you mean a mains 120/240V AC to 5V DC adapter?

By "regulator" I assume you mean a DC to DC regulator. But you don't have any DC power to regulate, as far as I can see. So you can't use that.

The point I am making is that however you make a 5V supply available, will it have sufficient current for the ESP and 4 relays?

Hey @jim-p I need your help here. Please help me in finding where the problem is? i'm connecting 220V AC bulbs directly with relays. Check my wiring diagram and suggest me which additional components should I use.

I think that may be the problem.

I mean a regulator that will increase the voltage if 5V not sufficiently supplying to relays

I'm confused in wiring connection of Relays with bulbs. Which wire of each bulb out of two will be connected to NO or COM of relay. and 5V adapter that I'm using to power ESP 32 wroom 32d.

This would only damage the relays, and the Arduino also.

It's becoming clear that your understanding of the basics of electricity is not enough to complete this project. You don't seem to have any understanding of the difference between voltage and current, for example. So I suggest you put the project to one side and spend some time studying electrical theory: voltage, current, power, Ohm's law and so on.

First thing : remove that URL. Just tried it and got a response
( host_or_IPv4)

In addition to the "=" issue you might consider creating a quick function that simply sets all outputs to "off" and call it before each change to the new state.

void reset (void) {
   digitalWrite(relay1, HIGH);
   digitalWrite(relay2, HIGH);
   digitalWrite(relay3, HIGH);
   digitalWrite(relay4, HIGH);
  }

Hi, @news123
Write some simple code that just cycles your relays.
This is just to test your hardware, make sure it works as you intend before playing with your main code.

Tom.... :smiley: :+1: :coffee: :australia:

Don't worry about the code just yet, it's not your main problem.
You will need to build a transistor driver for each relay.

The relays should be powered directly from your 5V power supply.

@jim-p , I'm working on Transistor driver circuit.

How to directly power relays from 5V power supply. Is that mean, I would use this below device to power relays and a separate 5V adapter to power ESP?


Please guide me If I'm wrong.