text:
How to get my LCD contentiously updating with data from sensor?
EDIT DOWNSTAIRS:
Hello beautiful people of the internet! How are you smart people doing with all that's going on these days. Okay so the title says it pretty much. I've got a code and inside of my if's I have added something that lets me see the data from the sensor in percentage on my LCD. It works but it just stays at the number it read when it went on that mode. How do I make it so it starts "updating" automatically.
Sooo I am talking about this part mostly (and other exactly like it)
    if (whichPlant == 2) {
      lcd.setRGB(plant3R, plant3G, plant3B);
      lcd.clear();
       lcd.display();
      lcd.print("Orchid");// print the results to the LCD Display:
      sensorValue = analogRead(waterSensorPin);// read the analog in value:
      sensorValue = map(sensorValue, 0, 750, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }

And here is my entire code if you're interested
#include <Servo.h>

#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;

const int numberOfPlants = 4;
const int noPlant = -1;  // index meaning no plant is being monitored

const int plant1R = 0;
const int plant1G = 0;
const int plant1B = 255;
const int zeroR = 0;
const int zeroG = 0;
const int zeroB = 0;
const int plant2R = 0;
const int plant2G = 255;
const int plant2B = 0;
const int plant3R = 255;
const int plant3G = 0;
const int plant3B = 0;
const int plant4R = 255;
const int plant4G = 0;
const int plant4B = 255;

// Pinout.
const int waterSensorPin = A1;
const int buttonPin = 2;
const int servoPin = 5;
const int ledPins[numberOfPlants] = {12, 11, 10, 9};

// Moisture ranges for the different plants.
const int moistureMinima[numberOfPlants] = {  0,   0,   0,   0};
const int moistureMaxima[numberOfPlants] = {195, 682, 750, 950};

// Servo holding the indicator needle.
Servo indicator;
int sensorValue = 0; // value read from the Soil Moisture
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  pinMode(waterSensorPin, INPUT);
  pinMode(buttonPin, INPUT);
  for (int ledNo = 0; ledNo < numberOfPlants; ledNo++) {
    pinMode(ledPins[ledNo], OUTPUT);
  }
  indicator.attach(servoPin);
}

void loop() {
  // Which plant are we currently monitoring?
  static int whichPlant = noPlant;
  // Switch to next plant on button press.
  if (digitalRead(buttonPin) == HIGH) {
    if (whichPlant != noPlant) {
      digitalWrite(ledPins[whichPlant], LOW);  // turn off previous LED
    }
    ++whichPlant;
    if (whichPlant == numberOfPlants) {
      whichPlant = noPlant;
    } else {
      digitalWrite(ledPins[whichPlant], HIGH);  // turn on current LED
    }
    if (whichPlant == 3) {

      digitalWrite(10, HIGH);  // turn off previous LED
      digitalWrite(12, HIGH);  // turn off previous LED
      lcd.setRGB(plant4R, plant4G, plant4B);
      lcd.clear();
       lcd.display();
      lcd.print("Swamp Plant");// print the results to the LCD Display:
      sensorValue = analogRead(waterSensorPin);// read the analog in value:
      sensorValue = map(sensorValue, 0, 950, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
      delay(500);  // crude debouncing
    }
    if (whichPlant == 2) {
      lcd.setRGB(plant3R, plant3G, plant3B);
      lcd.clear();
       lcd.display();
      lcd.print("Orchid");// print the results to the LCD Display:
      sensorValue = analogRead(waterSensorPin);// read the analog in value:
      sensorValue = map(sensorValue, 0, 750, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }
    if (whichPlant == 1) {
      lcd.setRGB(plant2R, plant2G, plant2B);
     lcd.clear();
      lcd.display();
      lcd.print("Sunflower");// print the results to the LCD Display:
      sensorValue = analogRead(waterSensorPin);// read the analog in value:
      sensorValue = map(sensorValue, 0, 682, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }
    if (whichPlant == 0) {
      lcd.setRGB(plant1R, plant1G, plant1B);
     lcd.clear();
      lcd.display();
      lcd.print("Orchid");// print the results to the LCD Display:
      sensorValue = analogRead(waterSensorPin);// read the analog in value:
      sensorValue = map(sensorValue, 0, 195, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }

  }
  if (whichPlant == noPlant) {
    digitalWrite(10, LOW);  // turn off previous LED
    digitalWrite(12, LOW);  // turn off previous LED
    lcd.clear();
    lcd.noDisplay();
    lcd.setRGB(zeroR, zeroG, zeroB);

  }
  // Report the moisture level of this plant.
  if (whichPlant != noPlant) {
    int sensorValue = analogRead(waterSensorPin);
    int position = map(sensorValue,
                       moistureMinima[whichPlant], moistureMaxima[whichPlant], 180, 0);
    indicator.write(constrain(position, 0, 180));
    Serial.println(sensorValue);
    delay(500);

  }
  // added 14-02 to make sure servo pointer goes back to start after reading last reading from waterSensor
  if (whichPlant == noPlant) {
    int sensorValue = analogRead(waterSensorPin);
    int position = map(sensorValue,
                       moistureMinima[whichPlant], moistureMaxima[whichPlant], 180, 0);
    indicator.write(constrain(position, 180, 180));
    delay(500);

  }

  //gemaakt door Sinan van Noppen
}

and if you have any suggestions or you have a go on making my code better, more DRY I would be honoured and appreciate it :)
EDIT: (just changed the place of the if whcihplant == 3 etc.)
#include <Servo.h>

#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;

const int numberOfPlants = 4;
const int noPlant = -1;  // index meaning no plant is being monitored

const int plant1R = 0;
const int plant1G = 0;
const int plant1B = 255;
const int zeroR = 0;
const int zeroG = 0;
const int zeroB = 0;
const int plant2R = 0;
const int plant2G = 255;
const int plant2B = 0;
const int plant3R = 255;
const int plant3G = 0;
const int plant3B = 0;
const int plant4R = 255;
const int plant4G = 0;
const int plant4B = 255;

// Pinout.
const int waterSensorPin = A1;
const int buttonPin = 2;
const int servoPin = 5;
const int ledPins[numberOfPlants] = {12, 11, 10, 9};

// Moisture ranges for the different plants.
const int moistureMinima[numberOfPlants] = {  0,   0,   0,   0};
const int moistureMaxima[numberOfPlants] = {195, 682, 750, 950};

// Servo holding the indicator needle.
Servo indicator;
int sensorValue = 0; // value read from the Soil Moisture
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  pinMode(waterSensorPin, INPUT);
  pinMode(buttonPin, INPUT);
  for (int ledNo = 0; ledNo < numberOfPlants; ledNo++) {
    pinMode(ledPins[ledNo], OUTPUT);
  }
  indicator.attach(servoPin);
}

void loop() {
  // Which plant are we currently monitoring?
  static int whichPlant = noPlant;
  sensorValue = analogRead(waterSensorPin);// read the analog in value:

  // Switch to next plant on button press.
  if (digitalRead(buttonPin) == HIGH) {
    if (whichPlant != noPlant) {
      digitalWrite(ledPins[whichPlant], LOW);  // turn off previous LED
    }
    ++whichPlant;
    if (whichPlant == numberOfPlants) {
      whichPlant = noPlant;
    } else {
      digitalWrite(ledPins[whichPlant], HIGH);  // turn on current LED
    }

  }
  if (whichPlant == noPlant) {
    digitalWrite(10, LOW);  // turn off previous LED
    digitalWrite(12, LOW);  // turn off previous LED
    lcd.clear();
    lcd.noDisplay();
    lcd.setRGB(zeroR, zeroG, zeroB);

  }
    if (whichPlant == 3) {

      digitalWrite(10, HIGH);  // turn off previous LED
      digitalWrite(12, HIGH);  // turn off previous LED
      lcd.setRGB(plant4R, plant4G, plant4B);
      lcd.clear();
      lcd.display();
      lcd.print("Swamp Plant");// print the results to the LCD Display:
      sensorValue = map(sensorValue, 0, 950, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
      delay(500);  // crude debouncing
    }
    if (whichPlant == 2) {
      lcd.setRGB(plant3R, plant3G, plant3B);
      lcd.clear();
      lcd.display();
      lcd.print("Orchid");// print the results to the LCD Display:
      sensorValue = map(sensorValue, 0, 750, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }
    if (whichPlant == 1) {
      lcd.setRGB(plant2R, plant2G, plant2B);
      lcd.clear();
      lcd.display();
      lcd.print("Sunflower");// print the results to the LCD Display:
      sensorValue = map(sensorValue, 0, 682, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }
    if (whichPlant == 0) {
      lcd.setRGB(plant1R, plant1G, plant1B);
      lcd.clear();
      lcd.display();
      lcd.print("Cactus");// print the results to the LCD Display:
      sensorValue = map(sensorValue, 0, 195, 0, 100);
      lcd.setCursor(0, 1);
      lcd.print(sensorValue);
      lcd.print("% Enough water");
      Serial.println(sensorValue);
    }

  // Report the moisture level of this plant.
  if (whichPlant != noPlant) {
    int sensorValue = analogRead(waterSensorPin);
    int position = map(sensorValue,
                       moistureMinima[whichPlant], moistureMaxima[whichPlant], 180, 0);
    indicator.write(constrain(position, 0, 180));
    Serial.println(sensorValue);
    delay(500);

  }
  // added 14-02 to make sure servo pointer goes back to start after reading last reading from waterSensor
  if (whichPlant == noPlant) {
    int sensorValue = analogRead(waterSensorPin);
    int position = map(sensorValue,
                       moistureMinima[whichPlant], moistureMaxima[whichPlant], 180, 0);
    indicator.write(constrain(position, 180, 180));
    delay(500);

  }

  //gemaakt door Sinan van Noppen
}

what does contentiously mean? ... do you mean continuously or continually?

you could use an array as a lookup table for data ... the four if (whichPlant == x) { could be replaced by one code block with data being retrieved from a lookup table plant1R, plant1G, plant1B, "Orchid", 195, "% Enough water"

look at this https://www.arduino.cc/en/Tutorial/Debounce ...... put the ++whichPlant; at the line in the tutorial  where the LED is toggled

the code starting at if (whichPlant == 3) { should not be inside of the if (digitalRead(buttonPin) == HIGH) { block ...................your code should check the button at the begining of the loop() block and increment the whichPlant variable if required ......... the subsequent code should always run and it should react to the value of whichPlant only ... it should not react to any button presses, or be prevented from running by any button state

you need to make some helper functions to cut down on the repetition and make the code easier to maintain. it looks like one to handle the plant could accept parameters of a string label and an upper bound for the map. another function should be the only way print to the lcd, from one place, i call it render(). you want the loop function to be short and to mainly call sub-routines to handle the details.

@jsotola hahah yes continuously, sorry

@dandavis Okay and how do I do that then? I'm not a programmer btw nor do I know any programming language, this is all new to me  :(

@jsotola okay so I see what you're saying about arrays the only problem is I have no clue how?? I have tried tinkering with it for hours but nevertheless I don't know.  As what you said I tried making a array int Orchid [] {plant3R, plant3G, plant3B, "Orchid", 750, "% Enough water"}; but if this is correct and then how to acces it? So the code works fine now it does what I want to do, but how I make it so it's cleaner with arrays and lookup tables I have no clue. I added updated code in EDIT.

no, an array like moistureMinima[] .... domething like this for the names plantNames[4] =  {"Cactus", "Sunflower","Orchid","Swamp Plant"}  .... use multiple arrays


text:
cannot connect ESP8266 web server after some time
I am new to ESP8266 and found an example about turning a LED ON/OFF using web interface. It works well but after some time (few minutes) i cannot open the web page (in my case it is http://192.168.100.23 and i made it static IP). It keeps 'waiting for 192.168.100.23'. I can ping the IP. Can someone please help to find what the problem is? Thank you very much!
Below is the code:
#include <ESP8266WiFi.h>
#define LED D2
const char* ssid = "myAP";
const char* password = "32133213";
unsigned char status_led=0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  /*WiFi.persistent( false );
  WiFi.setAutoConnect(true);
  WiFi.mode(WIFI_STA);*/
  Serial.println();
  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");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("new client");
  while(!client.available())
  {
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  if (req.indexOf("/ledoff") != -1)
  {
    status_led=0;
    digitalWrite(LED,LOW);
    Serial.println("LED OFF");
  }
  else if(req.indexOf("/ledon") != -1)
  {
    status_led=1;
    digitalWrite(LED,HIGH);
    Serial.println("LED ON");
  }
  String web = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  web += "\r\n";
  web += "\r\n";
  web += "
LED Status
\r\n";
  web += "
\r\n";
  if(status_led==1)
      web += "LED On\r\n";
  else
      web += "LED Off\r\n";
  web += "
\r\n";
  web += "
\r\n";
  web += "\r\n";
  web += "<button>LED On</button >\r\n";
  web += "\r\n";
  web += "
\r\n";

  web += "\r\n";
  web += "<button>LED Off</button >\r\n";
  web += "\r\n";

  web += "\r\n";
  web += "\r\n";

  client.print(web);
}

I added WiFi.setSleepMode(WIFI_NONE_SLEEP); but it does not help. I found another script that is working well so far (after 1 day). I am new so i do not know what problem is but i think it needs to free memory and close connection. Below is the new code for those who get the same problem!
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#define LED D2
// Replace with your network credentials
const char* ssid     = "myAP";
const char* password = "32133213";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String outputState = "off";
// Assign output variables to GPIO pins

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(LED, OUTPUT);
  // Set outputs to LOW
  digitalWrite(LED, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}
void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /on") >= 0) {
              Serial.println("light on");
              outputState = "on";
              digitalWrite(LED, HIGH);
            } else if (header.indexOf("GET /off") >= 0) {
              Serial.println("light off");
              outputState = "off";
              digitalWrite(LED, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
ESP8266 Web Server
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
State " + outputState + "
");
            // If the output5State is off, it displays the ON button
            if (outputState=="off") {
              client.println("
<button class=\"button button2\">TURN ON</button>
");
            } else {
              client.println("
<button class=\"button\">TURN OFF</button>
");
            }

            client.println("");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

The esp8266 enters modem sleep in STA mode without WiFi traffic. You can turn off the sleep mode with WiFi.setSleepMode. The possible parameters are WIFI_NONE_SLEEP, WIFI_LIGHT_SLEEP or WIFI_MODEM_SLEEP.
After some longer time the servers on esp8266 with arduino core usually get inaccessible even it the esp8266 connects as client to other servers or still sends UDP messages. It is a known issue with some possible workaround documented.

Thank you very much for your quick reply. I will work around on it.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Does flashing ESP8266/ESP-01 firmware mean uploading a new 'sketch' and why different firmware?
Hi I am new to IOT and I am now in love with this. However I'm a little confused right now with the jargon. My question is similar to this. But I do have some extra questions though.

When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?
On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?
For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?
To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.
Is the reason for using other firmware is because of how the code is compiled and the language used?

If someone could clear things up for me I would greatly appreciate it. Thanks!

the right term is "application". firmware is application. sketch is application. the rest of the question is off-topic

firmware can mean both host environments that run higher-level code like LUA, tasmota, and AT, or it can mean something custom like ardunio, sdk, etc.

When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

Yes. "Firmware" is application code running on the microcontroller.

On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?

Yes. "Firmware" is application code running on the microcontroller.

For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

Yes. "Firmware" is application code running on the microcontroller.

To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.

No. The Arduino IDE is for coding in C++ with the Arduino API extensions.

Is the reason for using other firmware is because of how the code is compiled and the language used?

The firmware is just what runs on the chip. If that firmware provides its own programming language then you can use that to execute that programming language.
If you write your own firmware in the Arduino IDE then the chip runs that firmware. If you upload the AT firmware then the chip runs the AT firmware and you can control it with AT commands. If you upload the NodeMCU Lua firmware then the chip runs the NodeMCU Lua firmware and you control it using Lua commands and scripts.

my opinion about the term 'firmware' https://stackoverflow.com/questions/57333773/is-programming-arduino-means-adding-firmware/57455539#57455539

@Juraj Your opinion is wrong. Firmware is machine code that runs directly on the hardware and has no other requirements. Software is code (compiled or otherwise) which requires other code to already exist to function. Anything "bare metal programmed" is firmware. On a PC the OS is software, but the BIOS or EFI are firmware. Sketches are therefore firmware.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
SIM800L - AT Commands not doing anything on Arduino Serial Monitor
I am trying to send AT commands to SIM800L through Arduino's Serial Monitor. However when I type any command in the serial monitor nothing happens. I'm using an Arduino MEGA 2560 and the TX/RX of the SIM800L is connected to 9 and 10 respectively. Here is the code:
#include <SoftwareSerial.h>

SoftwareSerial GPRS(9, 10);
boolean state, lastState;

void setup()
{
  pinMode(2, INPUT_PULLUP);
  state = digitalRead(2);
  lastState = state;

  GPRS.begin(9600);
  Serial.begin(9600);

  GPRS.println("AT+CMGF=1");

  delay(1000);
}

void loop()
{
  while(GPRS.available()) {
    Serial.write(GPRS.read());
  }

  lastState = state;
  state = digitalRead(2);

  if ( state != lastState ) {
    sendSMS();
  }

  delay(500);
}

void sendSMS() {
  Serial.print("Switch was turned ");
  Serial.println(state ? "on" : "off");

  GPRS.println("AT+CMGS=\"+64XXXXXXXXX\"");

  delay(500);

  GPRS.print("Switch was turned ");
  GPRS.println(state ? "on" : "off");
  GPRS.write( 0x1a ); // ctrl+Z character

  delay(500);
}

Any help would be much appreciated!
EDIT2: I forgot to mention but I am able to send, receive, and call from the GSM Module (with a different code). However I am not able to read the the received messages, since I only get a +CMT "SM",  message and I can't exactly use AT+CMGR or CMGL commands because the serial monitor does nothing with them. here's the code for that:
#include <SoftwareSerial.h>
SoftwareSerial sim(9,10);
int _timeout;
String _buffer;
String number = "+639XXXXXXXXX"; //-> change with your number
void setup() {
  delay(1000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Lets go!");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}
void SendMessage()
{
  Serial.println ("Sending Message");
  sim.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Wala kang jowa!";
  sim.println(SMS);
  delay(100);
  sim.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}
void RecieveMessage()
{
  Serial.println ("SIM800L Read an SMS");
  delay (1000);
  sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
  Serial.write ("Unread Message done");
}
String _readSerial() {
  _timeout = 0;
  while  (!sim.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim.available()) {
    return sim.readString();
  }
}
void callNumber() {
  sim.print (F("ATD"));
  sim.print (number);
  sim.print (F(";\r\n"));
  _buffer = _readSerial();
  Serial.println(_buffer);
}

when I type any command in the serial monitor nothing happens ... you don't have any code for that

@jsotola i thought it would take any AT commands automatically in the serial monitor? anyway i'll add my code that i used where i could send/receive/call the phone but not read any messages i receive

the arduino will not do something on its own ... try this code ... https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

Why are you using SoftwareSerial on a Mega?!?!

Do not use SoftwareSerial on a Mega2560 unless you absolutely know what you are doing.
SoftwareSerial does not work on many of the pins of the Mega2560, and since there are other hardware serial ports available there is seldom any reason to resort to using SoftwareSerial anyway.
Connect your SIM800L to the TX1/RX1 pins of the Mega2560 then communicate using the pre-defined Serial1 object.

I see. I looked up some stuff regarding my question on other posts and almost everyone says to not use SoftwareSerial with Mega2560. Althought tbh I still don't completely understand what to do. Do I simply remove everything related to SoftwareSerial? How do I use the hardware serial ports; do I still need to code them in like in software serial or can i just connect the SIM800L to the TX1/RX1 without worrying about anything else? Dumb questions I know, but I've been out of touch with Arduino for over a year no so please bear with me...

Of course you have to code them in. You read with Serial1.read() and write with Serial1.print(...) in the exact same way as any other form of serial communication. You can't just plug random things in and expect the Arduino to magically know what they are and how to work with them.

i guess what i really wanted to ask there was whether i needed to include another library like software serial. so basically i dont have to use any libraries now, right? What I still don't understand is that everyone seems to be using SoftwareSerial <GSM name>(<TX>,<RX>) to connect their GSM modules to their Arduino, regardless of whether it's an UNO or a Mega. If I'm not supposed to use SoftwareSerial, what should I be replacing that with? Or am I missing something completely here?

No libraries needed. Nothing to define. Serial1 is already defined for you. Just use Serial1.print() and Serial1.read() where you use sim.print() and sim.read() and so forth.

oh so i can just do something like sim(<TX>,<RX>) without anything before it and then it's already defined as Serial1?

No. You don't define anything. You just use Serial1.

oh, that's what i was confused about! thanks!

Make sure the RX of your arduino board is connected to TX of GSM and the TX should be connected in RX of GSM module.
Next try to do this

   GPRS.begin(9600);
   Serial.begin(115200);

Also double check your wirings, if you have a tester you might wanna check if both end are connected with each other. And in the loop try to print this Serial.println(GPRS.available()) if it is not greater than 0 then you have a problem with your connection.

    #include <SoftwareSerial.h>
    SoftwareSerial sim(2,3);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      sim.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while(Serial.available() > 0){
        sim.write(Serial.read());
      }

      while(sim.available() > 0){
        Serial.write(sim.read());
      }
    }

diagram reference.

Hope this help.

why would you wire it to RX/TX of the Mega and what is the GPRS object in your answer?

Where did I get the GPRS? from his code.
well actually just follow my supper simple diagram from the link bellow for you to understand
https://imageup.me/images/a49982fe-c592-44d7-b696-ed80e725fec5.png
and follow my supper simple code for you again to understand. :-)
#include <SoftwareSerial.h>
SoftwareSerial sim(2,3);
void setup() {
Serial.begin(115200);
sim.begin(9600);
}
void loop() {
while(Serial.available() > 0){
sim.write(Serial.read());
}
while(sim.available() > 0){
Serial.write(sim.read());
}
}

@homerio  Your link gives "Oops! An unhandled exception occurred while processing the request.".

@homerio Comments are not for posting images and code. Please amend your answer to make it clearer.

Follow this link also for the diagram reference - you can embed images into answers. That is better because external links can become link-dead.

That's strange? I don't know how to embed in comment @Nick :D, but thanks man :-)

You posted an answer. You can edit it. When you do so there is an icon for embedding images.

Saw it. thanks man.


text:
How to send NEO6M gps data to firebase?
I'm using nodemcu and neo6m gps module. I can't send data to firebase. As a library using tinygps++. Can anyone please help me how can i pass data to firebase.
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include "TinyGPS++.h"
#include "SoftwareSerial.h"

// Set these to run example.
#define FIREBASE_HOST "vessel-monitoring-a21f4.firebaseio.com"
#define FIREBASE_AUTH "EYUZc64JyLMR5cbJc99nZzjah8uwEDxSp3m93Lvr"
#define WIFI_SSID "H17"
#define WIFI_PASSWORD "pass@router"

//GPS
SoftwareSerial serial_connection(4, 0); //tx,rx
TinyGPSPlus gps;// GPS object to process the NMEA data

float latt, lngg;

void setup() {
  Serial.begin(9600);
  serial_connection.begin(9600);
  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop() {
    while (serial_connection.available()) {
      gps.encode(serial_connection.read());
    }
    if (gps.location.isUpdated()) {
      latt = gps.location.lat();
      lngg = gps.location.lng();
      Serial.println(latt, 6);
      Serial.println(lngg, 6);
      delay(1000);
    }
    char location_str[25]={0};
    sprintf(location_str, "%f, %f", latt, lngg);
    String name = Firebase.push("location", location_str);
    if (Firebase.failed()) {
      Serial.print("setting /location failed:");
      Serial.println(Firebase.error());
      return;
    }
    delay(1000);
}

Please show the code you have problems with, and tell us something about what goes wrong.

I update the code in the post. The problem is I got 0 value for lat, lng in firebase. Sometimes it provides the correct value in firebase(the ratio is too low).

With Firebase.push you add a new location to the "location"-collection with every call. Is that, what you intended to do?  If you just want to set a string to the location attribute use Firebase.setString("location", location_str);. It would also be a good idea to move the code that writes into the Firebase into the if (gps.location.isUpdated())  block. IMHO You only have to write into the Firebase if the location has been changed. Btw I would understand the behavior of the code better, if I'd know whether the Serial.println(latt, 6); and Serial.println(lngg, 6); prints out someth.

I don't understand more about your comment. Can you please help me to arrange the code, where i can store lat, lng in firebase database with nodemcu.


text:
Send data from UNO to MQTT through NodeMCU 12E - problem
i am trying to send data from ACS712 sensor which is connected to UNO (3 sensors). Everything works fine on UNO, but when I send only one value from UNO through NodeMCU 12E to MQTT server, it shows totally different number (UNO gives 0.25, mqtt shows 0 or 9 or something third). For connection btwn UNO and NodeMCU 12E i was using this picture (attached).
Here is code for UNO:
#include "ACS712.h"
char prva[5];
char druga[5];
char treca[5];
char cetvrta[5];
ACS712 sensor1(ACS712_30A, A0);
ACS712 sensor2(ACS712_30A, A1);
ACS712 sensor3(ACS712_30A, A2);
unsigned long last_time =0;
unsigned long current_time =0;
float Wh1 =0 ;
float Wh2 =0 ;
float Wh3 =0 ;
float Wh4 =0 ;
void setup() {
  Serial.begin(9600);
  sensor1.calibrate();
  sensor2.calibrate();
  sensor3.calibrate();
}

void loop() {
  float V = 220;
  float I1 = sensor1.getCurrentAC();
  float I2 = sensor2.getCurrentAC();
  float I3 = sensor3.getCurrentAC();
// Serial.println(I);
  float P1 = V * I1;
  float P2 = V * I2;
  float P3 = V * I3;
  float U = P1 + P2 + P3;
  last_time = current_time;
  current_time = millis();
   Wh1 = Wh1+  P1 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh1, 4, 2, prva);
   Wh2 = Wh2+  P2 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh2, 4, 2, druga);
   Wh3 = Wh3+  P3 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh3, 4, 2, treca);
   Wh4 = Wh4+  (P1 *(( current_time -last_time) /3600000.0))+ (P2 *(( current_time -last_time) /3600000.0))+  (P3 *(( current_time -last_time) /3600000.0)) ;
   dtostrf(Wh4, 4, 2, cetvrta);
  Serial.print( " (1) W: " );
  Serial.print(prva);
  Serial.print("   ");
  Serial.print( " (2) W: " );
  Serial.print(druga);
  Serial.print("   ");
  Serial.print( " (3) W: " );
  Serial.print(treca);
  Serial.print("   ");
  Serial.print( " (4) W: " );
  Serial.print(cetvrta);
  Serial.print("          ");
  Serial.print(P1);
  Serial.print("  W/h (1)");
  Serial.print("      ");
  Serial.print(P2);
  Serial.print("  W/h (2)");
  Serial.print("      ");
  Serial.print(P3);
  Serial.print("  W/h (3)");
  Serial.print("          ");
  Serial.print(U);
  Serial.print("  W/h (1,2,3)");
   delay(10000);
  Serial.println();

Here is code for NodeMCU 12E: (here i want to send only one data named cetvrta.
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WLAN_SSID       "Qwerty"
#define WLAN_PASS       "123456"
char cetvrta[5];
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "werty"
#define AIO_KEY         "12345"

WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish Power = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/power");
//Adafruit_MQTT_Publish bill = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/bill");
void MQTT_connect();

void setup() {
  Serial.begin(9600);
  delay(10);
  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());
}

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

 int i=0;
 float watt1;
 if(Serial.available() > 0 ){
   delay(1000); //allows all serial sent to be received together
    while(Serial.available() && i<6) {
     cetvrta[i++] = Serial.read();
    }
    cetvrta[i++]='\0';
  }

 watt1 = atof(cetvrta);
  Serial.print(F("\nSending Power val "));
  Serial.println(watt1);
  Serial.print("...");

  if (! Power.publish(watt1)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

delay(3000);
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Converting the 3.3V PWM signal to 5V PWM signal
I am using ESP32....the max Pwm signal of it is 3.3V...And I have to control two motors speed by TB6612FNG motor driver...when i was using Arduino.. The arduino can send max 5V Pwm signal to the motor drivers PWM pin.. And the motor runs at the exact speed...but now i have to use ESP32..which sends 3.3V and the motors slow down..
So what should I do to convert the ESP32's PWM signal to 5v and according If i change the PWM value at the program..the output will also change similarly as Arduino??
Please help me

Looking at TB6612FNG datasheet i read

Logic supply voltage (VCC) can be in the range of 2.7--5.5VDC

So, if you supply 3.3V to VCC all should be ok, if the motors themselves get enough power (via VM)


text:
Help using an Arduino as as an FTDI with a ESP8266 carrier shield to see an AT response
I have a Duinopeak shield that lets you plug on an ESP-01 and provides a 5V-3.3V regulator and level shifting for the Tx and Rx pins. I cannot get it to work with a setup that has worked with every ESP-01 or Wifi Shield I have used before.
Between the Arduino and the shield I connect Tx/Tx and Rx/Rx. I either load a blank sketch or jumper RST to ground on the Arduino. I use pins 0 and 1 through the shield. When I plug in the USB cable and type AT and "send". Nothing. No light blinks on the ESP sitting on the board. This is the board:
https://alexnld.com/product/duinopeak-esp8266-esp-01-wifi-expansion-board-shield-without-esp8266-module-for-arduino/
I know the ESP and the board works, because if I connect it to a Mega and use Seria1 instead of the main serial(0), rewire Tx/Rx and Rx/Tx, and upload a sketch to echo the USB Serial to Serial1 and back, using Serial Monitor, I can send AT commands and see responses. But when connected to pins 0 and 1, it acts like it isn't connected.
What I have tried:

Tried an Uno and Mega
Tried removing the plastic jumpers and running wires from the rows of Rx and Tx pins to the header directly
Tried different pins on the row (there are 8 Tx pins and 8 Rx pins so you can jumper to D0-D7)
Tested the continuity of each pin with a meter

I thought it must be the level shifter, but then why would it work when using Serial1? I thought the pins might have a cold solder joint, but then I used jumper wires from the pins in both tests and the same pins work (in reverse) when I connect them to Serial1 on the Mega. I thought it might be because of the 2 resistors on the USB path to pins 0 and 1 on an Arduino, but they prefer the pins over the USB. And why would another very similar board work? Tracing and finding an identical looking board shows this schematic. Odd thing is this is identical to a different board that works
:

and you power it from 5 V pin of Uno? on other pins you used SoftwareSerial with the SerialPassthrough sketch?

I have the shield on the Uno or Mega and which takes the 5V from the Arduino and regulates it to 3.3V. I can't use software serial because my sketch will need critical interrupt timing and the softwareSerial library will destroy that. tried to use pins 0/1 with the Uno and Mega for passthrough with no sketch and Tx/Tx, Rx/Rx. I used the "reflector" sketch on a mega to use serial1 or serial3 for the ESP and USB for the serial monitor and that works (Tx/Rx, Rx/Tx). Passthrough works with a bare ESP or a Makerfabs board with identical FETs and resistors for the level shifter circuit.

More info. I put a scope on the signal. My IOREF (that the schematic says it uses is 5.3V. When I jumper to Serial1 on a Mega, I see the Tx and Rx signals at around 4V. When I try to use Serial(0) The Tx to the ESP is only 3V. I suspect something in the Arduino circuit is not allowing enough voltage or current to drive. I'll try writing a sketch to continually send and see if I see 3V pulses that the Arduino can't read.


text:
Whats wrong with my SPI code using uno?
I am stuck reading A1335 sensor through SPI. I have asked on the Aduino forum under the "Networking.." topic but no one is helping.
Link to other forum post
I have changed the code so many times now that I am completely confused. Noob at understanding the data sheet, my problem mite have something to do with timing. Noob at SPI , I think my arduino-SPI code is where I went wrong.
Almost certain my wiring is good.
latest code:
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3
 */
#include <SPI.h>

  // set slave pins and variables
  const int ss1 = 10;
  const int ss2 = 9;
  const int ss3 = 8;
  uint16_t Ang_ss1 = 0;
  uint16_t Ang_ss2 = 0;
  uint16_t Ang_ss3 = 0;

/*SPI settings here and not declared globaly for attaching different
  spi devices with difrent settings. Call transaction,begin with new
  settings*/

SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3); //mode and 10mHz from manual, MSBfirst is a guess

void setup() {
   //set slave pins High and as outputs

  pinMode (ss1,OUTPUT);
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  //set up register once and receive data in loop
  SPI.begin();
  Serial.begin(9600); //in different post it's said Serial.begin must be before SPI.begi......true or false
  SPI.beginTransaction(settingsA);
  digitalWrite (ss1,LOW);
  SPI.transfer(0x20);
  SPI.transfer(0);
  digitalWrite(ss1,HIGH);
  SPI.endTransaction();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 to 3 and read registers 0x20 and 0x21 after I get First 1 working

digitalWrite (ss1,LOW);      // sensor one read and store two bite data in ANG_ss1
//Ang_ss1 = SPI.transfer(0x20); //0x20 and 0x21 angle register
Ang_ss1 = SPI.transfer(0); // receive data 0x20 high byte
Ang_ss1 = <<8;
Ang_ss1 |= SPI.transfer(0);//receive low byte
digitalWrite(ss1,HIGH);

SPI.endTransaction();

//De-bug code: display values from sensors
Serial.print(Ang_ss1,BIN);              //Serial.print Ang_ss1 in binary
Serial.println(" ss1     ");
Ang_ss1 = <<4;  //firs 4 bytes are not part of angle
Ang_ss1 = >>4;
Serial.print(Ang_ss1);Serial.println(" ss1 shifted");

Serial.print(Ang_ss1 * 360/4096 );  // formula from programming manual for sensor removed brackets from '(360/4096)'
Serial.println(" DEG   ");

delay (1000);                       // to read serial monitor for debugging
}

The relevant data sheet and programming manual is linked in link up top. There's only 3 relevant pages in programming manual, page 21-23.
Also a video of output to serial monitor and garble I got on my oscilloscope.
Will only be back home tomorrow to test latest code on oscilloscope.
new Video of whats going on. New code uploaded but same problems.
Reminder data sheet and such in link at start of post.
Progress: seems uno 5V out not enough for three sensors. I am getting better results with just one. here is a video Still need help with code please
Confirmed can only run 1x SPI and when using I2C it becomes buggy with 2x sensors but one works a treat.
new Video
And code:
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3, UNO: SCL 13, Miso 12, mosi 11.
 *                                                  pink     yelo       orange
 **********************************************************************************/
#include <SPI.h>

  const int ss1 = 10; const int ss2 = 9; const int ss3 = 8;          //slave select pins
  uint16_t Ang_ss1 = 0;  uint16_t Ang_ss2 = 0; uint16_t Ang_ss3 = 0; //store 16bit register
  float Chip1; float Chip2; float Chip3;                             //after math valaue with commas( deg out of 360)

  SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3);               //Spi settings

void setup() {

  pinMode (ss1,OUTPUT);                       //set slave pins High and as outputs
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  Serial.begin(9600);
  SPI.begin();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 and read 0x20 and 0x21 registers

digitalWrite (ss1,LOW);                          // sensor one read and store two bite data in ANG_ss1
Ang_ss1 = SPI.transfer(0x20);                              //0x20 and 0x21 angle register
Ang_ss1 = Ang_ss1 <<8;
Ang_ss1 |= SPI.transfer(0);                               //receive low byte 0x21
digitalWrite(ss1,HIGH);

SPI.endTransaction();

Ang_ss1 = Ang_ss1 <<4;                                    //first 4 bytes are not part of angle
Ang_ss1 = Ang_ss1 >>4;
Chip1 = (float) Ang_ss1 / 16;                             // change binary to desimal
Chip1 = (float)Ang_ss1 /4096.0 * 360.0;                  //  formula in manual is n*(360/4096)

Serial.print(Chip1);
Serial.println(" DEG   ");

//delay (2000);                       // to read serial monitor for debugging

}

Lines like this Ang_ss1 <<8; do nothing. I guess you want to write the result back into the Ang_ss1 variable? Have you forgotten the equal sign?

Yes I forgot the equal sign. I will change that thank you, still not getting angle from sensor.

Please show the pure data, that you receive from the sensor (not some calculated value), so that we can see, if the SPI code itself works or not

chrisl, I am about to board a bus to airport. Hopefully I will have 'the latest code' tested and oscilloscope attached to see what code does by 13.00 today. Up to now just received one constant value through serial monitor

You may have to set the SPI pins to output yourself

Sim Son,  I have solved the problem. I had a power supply issue. The code now works but only for one sensor. I saw it was preferred to edit original Q? rather than comment down here. See last part of original post.  How do I mark this Q as solved or answered or what ever?


text:
MKR Zero not showing up in WIN10 device manager / Arduino IDE cannot detect port / COM
I'm new to Arduino and hope you guys can give some advise.
I bought MKR Zero a few days before and tried to connect to my Win10 laptop. I can see the LED on the board is on, but the Arduino IDE cannot detect it. the "Port" is grey out. I tried 2 laptops which also Win10 but same situation happen. I tried different USB cables I had.
I checked the device manager in the control panel, there is no "Unknown device" under the USB port but also no MKR showing up. I don't know what to do.
I'm not sure if it is Win10 problem...Please kindly advise, thank you very much!!

Try a different cable?

You can try out this reference for your problem How To Disable Driver Signature Enforcement in Windows 10 . Also check the connections.

i bought another 2 cables and same situation still happen

did you install the SAMD boards package? https://www.arduino.cc/en/Guide/ArduinoMKRZero

yes i did - now the IDE can let me select MKR Zero board, but the "Port.  >" is grey out. I still cannot select the port that is connecting to the board

thank you kaviranga - i tried to disable the enforcement but still cannot connect to my board

Have you tried runnng the ArduinoIDE as admnistrator?

thank you Codebreaker007 - just tried to run as administrator, but the Port still grey out

Are you sure that you are using usb data cables, if the device shows not up in device manager you probably use a "charging only" usb cable used for mobile phones or similar to load. Can you see the MKR Zero in device manager?

thank you Codebreaker007 - no I cannot see it in device manager even if i plug it in my laptop, so maybe i am really using "charging only" usb cable...I will go to some shops and buy data cable and try again, thank you for your advice!

Take your laptop and your Arduino with you The right cable will let the Arduino show up in device manager (most sellers do not even know there are different types of usb cables on the market. Report back your proceedings

hello - i went to the shop and bought the "sync and charge" cable and tried on 3 different Win10 laptops, still same situation happen - the LED light is on but nothing detected in the device manager.
I think I will just simply go back to the shop and return the Arduino board...

hello - I went back to the hardware shop and they verified that my MKRZero is really not working...they changed another one to me and it works now...thank you everyone for your kind suggestion! I will close this question now. Thanks!

Hardware itself problem. Went to the shop and changed the board to me and now works.


text:
If condition not working as expected
In the last condition in else if (see code marked with ***), I am not getting my screen with the laser/specklke fail, if both failflag 1 and failgflag 5 is there,  however it shows me laser fail instead. Please help to solve my error.
#include <UTFT.h>
#include <avr/pgmspace.h>
#include <SPI.h>
#include <avr/wdt.h>
extern uint8_t Retro8x16[];
extern unsigned int virtek3[];  //display pic
UTFT myDisplay(ST7735, 11, 13, 3, 2, 4);

int buttonhold = 0;
int state = HIGH;
int tim = 0;
int tim1 = 0;
int tim2 = 0;
int button = 1;

float volt = 0;
float volt1 = 0;
float volt2 = 0;
float volt3 = 0;
float volt4 = 0;
float volt5 = 0;
float volt6 = 0;
float volt7 = 0;
float volt8 = 0;
float volt9 = 0;
float volt10 = 0;
float volt11 = 0;
float volt12 = 0;
float volt13 = 0;
float volt14 = 0;
float volt15 = 0;
float volt16 = 0;
float volt17 = 0;
float volt18 = 0;
float volt19 = 0;
float volt20 = 0;
float volt21 = 0;
float vcc = 0.0;
float temp = 0.0;
float r1 = 10000.0;
float r2 = 2200.0;
int failflag = 0;

//void(* resetFunc) (void) = 0;

void setup()
{
    pinMode(18, INPUT);   //For NEXT button
    pinMode(20, OUTPUT);  //For Relay power
    pinMode(21, OUTPUT);  //For Relay power
    pinMode(14, INPUT);
    Serial.begin(9600);
    myDisplay.InitLCD();
    myDisplay.clrScr();
    myDisplay.setFont(Retro8x16);

                                                                                digitalWrite(20, HIGH);
    digitalWrite(20, HIGH);
    digitalWrite(21, LOW);

    attachInterrupt(digitalPinToInterrupt(18), next, LOW);
    myDisplay.fillScr(255, 255, 255);
    myDisplay.drawBitmap(20, 1, 126, 126, virtek3, 1);

   while (1) {
    delay(100);
    if (state == LOW) {
    break;
    }
  }
}

void next() {
    state = LOW;
    Serial.println(buttonhold);
    buttonhold++;
    if (buttonhold > 500) {
    //digitalWrite(21, LOW);
    resetFunc();
    }
  }

void loop()
{
  digitalWrite(20, LOW);
 digitalWrite(21, LOW);   //Relay is ON.
  myDisplay.clrScr();
  state = HIGH;
  buttonhold = 0;
  while (1) {
    failflag = 0;
    float voltage_value = 0;

    myDisplay.setColor(0, 255, 255);
    myDisplay.print("1.Voltage Test", 35, 0);

    myDisplay.setColor(255, 255, 255);
    myDisplay.print("(V)", 0, 20);
    myDisplay.print("LASER",50,20);
    myDisplay.print("SPECKLE",100,20);

delay(1000);

      //FOR ANALOG A4 PIN
      //A4 pin connected to TP2 of speckle
      float volt_b = 0;
       float volt_c = 0;
       float volt_d = 0;
      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A4)));
      }
      volt_b = volt_b / 1000;
      volt1 = volt_b / (r2 / (r1 + r2));

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("TP2 :", 0, 38);

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 60, 37);

      Serial.println(volt1);                      //ANALOG A4
      if (volt1 >= 5 && volt1 <= 7.30) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt1, 2, 120, 38);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt1, 2, 120, 38);
      //myDisplay.print(" ", 150, 38);
      failflag = 1;
      }

      delay(2000);

      digitalWrite(20, HIGH);
      digitalWrite(21, LOW);
       delay(2000);

      //FOR ANALOG A4 PIN
      //A4 pin connected to TP2/L of SPECKLE

      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A4)));
      }
      volt_b = volt_b / 1000;
      volt2 = volt_b / (r2 / (r1 + r2));

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("TP2/L :", 0, 56);

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 60, 56);

      Serial.println(volt2);                       //ANALOG A4
      if (volt2 >= 5 && volt2 <= 0.05) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt2, 2, 120, 56);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt2, 2, 120, 56);
      //myDisplay.print(" ", 150, 56);
      failflag = 1;
      }

      //FOR ANALOG A1 PIN
      //A1 pin connected to J1_1 of SENSOR
      volt = analogRead(A1);
      volt3 =(volt * 4.8) /1024;

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("J1_1 :", 0, 74);

      Serial.println(volt3);                 //ANALOG A1
      if (volt3 >= 0 && volt3 <= 5.25) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt3, 2, 60, 74);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt3, 2, 60, 74);
      //myDisplay.print(" ", 150, 74);
      failflag = 5;
      }

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 125, 74);

      //FOR ANALOG A0 PIN
      //A0 pin connected to J2_2 of SENSOR

      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A0)));
      }
      volt_b = volt_b / 1000;
      volt4 = volt_b / (r2 / (r1 + r2));

    //volt4 = volt_c - 2.7;

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("J2_2 :", 0, 92);

      Serial.println(volt4);                //ANALOG A0
      if (volt4 >= 5 && volt4 <= 8.82) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt4, 2, 60, 92);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt4, 2, 60, 92);
      //myDisplay.print(" ", 150, 92);
      failflag = 5;
      }

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 125, 93);

      digitalWrite(20, LOW);
      digitalWrite(20, LOW);
      delay(2000);

      if (failflag == 5) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("LASER FAIL", 35, 108);
      delay(4000);
      state = 0;

      }

      else if (failflag == 1) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("SPECKLE FAIL", 35, 108);
      delay(40000);
      state = 0;

      }

 // *** Here the condition not working START
    else if ((failflag == 5) && (failflag == 1)) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("LASER/SPECKLE FAIL", 15, 108);
      delay(40000);
      state = 0;
      }
  // *** Here the condition not working END

what is the program supposed to do? .... what are you expecting to happen? .... what actually happens? .... do you get any errors?

(failflag == 5) && (failflag == 1))

failflag can't be both 5 and 1 at the same time.

As you ask for two different assignments for the same var its never gone to work this way. Two quick options:
Do binary addidition
 failflag = 0;
 if(errorA) failflag += 1;
 if(errorB) failflag += 2;
 if(errorC) failflag += 4;
 if(errorD) failflag += 8;

//then you can decode combined errors as follows
else if (failflag == 13) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

The other quick one is defining failflag as bool array
bool failflag [5] = {00000}; // 5 elements

 if(errorA) failflag [0]= 1;
 if(errorB) failflag [1]= 1;
 if(errorC) failflag [2]= 1;
 if(errorD) failflag [3]= 1;

//then you can decode combined errors as follows
else if ( failflag [0] == 1 &&  failflag [2]== 1 && failflag [3]== 1) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

as we have failflag[i] as a bool we can condense the code to
else if ( failflag [0] && failflag [2] && failflag [3]) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

Whatever suits your needs. As I said just 2 quick ones
Edit Cleaning up you question other things to change:
Get rid of the delay() (except in setup to initialize your hardware and in loop  during debuging.
The 21 float vars could be stores in a float array
 float myFloatVars [22]

and write the values to the position
 myFloatVars [11] = myMeasureFunction();

you can do this even in a timed for loop doing a recurring FIFO function (kind of circle buffer), the first saved value is dumped if the array is full to put the next one in. So you are able to produce a "gliding" average, which is what you want

bool data type is true/false, so the test is if ( failflag [0])  or if ( !failflag [0])   .... if ( failflag [0]== 1) equates to if ( true==true), which is redundant

Your right  copy & paste error. changed it to true so that the OP sees whats going on - the redundancy helps beginners to understand. Thanks for the eagle eye

note: null termination is used for strings, not for numerical arrays

this is for OP's benefit .... if(errorA) failflag [0]= 1; can be replaced by failflag[0] = errorA, but only if the failflag[0] is not set by multiple sources

Thank you so much . I use bool array and it works. Really appreciate you legend !

Please mark as solved/accepted Thanks


text:
ESP32 on Arduino IDE: Identify the board type in code (preprocessor macro)
I have read the answers on this post, but they do not seem to be providing a solution for ESP32 boards.
Is there a way to get the .name that is used from the boards.txt without modifying the platform.txt?
for example for uno there is uno.name=Arduino Uno
for esp32 esp32wrover.name=ESP32 Wrover Module
For ESP32 I can only find .name having the specific board name
This is a sample of the first 2 boards defined in boards.txt for esp332
menu.UploadSpeed=Upload Speed
menu.CPUFreq=CPU Frequency
menu.FlashFreq=Flash Frequency
menu.FlashMode=Flash Mode
menu.FlashSize=Flash Size
menu.PartitionScheme=Partition Scheme
menu.DebugLevel=Core Debug Level
menu.PSRAM=PSRAM
menu.Revision=Board Revision

##############################################################
### DO NOT PUT BOARDS ABOVE THE OFFICIAL ESPRESSIF BOARDS! ###
##############################################################

esp32.name=ESP32 Dev Module

esp32.upload.tool=esptool_py
esp32.upload.maximum_size=1310720
esp32.upload.maximum_data_size=327680
esp32.upload.wait_for_upload_port=true

esp32.serial.disableDTR=true
esp32.serial.disableRTS=true

esp32.build.mcu=esp32
esp32.build.core=esp32
esp32.build.variant=esp32
esp32.build.board=ESP32_DEV

esp32.build.f_cpu=240000000L
esp32.build.flash_size=4MB
esp32.build.flash_freq=40m
esp32.build.flash_mode=dio
esp32.build.boot=dio
esp32.build.partitions=default
esp32.build.defines=

esp32.menu.PSRAM.disabled=Disabled
esp32.menu.PSRAM.disabled.build.defines=
esp32.menu.PSRAM.enabled=Enabled
esp32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32.menu.PartitionScheme.default.build.partitions=default
esp32.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336
esp32.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32.menu.PartitionScheme.minimal.build.partitions=minimal
esp32.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32.menu.PartitionScheme.fatflash.build.partitions=ffat
esp32.menu.PartitionScheme.fatflash.upload.maximum_size=2097152
esp32.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9MB FATFS)
esp32.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB
esp32.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728

esp32.menu.CPUFreq.240=240MHz (WiFi/BT)
esp32.menu.CPUFreq.240.build.f_cpu=240000000L
esp32.menu.CPUFreq.160=160MHz (WiFi/BT)
esp32.menu.CPUFreq.160.build.f_cpu=160000000L
esp32.menu.CPUFreq.80=80MHz (WiFi/BT)
esp32.menu.CPUFreq.80.build.f_cpu=80000000L
esp32.menu.CPUFreq.40=40MHz (40MHz XTAL)
esp32.menu.CPUFreq.40.build.f_cpu=40000000L
esp32.menu.CPUFreq.26=26MHz (26MHz XTAL)
esp32.menu.CPUFreq.26.build.f_cpu=26000000L
esp32.menu.CPUFreq.20=20MHz (40MHz XTAL)
esp32.menu.CPUFreq.20.build.f_cpu=20000000L
esp32.menu.CPUFreq.13=13MHz (26MHz XTAL)
esp32.menu.CPUFreq.13.build.f_cpu=13000000L
esp32.menu.CPUFreq.10=10MHz (40MHz XTAL)
esp32.menu.CPUFreq.10.build.f_cpu=10000000L

esp32.menu.FlashMode.qio=QIO
esp32.menu.FlashMode.qio.build.flash_mode=dio
esp32.menu.FlashMode.qio.build.boot=qio
esp32.menu.FlashMode.dio=DIO
esp32.menu.FlashMode.dio.build.flash_mode=dio
esp32.menu.FlashMode.dio.build.boot=dio
esp32.menu.FlashMode.qout=QOUT
esp32.menu.FlashMode.qout.build.flash_mode=dout
esp32.menu.FlashMode.qout.build.boot=qout
esp32.menu.FlashMode.dout=DOUT
esp32.menu.FlashMode.dout.build.flash_mode=dout
esp32.menu.FlashMode.dout.build.boot=dout

esp32.menu.FlashFreq.80=80MHz
esp32.menu.FlashFreq.80.build.flash_freq=80m
esp32.menu.FlashFreq.40=40MHz
esp32.menu.FlashFreq.40.build.flash_freq=40m

esp32.menu.FlashSize.4M=4MB (32Mb)
esp32.menu.FlashSize.4M.build.flash_size=4MB
esp32.menu.FlashSize.8M=8MB (64Mb)
esp32.menu.FlashSize.8M.build.flash_size=8MB
esp32.menu.FlashSize.8M.build.partitions=default_8MB
esp32.menu.FlashSize.2M=2MB (16Mb)
esp32.menu.FlashSize.2M.build.flash_size=2MB
esp32.menu.FlashSize.2M.build.partitions=minimal
esp32.menu.FlashSize.16M=16MB (128Mb)
esp32.menu.FlashSize.16M.build.flash_size=16MB

esp32.menu.UploadSpeed.921600=921600
esp32.menu.UploadSpeed.921600.upload.speed=921600
esp32.menu.UploadSpeed.115200=115200
esp32.menu.UploadSpeed.115200.upload.speed=115200
esp32.menu.UploadSpeed.256000.windows=256000
esp32.menu.UploadSpeed.256000.upload.speed=256000
esp32.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32.menu.UploadSpeed.230400=230400
esp32.menu.UploadSpeed.230400.upload.speed=230400
esp32.menu.UploadSpeed.460800.linux=460800
esp32.menu.UploadSpeed.460800.macosx=460800
esp32.menu.UploadSpeed.460800.upload.speed=460800
esp32.menu.UploadSpeed.512000.windows=512000
esp32.menu.UploadSpeed.512000.upload.speed=512000

esp32.menu.DebugLevel.none=None
esp32.menu.DebugLevel.none.build.code_debug=0
esp32.menu.DebugLevel.error=Error
esp32.menu.DebugLevel.error.build.code_debug=1
esp32.menu.DebugLevel.warn=Warn
esp32.menu.DebugLevel.warn.build.code_debug=2
esp32.menu.DebugLevel.info=Info
esp32.menu.DebugLevel.info.build.code_debug=3
esp32.menu.DebugLevel.debug=Debug
esp32.menu.DebugLevel.debug.build.code_debug=4
esp32.menu.DebugLevel.verbose=Verbose
esp32.menu.DebugLevel.verbose.build.code_debug=5

##############################################################

esp32wrover.name=ESP32 Wrover Module

esp32wrover.upload.tool=esptool_py
esp32wrover.upload.maximum_size=1310720
esp32wrover.upload.maximum_data_size=327680
esp32wrover.upload.wait_for_upload_port=true

esp32wrover.serial.disableDTR=true
esp32wrover.serial.disableRTS=true

esp32wrover.build.mcu=esp32
esp32wrover.build.core=esp32
esp32wrover.build.variant=esp32
esp32wrover.build.board=ESP32_DEV

esp32wrover.build.f_cpu=240000000L
esp32wrover.build.flash_size=4MB
esp32wrover.build.flash_freq=40m
esp32wrover.build.flash_mode=dio
esp32wrover.build.boot=dio
esp32wrover.build.partitions=default
esp32wrover.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32wrover.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32wrover.menu.PartitionScheme.default.build.partitions=default
esp32wrover.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32wrover.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32wrover.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32wrover.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32wrover.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32wrover.menu.PartitionScheme.minimal.build.partitions=minimal
esp32wrover.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32wrover.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32wrover.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32wrover.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32wrover.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32wrover.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32wrover.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32wrover.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32wrover.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32wrover.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32wrover.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32wrover.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32wrover.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32wrover.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32wrover.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32wrover.menu.PartitionScheme.fatflash.build.partitions=ffat

esp32wrover.menu.FlashMode.qio=QIO
esp32wrover.menu.FlashMode.qio.build.flash_mode=dio
esp32wrover.menu.FlashMode.qio.build.boot=qio
esp32wrover.menu.FlashMode.dio=DIO
esp32wrover.menu.FlashMode.dio.build.flash_mode=dio
esp32wrover.menu.FlashMode.dio.build.boot=dio
esp32wrover.menu.FlashMode.qout=QOUT
esp32wrover.menu.FlashMode.qout.build.flash_mode=dout
esp32wrover.menu.FlashMode.qout.build.boot=qout
esp32wrover.menu.FlashMode.dout=DOUT
esp32wrover.menu.FlashMode.dout.build.flash_mode=dout
esp32wrover.menu.FlashMode.dout.build.boot=dout

esp32wrover.menu.FlashFreq.80=80MHz
esp32wrover.menu.FlashFreq.80.build.flash_freq=80m
esp32wrover.menu.FlashFreq.40=40MHz
esp32wrover.menu.FlashFreq.40.build.flash_freq=40m

esp32wrover.menu.UploadSpeed.921600=921600
esp32wrover.menu.UploadSpeed.921600.upload.speed=921600
esp32wrover.menu.UploadSpeed.115200=115200
esp32wrover.menu.UploadSpeed.115200.upload.speed=115200
esp32wrover.menu.UploadSpeed.256000.windows=256000
esp32wrover.menu.UploadSpeed.256000.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400=230400
esp32wrover.menu.UploadSpeed.230400.upload.speed=230400
esp32wrover.menu.UploadSpeed.460800.linux=460800
esp32wrover.menu.UploadSpeed.460800.macosx=460800
esp32wrover.menu.UploadSpeed.460800.upload.speed=460800
esp32wrover.menu.UploadSpeed.512000.windows=512000
esp32wrover.menu.UploadSpeed.512000.upload.speed=512000

esp32wrover.menu.DebugLevel.none=None
esp32wrover.menu.DebugLevel.none.build.code_debug=0
esp32wrover.menu.DebugLevel.error=Error
esp32wrover.menu.DebugLevel.error.build.code_debug=1
esp32wrover.menu.DebugLevel.warn=Warn
esp32wrover.menu.DebugLevel.warn.build.code_debug=2
esp32wrover.menu.DebugLevel.info=Info
esp32wrover.menu.DebugLevel.info.build.code_debug=3
esp32wrover.menu.DebugLevel.debug=Debug
esp32wrover.menu.DebugLevel.debug.build.code_debug=4
esp32wrover.menu.DebugLevel.verbose=Verbose
esp32wrover.menu.DebugLevel.verbose.build.code_debug=5

As I guess you mean the preprocessor defines to distinguish between different boards and include/exclude based on this different code parts.In ArduinoIDE except from
 #ifdef ESP32
 const uint8_t pinA = 12;
 #endif

no luck as of core 1.04, because there are no preproc macros defined (like in other architectures).If you are using PlatformIO you can get the board type from the define ARDUINO_BOARD.
On ArduinoIDE you only can write your own macros (but this only solves the problem for your dev environment)
So as of core 1.04 you can only do it manually by un/commenting defines:
/** Choose the correct model to use and compile the right pin settings*/
#define AI_THINKER_KIT
//#define WROVER_DEV_KIT
//#define ESP_EYE_32
//#define M5STACK_PSRAM
//#define M5STACK_NO_PSRAM

As an example the build.board property for SAM Boards is:
adafruit_itsybitsy_m0.build.board=ITSYBITSY_M0

Then in the Adafruit SAMD Boards platform.txt file you can see where the macro is defined:
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

If you want to dig intoit deeper: Arduino 3rd party hardware documantatuion

Yes that is exactly what I want it for.
I will have to do it manually. Thank you for your response

Please mark the answer as accepted


text:
Why can the Xbox360 not detect the Arduino Leonardo as keyboard?
Arduino Leonardo as keyboard in the computer works! But not with the Xbox360.
The Teensy works perfectly on the PC but how to emulate a keyboard device for the Xbox360.
I know the Xbox360 has security IC, but a simple USB keyboard works!
What is the diference ?
How i can emulate an usb keyboard for the Xbox360?

It probably needs the "Boot Keyboard" protocol, which the Leonardo doesn't provide.

I very new to hid devices, i will find out about that

does leonardo work as a keyboard at boot time in BIOS?

i don't remember, i guess no, but i will try later!

@jsotola, it doesn't work as boot keyboard with Arduino Keyboard library. this library can emulate boot keyboard on Leonardo: https://github.com/NicoHood/HID

Like Juraj and Majenko said. Arduino Keyboard library does emulate "Boot Keyboard".
I use NicoHood HID library and now it works.


text:
How to get the free/used space on a SD card and transmit it
I'm using this block of code to read and sum up the bytes of all the text files I have on an SD card:
long get_sd_memory_taken() {
  File dir = SD.open("/");
  long sd_memory_taken;
  int c = 0;
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      return sd_memory_taken;
      break;
    }
    if(strcmp(entry.name(), "SYSTEM~1") == 0) {
      continue;
    }
    if(c > 15) {
      tft.println(entry.name());
      tft.println(entry.size());
    }
    sd_memory_taken += entry.size();
    entry.close();
    c++;
  }
}

The SD card is 8GB so the number won't be larger than 8,589,934,592. The function get_sd_memory_taken() returns the number so it can be send to a phone using Bluetooth. I just checked that long can hold max 2,147,483,647, so if the SD card is filled more than that, I suppose errors are gonna appear. How can I prevent this? I was thinking of maybe using a double and put the comma maybe 5 digits to the left and send that or maybe divide the number into 10 smaller longs and send them to the phone separately. I think the former method is better but I'm not sure if it'll work. What's the best way to go about this problem where I'm trying to use as less memory as possible?

What Arduino (and SD lib) are you using?

unsigned long long aka uint64_t can hold up to 9,223,372,036,854,775,807.

@Codebreaker007 Blue Pill, SD.h

@Majenko I'll try that, hopefully that's the most memory-efficient way to do it

8 bytes is all that uses. Same a double.

for a lot of arduino boards, a double is 32 bits (synonymous to float).  just be aware if you run into this here when working a different board.

As SD.h includes
  #include "utility/SdFat.h"
  #include "utility/SdFatUtil.h"

or if you use the SDfat library than this function is more efficient than going all over the place:
#include <SdFat.h>

SdFat SD;

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = SD.vol()->freeClusterCount();
  lFreeKB *= SD.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}


text:
Reading from SPIFFS - What's the best way to deal with a string (or char) array with undefined length?
I've read that it's best to avoid using String in Arduino so I'm ready to use a char array if it's better.
I'm reading the file names from an SD Card and my goal is to store them in an array and then be able to read that array. What I'm currently doing is:
String lib_arr[100];
int lib_arr_size;

and then
File dir = SD.open("/");
int c = 0;
while (true) {
  File entry = dir.openNextFile();
  if (!entry) {
    // If no more files
    lib_arr_size = c - 1;
    break;
  }
  if(strcmp(entry.name(), "SYSTEM~1") == 0) {
    continue;
  }
  lib_arr[c] = entry.name();
  entry.close();
  c++;
}

and then
for (int i = 0; i < lib_arr_size; i++) {
  if(i == pos) {
    tft.print("> ");
    tft.println(lib_arr[i]);
  } else {
    tft.println(lib_arr[i]);
  }
}

This is not a solution because, for my purposes, the String lib_arr[100] can be 1000 or 10000 or 100000... and I found out that by increasing that value the global variables use skyrockets and Arduino says that it's out of memory. My goal is memory optimization. I don't know how to go about this problem.

read and print/process in one go. don't store the list in memory. here I have a SD browser https://github.com/jandrassy/lab/blob/master/SDWebServer/SDWebServer.ino

@Juraj That's a great idea! But when I'm browsing, whenever I go up or down to select different files, I would have to each time go to the SD card and get the files. Wouldn't that be bad for the memory? Is it a good practice? Is it better than storing in array?

The SD library uses these old "DOS" file names in 8.3 format, with automatic renaming. This a) limits the required size and b) makes it useless to deal with 10,000 files at once, as they will have unrecognizable names...

you don't have the RAM to cache the names. but you have time to load them. on a MCU with more RAM you could cache some last seen folder, but this would be premature optimization and that is the root of all evil in coding. https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize

@Juraj So I should get and read the file names on every file select?

why not? it is not slow and doesn't consume anything

@Juraj Got it. Thank you!

Please look into the SPIFFS/ LittleFS library. You will see that the length of a filename (in those file systems it includes the path and the root indicator "/" as well as the extension .XXXXX as in .shtml ).
The maximum length defined in the libs is 32 as max length this means 31 chars to use + 1 terminator. To all the wise guys claiming you can change that (Yes you can but you should not). Do not do it - there are reasons for that. Read more.The maximum files is defined by blocksize and howlargeyou defined your SPIFFS partition.
There is no difference between writing to SPIFFs or a SD card both have around 100.000 r/w cycles per individual physical "cell" Sometimes it is cheaper to get a new ESP than a SDcard.
The question of the OP: As long as you read its no problem to do it often if you do mass renames you might have a problem after some time. What you do is actually partly copying what the libs do - so utterly obsolete. Speed is the same because its the same flash memory anyway (+ your processing overhead). You do not really have directories its a flat table system, so searching for path beginning with or containing (combined with a clever read strategy) can be done on the fly without problems. If you need data elsewhere (browser) filter & stream it - do not make in between storage (=duplication) with the small memory
As a final thought from the tech specs:

The main complication writing spiffs was that it cannot be assumed
  the target has a heap. Spiffs must go along only with the work ram
  buffer given to it.  This forces extra implementation on many areas of
  spiffs. ....
SPI flash devices are physically divided in blocks. On some SPI flash
  devices, blocks are further divided into sectors. Datasheets sometimes
  name blocks as  sectors and vice versa.
Common memory capacaties for SPI flashes are 512kB up to 8MB of data,
  where blocks may be 64kB. Sectors can be e.g. 4kB, if supported. Many
  SPI flashes  have uniform block sizes, whereas others have non-uniform
  - the latter meaning  that e.g. the first 16 blocks are 4kB big, and the rest are 64kB.
The entire memory is linear and can be read and written in random
  access.  Erasing can only be done block- or sectorwise; or by mass
  erase.

Well, you cannot use more memory than you have. If the length of file names is (probably/possibly) too much, you just cannot store it in memory. Some alternatives:

Use some compression... This will save you a bit, but at the end if you don't know how much the maximum bytes you need to store is, it will not help much
Use external SRAM memory... You need to write your own memory functions. Also a slight performance hit.
Use SD card memory... As SRAM, but much slower. Also not sure if you can use the same SD card to write on.
The best solution, but could be a big performance hit, is not to store at all the file names, but go through the file names and process what you need along the way. This is not always possible or feasible though. In your solution you can print the file names directly without storing (but I guess you want to do some additional processing).

The user can create 10000 files with a single character in each for example.

I can imagine, but you still cannot put all those file names in memory. You need either external memory or process them as you go through each file (without storing inbetween data/results).


text:
STM32 and SDFat - Can't create file in directory in SD
I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using SD.open("test.txt", FILE_WRITE); but my code fails to create SD.open("DATA/data_test.txt", FILE_WRITE); in a directory.
Here's the piece of code that successfully creates a file in the root:
String final_book_name = upload_book_name + ".txt";
if (SD.exists(final_book_name.c_str())) {
  SD.remove(final_book_name.c_str());
}
tft.println(final_book_name); // This successfully prints "test.txt"
book_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name.c_str())) {
  tft.print("Created file");
} else {
  tft.print("Failed to create/replace\nfile!");
}

and here's the piece of the code that fails to create a file in a directory:
if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
}
String final_book_name = upload_book_name + ".txt";
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;
if (SD.exists(book_data_path.c_str())) {
  SD.remove(book_data_path.c_str());
}
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(book_data_path, FILE_WRITE);
if (SD.exists(book_data_path.c_str())) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name.c_str())) {
    SD.remove(final_book_name.c_str());
  }
}

Try it with /DATA/test.txt I remember SD library uses the classic 8.3 filenames and data_test.txt is invalid

@DataFiddler I'm using SdFat.h with Long Names (which allows names up to 255 characters)

I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.
UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.

As you have given no variable for DATA_DIR
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;

so your resulting path looks like
DATA_DIR + "/data_" + final_book_name

IF DATA_DIR = "/" then it would be "/" + "/data_" + final_book_name
As tip do not use the string class but char arrays
definition
 const char[] DATA_DIR = "/books";
 char book_data_path [128] = {'\0'};
 char final_book_name [13] =  {'\0'}; // IF no LFN support is used its 8.3 !!!
 const char upload_book_name[] = "my_book";
 strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt");
 Serial.println(final_book_name);

If you want long filr namesupport us SDFat library or enable LFB withSD lib (whichneeds about 35% ,ore memory as SDfat (when using long file names).
EDITAs you are using SDFat and I do not know which version/fork there is abug with writing to subdirectories. Please check the following:
To check run the SdFat\examples\DirectoryFunctions and watch your serial monitor for the results
SdFile.cpp. At line 782 and 1452, you have (in my version):
if (block <= m_vol->cacheBlockNumber()
  && block < (m_vol->cacheBlockNumber() + nb)) {

The working code has:
if (m_vol->cacheBlockNumber() <= block
  && block < (m_vol->cacheBlockNumber() + nBlock)) {

If you have the upper version change it and it should work
EDIT 2 Work around for buggy SDFat lib
Here is a workaround code
const char DATA_DIR [] = "data";
char final_book_name[128] ={'\0'};
char book_data_path [256] ={'\0'};

if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
  SD.chdir(DATA_DIR);
}

strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt";
String book_data_path = DATA_DIR;

strcpy(book_data_path, "data_");
strcat(book_data_path, final_book_name);

if (SD.exists(book_data_path)) {
  SD.remove(book_data_path);
}
SD.mkdir(book_data_path);
SD.chdir(book_data_path);

tft.println(DATA_DIR);
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name)) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name)) {
    SD.remove(final_book_name);
  }
}

DATA_DIR is "DATA". I don't see the solution in your answer. I will make my Strings to characters, that's a good idea but what about my main issue here?

Sorry, it's still unclear to me what I should do. I'm using STM32, not an Arduino and I don't have a Serial Monitor. I will try downloading a newer SdFat version.

I downloaded the newest version of SdFat from here: https://github.com/greiman/SdFat and ran it, but it still fails to create a file in a subdirectory

I could try to do SD.chdir(DATA_DIR); but I'm not sure how that works exactly and if even that's the problem. I don't think SD.chdir(DATA_DIR); is necessary

I tried with SD.chdir(DATA_DIR); (as far as I know how to use it) but it failed. (it created the file in the root, not in the dir)

Use my EDIT 2 leave it for the moment as it is

"As you do not want to fix your obviously buggy SD.lib" I've never said that. How do I fix it, I don't have serial monitor?

Sorry for my cynism. But you reveal info step by step which should be in you question from the beginning.On the stm32you will have to rewrite the progfor your Tft. So have you tested the work around.On an STM32 the lib isknown to give problems

I have no idea what you're talking about. Thanks for trying to help me out. I will look at the code you posted and I'll try to implement some parts of it tomorrow. Thanks for the help.


text:
NodeMCU Server side cannot send things to client side - multiple clients attached
I technically need your help, when I am working on my project, I found out that my server-side cannot send data to the client-side, my server-side is made with WiFiServer(80) so it is when my client-side do client.print, it can send to the server-side, and the server-side just easily send to the Python side with Serial, and Python can still send it to the server-side, but the server-side cannot send it to the client-side.  The basic code is from this page

Server Code

Here's the code:
#include <SPI.h>
#include <ESP8266WiFi.h>
#define led LED_BUILTIN
char ssid[] = "AP";
char pass[] = "Science_Fair";
WiFiServer server(80);
WiFiClient client;
IPAddress ip(10, 241, 241, 27);
IPAddress gateway(10, 241, 241, 254);
IPAddress subnet(255, 255, 255, 0);
int i;

void setup()
{
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(100);
  }
  // Serial.println("Connected to WiFi");
  server.begin();
  pinMode(led, OUTPUT);
}

void loop()
{
  client = server.available();
  client.setTimeout(3000);
  Serial.setTimeout(2000);
  if (client)
  {

    // Serial.println("Available");
    if (client.connected())
    {
      Serial.println("Connected");
    }

    while (client.connected())
    {
      // Serial.println(".");

      String request = client.readStringUntil('e');
      if (request == "LR")
      {
        digitalWrite(led, LOW);
        Serial.println("LR");
        for (i = 0; i < 3; i++)
        {
          String reply = Serial.readStringUntil('e');
          if (reply == "WARN_B")
          {
            Serial.println("Confirm");
            client.print("WARN_Be");
            break;
          }
          yield();
        }
      }
      else if (request == "RR")
      {
        Serial.println("RR");
        for (i = 0; i < 3; i++)
        {
          String reply = Serial.readStringUntil('e');
          yield();
          if (reply == "WARN_A")
          {
            Serial.println("Confirm");
            client.print("WARN_Ae");
            break;
          }
          yield();
        }
        yield();
      }
      yield();
    }
  }
  // Serial.println("");
  client.stop();
}

Client A Code

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <DFPlayer_Mini_Mp3.h>
#define PIR_A D3
#define PIR_B D8
#define led LED_BUILTIN
const char ssid[] = "AP";
const char pass[] = "Science_Fair";
SoftwareSerial DFPlayer_Mini(D1, D2);
WiFiClient client;
IPAddress server(10, 241, 241, 27);
IPAddress ip(10, 241, 241, 28);
IPAddress gateway(10, 241, 241, 254);
IPAddress subnet(255, 255, 255, 0);

void setup()
{
    pinMode(PIR_A, INPUT);
    pinMode(PIR_B, INPUT);
    pinMode(led, OUTPUT);
    DFPlayer_Mini.begin(9600);
    mp3_set_serial(DFPlayer_Mini);
    mp3_set_volume(30);
    WiFi.mode(WIFI_STA);
    WiFi.config(ip, gateway, subnet);
    WiFi.begin(ssid, pass);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(100);
    }
    Serial.begin(9600);
}

void loop()
{
    int i;
    float time = 0;
    int PIR_A_VAL = digitalRead(PIR_A);
    int PIR_B_VAL = digitalRead(PIR_B);
    client.connect(server, 80);
    client.setTimeout(1500);
    if (PIR_A_VAL == HIGH)
    {
        while (1)
        {
            time += 1;
            delay(1);
            if (time >= 1000)
            {
                Serial.println("OFD");
                for (i = 0; i < 40; i++)
                {
                    delay(100);
                    yield();
                }
                break;
            }
            else if (PIR_B_VAL == HIGH)
            {
                if (time == 1)
                {
                    client.print("RRe");
                    client.flush();
                    for (i = 0; i < 40; i++)
                    {
                        delay(100);
                        yield();
                    }
                    break;
                }
                break;
            }
            PIR_B_VAL = digitalRead(PIR_B);
            yield();
        }
    }
    else if (PIR_B_VAL == HIGH)
    {
        String fromServer = client.readStringUntil('e');
        yield();
        if (fromServer == "WARN_A")
        {
            mp3_play();
        }
        Serial.println("B Triggered");
        for (i = 0; i < 2; i++)
        {
            delay(1250);
            yield();
        }
    }
    Serial.println("OFL");
    client.stop();
}

Client B Code

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <DFPlayer_Mini_Mp3.h>
#define PIR_A D7
#define PIR_B D8
#define led LED_BUILTIN
const char ssid[] = "AP";
const char pass[] = "Science_Fair";
SoftwareSerial DFPlayer_Mini(D1, D2);
WiFiClient client;
IPAddress server(10, 241, 241, 27);
IPAddress ip(10, 241, 241, 29);
IPAddress gateway(10, 241, 241, 254);
IPAddress subnet(255, 255, 255, 0);

void setup()
{
    pinMode(PIR_A, INPUT);
    pinMode(PIR_B, INPUT);
    pinMode(led, OUTPUT);
    DFPlayer_Mini.begin(9600);
    mp3_set_serial(DFPlayer_Mini);
    mp3_set_volume(30);
    WiFi.mode(WIFI_STA);
    WiFi.config(ip, gateway, subnet);
    WiFi.begin(ssid, pass);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(100);
    }
    Serial.begin(9600);
}

void loop()
{
    int i;
    float time = 0;
    int PIR_A_VAL = digitalRead(PIR_A);
    int PIR_B_VAL = digitalRead(PIR_B);
    client.connect(server, 80);
    client.setTimeout(1500);
    if (PIR_A_VAL == HIGH)
    {
        while (1)
        {
            time += 1;
            delay(1);
            if (time >= 1000)
            {
                Serial.println("OFD");
                for (i = 0; i < 40; i++)
                {
                    delay(100);
                    yield();
                }
                break;
            }
            else if (PIR_B_VAL == HIGH)
            {
                if (time == 1)
                {
                    client.print("LRe");
                    client.flush();
                    for (i = 0; i < 40; i++)
                    {
                        delay(100);
                        yield();
                    }
                    break;
                }
                break;
            }
            PIR_B_VAL = digitalRead(PIR_B);
            yield();
        }
    }
    else if (PIR_B_VAL == HIGH)
    {
        String warnStatus = client.readStringUntil('e');
        yield();
        if (warnStatus == "WARN_B")
        {
            mp3_play();
        }
        Serial.println("B Triggered");
        for (i = 0; i < 2; i++)
        {
            delay(1250);
            yield();
        }
    }
    Serial.println("OFL");
    client.stop();
}

I've tried:
 - Using client.print instead of client.printf
 - Using data with underlines instead of spaces
 - Added client.flush
 - Added client.stop
 - Changed NodeMCU
 - Checked wires
 - Checked power supply
 - Checked the data to send
 - Made the timeout longer
 - Checked speaker
But none of them is working
Please help me guys I'm in a rush, thank you!

try to create a minimal reproducible example without workaround attempts

@Juraj I already did that tho, it is working, but I couldn't solve the problem with that way

And it is almost the same tbh ( I found one, not coded one )

The link is here, I used this guy's example

the code in the instructable is nice and clean. why is yours so cluttered?

@Juraj uh technically I need to add a lot of things some HC-SR501 and a lot of things

I read through the instructable and found - hidden in the comments the following

Author of the instructable:  Would you like to send message to the
  four clients in the same time?
If it is right I can not support you. I am not a expert in this topic.
  My server sends message to the current client only which is triggering
  the server. Using my sketch you can send same message to the clients,
  but in different time. (Remark codebreaker007: which would not work anyway!)

So this solution you have in your code is supposed to work with only one client. So you have to implement yourself a kind of com-sequence wether sever triggered or client side.
Here a short how to add this functionality:
#define MAX_SRV_CLIENTS 4 // max clients connecting

WiFiClient serverClients[MAX_SRV_CLIENTS];

in the loop do the following:
  uint8_t i;
 for (i = 0; i < MAX_SRV_CLIENTS; i++) {
  //check if there are any new clients
  if (server.hasClient()) {
 //find free/disconnected client spot
  if (!serverClients[i] || !serverClients[i].connected()) {
    if (serverClients[i]) serverClients[i].stop();
    serverClients[i] = server.available();
    Serial.print("New client: "); Serial.print(i);
    break;
  }
 }

So you can differentiate between the clients and send with for loop to all or
 serverClients[2].print("WARN Client 2");

Hope this resolves the issue (And read also comments of instructables about problems - the author is actually a newbie)

Uh sorry I couldn't understand you, do you mean by that I need to give it a few more code to it so it can work with more than one client?

YES your solution is only for one client!

Oh man tks, this freacking problem has taken me over a month, deeply thank you

But I am at home now, I can only test at my lab, so I'll test it tmr, tks

I've already given you best answer!

WAIT! No need for WiFiServer?

#include <ESP8266WiFi.h>  look into the library examples, this lib supports client and server code

Sorry my brain was dead haha tks bro

the code in the instructable takes the current client, handles it, closes the connection and forgets the client. then it can handle the next client.

This does not help the OP if he wants to do Server initiated communication with two or more clients attached at the same time