text:
ESP12E Soft WDT reset stack trace leads to libraries
Im using ESP12E DevKit v2 (esp8266 wifi module) board for controlling relays and displaying DHT22 temp,humidity on web server.
It runs smoothly when the web client is closed but when i leave the website on for like a 20mins it crashes.
I have installed the ESPdecoder and the stack trace always leads mostly to libraries. I tried using
  ESP.wdtDisable();
   ESP.wdtEnable(WDTO_8S); commands and yield(); function but doesnt make any difference.
How can i fix this or what am i doing wrong in the code?
Soft WDT reset

>>>stack>>>

ctx: sys
sp: 3fffed40 end: 3fffffb0 offset: 01b0
3fffeef0:  3ffe93dc c84524b8 60000600 4020ea06
3fffef00:  00000000 3ffeda08 00000000 00000000
3fffef10:  4022d488 3ffeda08 3ffee9c0 60000600
3fffef20:  4022fdd1 3ffeda08 3ffee9c0 c84550ad
3fffef30:  4022fe16 3fffdab0 00000000 3fffdcb0
3fffef40:  3ffee9d0 3fffdab0 00000000 40206223
3fffef50:  40000f49 40000f49 3fffdab0 40000f49
3fffef60:  40000e19 40001878 00000002 00000000
3fffef70:  3fffff10 aa55aa55 000000f0 40104ba0
3fffef80:  40104ba6 00000002 00000000 3715d4f6
3fffef90:  4010000d 0e060f10 942b6d57 69e0d507
3fffefa0:  40100b40 3fffef3c 40100aed 3ffffea8
3fffefb0:  3fffffc0 00000000 00000000 feefeffe
3fffefc0:  feefeffe feefeffe feefeffe feefeffe
3fffefd0:  feefeffe feefeffe feefeffe feefeffe
3fffefe0:  feefeffe feefeffe feefeffe feefeffe
3fffeff0:  feefeffe feefeffe feefeffe feefeffe
3ffff000:  feefeffe feefeffe feefeffe feefeffe
3ffff010:  feefeffe feefeffe feefeffe feefeffe
3ffff020:  feefeffe feefeffe feefeffe feefeffe
3ffff030:  feefeffe feefeffe feefeffe feefeffe
3ffff040:  feefeffe feefeffe feefeffe feefeffe
3ffff050:  feefeffe feefeffe feefeffe feefeffe
3ffff060:  feefeffe feefeffe feefeffe feefeffe
3ffff070:  feefeffe feefeffe feefeffe feefeffe
3ffff080:  feefeffe feefeffe feefeffe feefeffe
3ffff090:  feefeffe feefeffe feefeffe feefeffe
3ffff0a0:  feefeffe feefeffe feefeffe feefeffe
3ffff0b0:  feefeffe feefeffe feefeffe feefeffe
3ffff0c0:  feefeffe feefeffe feefeffe feefeffe
3ffff0d0:  feefeffe feefeffe feefeffe feefeffe
3ffff0e0:  feefeffe feefeffe feefeffe feefeffe
3ffff0f0:  feefeffe feefeffe feefeffe feefeffe
3ffff100:  feefeffe feefeffe feefeffe feefeffe
3ffff110:  feefeffe feefeffe feefeffe feefeffe
3ffff120:  feefeffe feefeffe feefeffe feefeffe
3ffff130:  feefeffe feefeffe feefeffe feefeffe
3ffff140:  feefeffe feefeffe feefeffe feefeffe
3ffff150:  feefeffe feefeffe feefeffe feefeffe
3ffff160:  feefeffe feefeffe feefeffe feefeffe
3ffff170:  feefeffe feefeffe feefeffe feefeffe
3ffff180:  feefeffe feefeffe feefeffe feefeffe
3ffff190:  feefeffe feefeffe feefeffe feefeffe
3ffff1a0:  feefeffe feefeffe feefeffe feefeffe
3ffff1b0:  feefeffe feefeffe feefeffe feefeffe
3ffff1c0:  feefeffe feefeffe feefeffe feefeffe
3ffff1d0:  feefeffe feefeffe feefeffe feefeffe
3ffff1e0:  feefeffe feefeffe feefeffe feefeffe
3ffff1f0:  feefeffe feefeffe feefeffe feefeffe
3ffff200:  feefeffe feefeffe feefeffe feefeffe
3ffff210:  feefeffe feefeffe feefeffe feefeffe
3ffff220:  feefeffe feefeffe feefeffe feefeffe
3ffff230:  feefeffe feefeffe feefeffe feefeffe
3ffff240:  feefeffe feefeffe feefeffe feefeffe
3ffff250:  feefeffe feefeffe feefeffe feefeffe
3ffff260:  feefeffe feefeffe feefeffe feefeffe
3ffff270:  feefeffe feefeffe feefeffe feefeffe
3ffff280:  feefeffe feefeffe feefeffe feefeffe
3ffff290:  feefeffe feefeffe feefeffe feefeffe
3ffff2a0:  feefeffe feefeffe feefeffe feefeffe
3ffff2b0:  feefeffe feefeffe feefeffe feefeffe
3ffff2c0:  feefeffe feefeffe feefeffe feefeffe
3ffff2d0:  feefeffe feefeffe feefeffe feefeffe
3ffff2e0:  feefeffe feefeffe feefeffe feefeffe
3ffff2f0:  feefeffe feefeffe feefeffe feefeffe
3ffff300:  feefeffe feefeffe feefeffe feefeffe
3ffff310:  feefeffe feefeffe feefeffe feefeffe
3ffff320:  feefeffe feefeffe feefeffe feefeffe
3ffff330:  feefeffe feefeffe feefeffe feefeffe
3ffff340:  feefeffe feefeffe feefeffe feefeffe
3ffff350:  feefeffe feefeffe feefeffe feefeffe
3ffff360:  feefeffe feefeffe feefeffe feefeffe
3ffff370:  feefeffe feefeffe feefeffe feefeffe
3ffff380:  feefeffe feefeffe feefeffe feefeffe
3ffff390:  feefeffe feefeffe feefeffe feefeffe
3ffff3a0:  feefeffe feefeffe feefeffe feefeffe
3ffff3b0:  feefeffe feefeffe feefeffe feefeffe
3ffff3c0:  feefeffe feefeffe feefeffe feefeffe
3ffff3d0:  feefeffe feefeffe feefeffe feefeffe
3ffff3e0:  feefeffe feefeffe feefeffe feefeffe
3ffff3f0:  feefeffe feefeffe feefeffe feefeffe
3ffff400:  feefeffe feefeffe feefeffe feefeffe
3ffff410:  feefeffe feefeffe feefeffe feefeffe
3ffff420:  feefeffe feefeffe feefeffe feefeffe
3ffff430:  feefeffe feefeffe feefeffe feefeffe
3ffff440:  feefeffe feefeffe feefeffe feefeffe
3ffff450:  feefeffe feefeffe feefeffe feefeffe
3ffff460:  feefeffe feefeffe feefeffe feefeffe
3ffff470:  feefeffe feefeffe feefeffe feefeffe
3ffff480:  feefeffe feefeffe feefeffe feefeffe
3ffff490:  feefeffe feefeffe feefeffe feefeffe
3ffff4a0:  feefeffe feefeffe feefeffe feefeffe
3ffff4b0:  feefeffe feefeffe feefeffe feefeffe
3ffff4c0:  feefeffe feefeffe feefeffe feefeffe
3ffff4d0:  feefeffe feefeffe feefeffe feefeffe
3ffff4e0:  feefeffe feefeffe feefeffe feefeffe
3ffff4f0:  feefeffe feefeffe feefeffe feefeffe
3ffff500:  feefeffe feefeffe feefeffe feefeffe
3ffff510:  feefeffe feefeffe feefeffe feefeffe
3ffff520:  feefeffe feefeffe feefeffe feefeffe
3ffff530:  feefeffe feefeffe feefeffe feefeffe
3ffff540:  feefeffe feefeffe feefeffe feefeffe
3ffff550:  feefeffe feefeffe feefeffe feefeffe
3ffff560:  feefeffe feefeffe feefeffe feefeffe
3ffff570:  feefeffe feefeffe feefeffe feefeffe
3ffff580:  feefeffe feefeffe feefeffe feefeffe
3ffff590:  feefeffe feefeffe feefeffe feefeffe
3ffff5a0:  feefeffe feefeffe feefeffe feefeffe
3ffff5b0:  feefeffe feefeffe feefeffe feefeffe
3ffff5c0:  feefeffe feefeffe feefeffe feefeffe
3ffff5d0:  feefeffe feefeffe feefeffe feefeffe
3ffff5e0:  feefeffe feefeffe feefeffe feefeffe
3ffff5f0:  feefeffe feefeffe feefeffe feefeffe
3ffff600:  feefeffe feefeffe feefeffe feefeffe
3ffff610:  feefeffe feefeffe feefeffe feefeffe
3ffff620:  feefeffe feefeffe feefeffe feefeffe
3ffff630:  feefeffe feefeffe feefeffe feefeffe
3ffff640:  feefeffe feefeffe feefeffe feefeffe
3ffff650:  feefeffe feefeffe feefeffe feefeffe
3ffff660:  feefeffe feefeffe feefeffe feefeffe
3ffff670:  feefeffe feefeffe feefeffe feefeffe
3ffff680:  feefeffe feefeffe feefeffe feefeffe
3ffff690:  feefeffe feefeffe feefeffe feefeffe
3ffff6a0:  feefeffe feefeffe feefeffe feefeffe
3ffff6b0:  feefeffe feefeffe feefeffe feefeffe
3ffff6c0:  feefeffe feefeffe feefeffe feefeffe
3ffff6d0:  feefeffe feefeffe feefeffe feefeffe
3ffff6e0:  feefeffe feefeffe feefeffe feefeffe
3ffff6f0:  feefeffe feefeffe feefeffe feefeffe
3ffff700:  feefeffe feefeffe feefeffe feefeffe
3ffff710:  feefeffe feefeffe feefeffe feefeffe
3ffff720:  feefeffe feefeffe feefeffe feefeffe
3ffff730:  feefeffe feefeffe feefeffe feefeffe
3ffff740:  feefeffe feefeffe feefeffe feefeffe
3ffff750:  feefeffe feefeffe feefeffe feefeffe
3ffff760:  feefeffe feefeffe feefeffe feefeffe
3ffff770:  feefeffe feefeffe feefeffe feefeffe
3ffff780:  feefeffe feefeffe feefeffe feefeffe
3ffff790:  feefeffe feefeffe feefeffe feefeffe
3ffff7a0:  feefeffe feefeffe feefeffe feefeffe
3ffff7b0:  feefeffe feefeffe feefeffe feefeffe
3ffff7c0:  feefeffe feefeffe feefeffe feefeffe
3ffff7d0:  feefeffe feefeffe feefeffe feefeffe
3ffff7e0:  feefeffe feefeffe feefeffe feefeffe
3ffff7f0:  feefeffe feefeffe feefeffe feefeffe
3ffff800:  feefeffe feefeffe feefeffe feefeffe
3ffff810:  feefeffe feefeffe feefeffe feefeffe
3ffff820:  feefeffe feefeffe feefeffe feefeffe
3ffff830:  feefeffe feefeffe feefeffe feefeffe
3ffff840:  feefeffe feefeffe feefeffe feefeffe
3ffff850:  feefeffe feefeffe feefeffe feefeffe
3ffff860:  feefeffe feefeffe feefeffe feefeffe
3ffff870:  feefeffe feefeffe feefeffe feefeffe
3ffff880:  feefeffe feefeffe feefeffe feefeffe
3ffff890:  feefeffe feefeffe feefeffe feefeffe
3ffff8a0:  feefeffe feefeffe feefeffe feefeffe
3ffff8b0:  feefeffe feefeffe feefeffe feefeffe
3ffff8c0:  feefeffe feefeffe feefeffe feefeffe
3ffff8d0:  feefeffe feefeffe feefeffe feefeffe
3ffff8e0:  feefeffe feefeffe feefeffe feefeffe
3ffff8f0:  feefeffe feefeffe feefeffe feefeffe
3ffff900:  feefeffe feefeffe feefeffe feefeffe
3ffff910:  feefeffe feefeffe feefeffe feefeffe
3ffff920:  feefeffe feefeffe feefeffe feefeffe
3ffff930:  feefeffe feefeffe feefeffe feefeffe
3ffff940:  feefeffe feefeffe feefeffe feefeffe
3ffff950:  feefeffe feefeffe feefeffe feefeffe
3ffff960:  feefeffe feefeffe feefeffe feefeffe
3ffff970:  feefeffe feefeffe feefeffe feefeffe
3ffff980:  feefeffe feefeffe feefeffe feefeffe
3ffff990:  feefeffe feefeffe feefeffe feefeffe
3ffff9a0:  feefeffe feefeffe feefeffe feefeffe
3ffff9b0:  feefeffe feefeffe feefeffe feefeffe
3ffff9c0:  feefeffe feefeffe feefeffe feefeffe
3ffff9d0:  feefeffe feefeffe feefeffe feefeffe
3ffff9e0:  feefeffe feefeffe feefeffe feefeffe
3ffff9f0:  feefeffe feefeffe feefeffe feefeffe
3ffffa00:  feefeffe feefeffe feefeffe feefeffe
3ffffa10:  feefeffe feefeffe feefeffe feefeffe
3ffffa20:  feefeffe feefeffe feefeffe feefeffe
3ffffa30:  feefeffe feefeffe feefeffe feefeffe
3ffffa40:  feefeffe feefeffe feefeffe feefeffe
3ffffa50:  feefeffe feefeffe feefeffe feefeffe
3ffffa60:  feefeffe feefeffe feefeffe feefeffe
3ffffa70:  00000000 00000000 0000001f 40105379
3ffffa80:  4000050c feefeffe feefeffe feefeffe
3ffffa90:  40222216 00000030 00000010 ffffffff
3ffffaa0:  40218973 3fff0884 00000000 00000000
3ffffab0:  00000a43 00000000 00000a43 3fff07b4
3ffffac0:  00000a43 00000000 00000020 000000fd
3ffffad0:  00000005 00000000 00000020 40101696
3ffffae0:  3ffe96b5 40104a97 3ffed118 40101696
3ffffaf0:  401023ad 3ffed118 3ffed118 40101696
3ffffb00:  00000005 00000000 00000020 40101696
3ffffb10:  3ffe96b5 40104a97 3ffed0f0 4010257e
3ffffb20:  00000002 00000000 00000020 40101696
3ffffb30:  3ffe96b2 40104a7c 3ffece48 4010257e
3ffffb40:  00000001 40103c9f 3ffed878 00000001
3ffffb50:  40104102 c047a314 401029be 00000100
3ffffb60:  00000000 00000000 0000001f 40105379
3ffffb70:  40103be6 00000023 7fffffff 00000002
3ffffb80:  00000123 3ffed118 3ffe9801 00000008
3ffffb90:  40102a5b 00080000 3ffedb88 4010257e
3ffffba0:  00000000 00000000 00002200 4000050c
3ffffbb0:  3fffc278 40102758 3fffc200 00000022
3ffffbc0:  3ffffbd0 3ffe9f6c 3ffe9f6c 00000001
3ffffbd0:  4021bddb 00000030 00000010 ffffffff
3ffffbe0:  4021bddb 00000001 00000000 0000c005
3ffffbf0:  0000024e 00000001 ffff7f72 0000888e
3ffffc00:  000005e0 00000020 401038a1 3ffed830
3ffffc10:  0000013a 00000000 3fff0c70 000000fd
3ffffc20:  0000005a 00000001 401049e2 3ffed830
3ffffc30:  00000000 00000000 00000020 40101696
3ffffc40:  3ffe96b0 40104a7c 3fff034c 3ffed830
3ffffc50:  00000001 40103c9f 3ffed830 40101696
3ffffc60:  40104102 00040000 40229be3 00000001
3ffffc70:  ffffffff 00000000 3ffe9801 00000008
3ffffc80:  40229c32 3ffecdd0 3ffefa4c 00000001
3ffffc90:  40229d3e 3ffecdd0 3ffefa4c 3ffecdd0
3ffffca0:  00000002 00000000 00000020 40101696
3ffffcb0:  3ffe96b2 40228cef 3ffecdd0 3fff0c54
3ffffcc0:  00000000 4021bf97 3ffee2d8 40105379
3ffffcd0:  00000000 00000002 00000000 3ffecdd0
3ffffce0:  3fff1882 4010511f 3fff0c54 3fff01dc
3ffffcf0:  3fff184c 0000002f 00000000 00000001
3ffffd00:  00000004 4020e2d9 3ffef418 3fff01dc
3ffffd10:  3fff1882 00000045 00000001 3ffeefc8
3ffffd20:  3fffff20 3fffff20 0000000a 00000000
3ffffd30:  3ffef83c 3ffef804 3fff184c 4020e55b
3ffffd40:  00000002 3ffef804 3fff184c 4020e94c
3ffffd50:  3ffef6a8 4bc6a7f0 94bc6a7f 00000001
3ffffd60:  00000001 00000000 4bc6a7f0 3ffef6ac
3ffffd70:  3ffef83c 00000003 3ffef804 40216024
3ffffd80:  00000000 3ffee998 8d04d0fb 00000000
3ffffd90:  00000002 3fff184c 3ffef294 00000000
3ffffda0:  3ffee9c0 3ffef294 3ffe851c 3fff184c
3ffffdb0:  00000001 4bc6a7f0 deb851eb 00000001
3ffffdc0:  00000001 00000000 4bc6a7f0 00000000
3ffffdd0:  3ffef2bc 000001d3 000001d3 40100664
3ffffde0:  00000001 00000000 3fff0774 40100aa8
3ffffdf0:  3b172b21 000001d3 3ffe851c 4020e175
3ffffe00:  00000001 3ffffe8f 40206268 402036f7
3ffffe10:  00000001 00000000 3fff0774 40203e3f
3ffffe20:  00000002 3ffffeae 3fff0774 40203ec5
3ffffe30:  00000001 4bc6a7f0 8083126e 3fffff40
3ffffe40:  00000030 0000000a 3fffff40 402057ed
3ffffe50:  3ffffe8f 000001d3 000001d3 40100664
3ffffe60:  00000001 4bc6a7f0 3c6a7efa 00000001
3ffffe70:  00000001 00000000 4bc6a7f0 00000000
3ffffe80:  00000001 00000000 401001c0 00334411
3ffffe90:  00000000 000001d3 000001d3 40100664
3ffffea0:  3b46b3ee 00000000 3ffe851c 00000000
3ffffeb0:  00000002 3ffe9259 40206268 3fffefa0
3ffffec0:  00000002 00000000 3fff0774 40203e73
3ffffed0:  0000000b 00000000 3fff0774 40203ec5
3ffffee0:  3fffff40 3fe0004f 3fff0774 41cccccd
3ffffef0:  423c999a 00000000 3fffff40 402057ed
3fffff00:  3ffe9259 3ffef020 3fffff40 402057ed
3fffff10:  3ffe8be4 3ffef020 3fffff40 40205818
3fffff20:  423c999a 3ffef020 3fffff40 40205864
3fffff30:  429a0000 3ffef020 3ffef03c 40202cc9
3fffff40:  40206988 00000000 00001388 40206738
3fffff50:  00000000 3fff0774 00000000 00000000
3fffff60:  00000000 00000000 00000000 00000000
3fffff70:  3fff0ccc 0000007f 00000000 feefeffe
3fffff80:  429c28f6 00000000 42473333 feefeffe
3fffff90:  00000000 00000000 00000001 3ffef238
3fffffa0:  3fffdad0 00000000 3ffef208 40206314
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

My code:
#include <ESP8266WiFi.h>
#include <DHT.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define DHTTYPE DHT22

const char* ssid = "ID";
const char* password = "pass";
const char* ssid2 = "ID2";
const char* password2 = "pass2";

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

WiFiServer server(80); // Set web server port number to 80
String header; // Variable to store the HTTP request

// Decode HTTP GET value
String valueString = "0";
int pos1 = 0;
int pos2 = 0;

// Variables to store the current output state
int relay0State = 0;
int relay1State = 0;
int relay2State = 0;
String brightness = "0";

// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;

// Variables assigned to pins
const int relay0 = 16;
const int relay1 = 5;
const int relay2 = 4;
const int DHT1Pin = 0;
const int DHT2Pin = 2;

// Initialize DHT sensors
DHT dht1(DHT1Pin, DHTTYPE);
DHT dht2(DHT2Pin, DHTTYPE);

void setup() {
  //Watchdog timer settings
  ESP.wdtDisable();
  ESP.wdtEnable(WDTO_8S);

  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(relay0, OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  // Set outputs to LOW
  digitalWrite(relay0, LOW);
  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);

  dht1.begin();
  dht2.begin();

  // Connect to available Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  int n = WiFi.scanNetworks();
  if (n == 0)
    Serial.println("No networks found!");
  else {
    for(int i=0;i<n;i++) {
      if(WiFi.SSID(i)==ssid) {
        WiFi.begin(ssid,password);
        ssid = ssid;
      } else if (WiFi.SSID(i)== ssid2) {
        WiFi.begin(ssid2,password2);
        ssid = ssid2;
      }
    }
  }
  Serial.println(ssid);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi CONNECTED with IP: ");
  Serial.println(WiFi.localIP());
  server.begin();
  timeClient.begin(); // Initialize a NTPClient to get time
  timeClient.setTimeOffset(7200); // Setting offset time in seconds to adjust for current timezone -> GMT +1 = 3600
}

void loop(){
  ESP.wdtFeed(); //Feed the watchdog timer
  WiFiClient client = server.available();   // Listen for incoming clients

   while(!timeClient.update()) {
    timeClient.forceUpdate();
  }
  formattedDate = timeClient.getFormattedDate(); // The formattedDate comes with the following format 2018-05-28T16:00:13Z
  // Extract date
  int splitT = formattedDate.indexOf("T");
  dayStamp = formattedDate.substring(0, splitT);
  // Extract time
  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);

  if (client) {
    String currentLine = "";               // String to hold incoming data from the client
    while (client.connected()) {           // loop while the client's connected
      if (client.available()) {            // if there's bytes to read from the client,
        char c = client.read();            // read a byte, then
        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();

            // Read humidity
            float h1 = dht1.readHumidity();
            float h2 = dht2.readHumidity();
            // Read temperature as Celsius (the default)
            float t1 = dht1.readTemperature();
            float t2 = dht2.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f1 = dht1.readTemperature(true);
            float f2 = dht2.readTemperature(true);

            // Calculating average temp and humidity from DHT22 sensors
            float temperature = (t1 + t2)/2;
            float temperaturef = (f1 + f2)/2;
            float humidity = (h1 + h2)/2;

            if(header.indexOf("GET /1/") | header.indexOf("GET /0/") < 0){
                if(humidity < 50){
                relay1State = 1;
                digitalWrite(relay1, HIGH);
              } else {
                relay1State = 0;
                digitalWrite(relay1, LOW);
              }
              if(temperature < 23) {
                relay0State = 1;
                digitalWrite(relay0, HIGH);
              } else {
                relay0State = 0;
                digitalWrite(relay0, LOW);
              }
            }

            if (header.indexOf("GET /0/on") >= 0) {
              relay0State = 1;
              digitalWrite(relay0, HIGH);
            } else if (header.indexOf("GET /0/off") >= 0) {
              relay0State = 0;
              digitalWrite(relay0, LOW);
            } else if (header.indexOf("GET /1/on") >= 0) {
              relay1State = 1;
              digitalWrite(relay1, HIGH);
            } else if (header.indexOf("GET /1/off") >= 0) {
              relay1State = 0;
              digitalWrite(relay1, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta http-equiv=\"refresh\" content=\"1\" name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
            client.println("<style> html {font-family: Helvetica; display: inline-block; margin: 0px; text-align: center; height: auto; box-sizing: border-box;} h1, h2{width: 100%; color: #444444; font-size: 55px;} h2 {font-size: 30px;} h3, h4 {width: 50%; font-size: 24px; color: #444444; padding: 18px; margin: 10px; border-radius: 35px; margin: 4px auto;} h4 {padding: 5px;} .button {background-color: #4CAF50; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} .button2 {background-color: #555555;} .content {width: 100%; } .light {border-radius: 35px; width: 50%; margin: 4px auto;} .slider {-webkit-appearance: none; width: 30%; height: 10px; border-radius: 5px; margin-bottom: 20px; background: #d3d3d3; outline: none; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 20px; height: 20px; border-radius: 50%; background: #444444; cursor: pointer;} @media (max-width: 1000px) {h1{font-size: 40px;} h2{font-size: 25px;} h3,h4{width: 75%; font-size: 20px;} .light{ width: 75%;}}</style><title>Smart TERA</title> </head> ");
            client.println("<body><div class=\"header\"> <h1>Smart TERA</h1><h2>");
            client.println(timeStamp);
            client.println(" / " + dayStamp);
            client.println("</h2> </div> <div class=\"content\"><h3 style =\"background-color: #ff8000;\">Temperature: ");
            client.println(temperature);
            client.println("℃ /  ");
            client.println(temperaturef);
            client.println("℉ </h3><h3 style =\"background-color: #4da6ff;\">Humidity: ");
            client.println(humidity);
            client.println("%</h3><div class=\"light\" style=\"background-color: #ffff33;\"><h3>Light Brightness: <span id=\"lightPos\"></span> %</h3> <input class=\"slider\" type=\"range\" min=\"0\" max=\"100\" step=\"25\" value="+brightness+" id=\"myRange\">");
            client.println("<script> var slider = document.getElementById(\"myRange\"); var lightP = document.getElementById(\"lightPos\"); lightP.innerHTML = slider.value; $.ajaxSetup({timeout:1000}); slider.oninput = function() { slider.value = this.value; lightP.innerHTML = this.value; $.get(\"/?value=\" + this.value + \"&\"); {Connection: close};}</script> </div>");

            if(header.indexOf("GET /?value=")>=0) {
                pos1 = header.indexOf('=');
                pos2 = header.indexOf('&');
                valueString = header.substring(pos1+1, pos2);
                if(valueString == "0" ){
                  brightness = "0";
                  analogWrite(relay2, 0);
                } else if (valueString == "25"){
                  brightness = "25";
                  analogWrite(relay2, 256);
                } else if (valueString == "50"){
                  brightness = "50";
                  analogWrite(relay2, 512);
                } else if (valueString == "75"){
                  brightness = "75";
                  analogWrite(relay2, 768);
                } else if (valueString == "100"){
                  brightness = "100";
                  analogWrite(relay2, 1024);
                }
           }
            // Display current state, and ON/OFF buttons for controlling relays, If the relay0State is off, it displays the ON button
            client.println("<h4>Rock Heater - State ");
            if (relay0State == 0) {
              client.println("off</h4><p><a href=\"/0/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("on</h4><p><a href=\"/0/off\"><button class=\"button button2\">OFF</button></a></p>");
            }

            client.println("<h4>Humidifier - State ");
            if (relay1State == 0) {
              client.println("off </h4><p><a href=\"/1/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("on </h4><p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</div></body></html>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            yield();
            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 and close the connection
    header = "";
    client.stop();
   }
}

Decoded error:

esp8266 arduino package version? use 2.4.2

im using 2.5.0, ok i will try

2.4.0 had a memory leak. your problem is memory fragmentation with String class.

how can i fix that? i tried replacing strings with chars but i cant get my code working.. i dont know how to make same operations without strings

learn it. I don't know if it can help you, but here is my Web Server https://github.com/jandrassy/Regulator/blob/master/Regulator/WebServer.ino

or use the ESP8266WebServer library and url parameters. see the SimpleAuthentication example. it uses url parameters

First, take out the wdt.feed all that does is delay the real problem and/or shift it somewhere else. As a rule of thumb, if you even THINK you have to use / touch / play with / cancel the WDT, your code is already wrong. The root problem is your code is "blocking" longer than the underlying WiFI stack is happy with. A culprit is: while(!timeClient.update()) How long does that take? If it "blocks" then your code will fail. "Multiple" / "Parallel" tasks must run asynchronously and yield() to the backgound WiFi if they are long-running. If you mix old fashioned, blocking code with modern asynchronous code, THIS is exactly what you will get.
Other points: all that println stuff in the main loop is horribly inefficient and won't be helping. Setup the main body of text once and edit / resend the bits that change.
Also I believe DHT11 can sometimes take a while to settle / read. If the library you are using is not optimised for ESP8266 and / or non-blocking, there's another potential source of error. I believe DHT11 can also sometimes return NaN rather than a valid value - how do you cope with that?
There's an async webserver library that does all that side of things properly - you are reinventing a wheel and yours is square. You need to find an async NTP library too. "But I found it in the library examples!" Is NOT a guarantee / justification that the code is a) useful b) any good c) well-written d) functional for any other purpose. In my experience its usually the opposite of all four, especially if you mix two libraries together. It's an "example" - it's not production code.
Final takeaway:

Use the right library for the right job
NEVER mess with the WDT
NEVER mix sync + async code
Most example ESP8266 code assumes a single function, not needing to cooperate with any other. If you mix / blend separate examples / functions (e.g. DHT11 AND NTP AND WEBSERVER), YOU must provide the co-operation between functions + ESP8266 background WiFi. If you don't (and you haven't) you will cause a WDT reset, 100% guaranteed.

i had look like this problem before.
for me , when i much used of " Serial.print " this RST fault occur for me..
so i use of a function:
void Serial_Show() {
    Serial.println();
}

maybe your problem is this.
you can test it by deleting all Serial.print() function and next add one by one...


text:
Unable to read data more than once via Modbus RTU
I'm a newbie to this forum so kindly excuse me for any errors.
I'm using an Arduino Uno and Max485 (RS-485 to TTL) to communicate with a Power meter, but I'm able to receive the data from the Power Meter only once and then it prints "Error" continuously. I need to reopen the Serial Monitor to get the new reading but again the issue persists thereafter. Reading parameter is voltage.
I am using ModbusMaster library. Please refer to the code below.
#include <ModbusMaster.h>

uint16_t vl1, v11;
uint8_t result1;
float v1;

ModbusMaster  node;
#define MAX485_DE      2
#define MAX485_RE_NEG  3

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG, 1);
  digitalWrite(MAX485_DE, 1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);
}

void setup()
{
  // Open serial communications and wait for port to open:

  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);

  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);

  Serial.begin(9600);

  node.begin(1, Serial);

  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);

}

void loop()
{
  result1 = node.readInputRegisters(0x0001, 5);

  delay(1000);

  if (result1 == node.ku8MBSuccess)
  {
    //Retrieiving data from energy meter via modbus

    vl1 = node.getResponseBuffer(0x01);
    v11 = node.getResponseBuffer(0x00);
    uint16_t data[2] = {va11, val1};
    memcpy(&v1, data, 4);
    Serial.println("Voltage:);
    Serial.print(v1);
  }

  else
  {
    Serial.println("Error");
  }
}

This is the output I get from the Serial Monitor
Voltage:221.21
Error
Error
Error

FYI, Meter communication details as follows:

Baud Rate: 9600, Parity: None, Stop bits: 1, Slave ID: 1

I'm unable to figure out the issue therefore I'm looking forward in seeking your assistance. Thank you!

Please, confirm you're using this ModBus library.
Let us also know if you cut&pasted code from somewhere or if you really wrote it as... I'm a bit skeptical about the "delay(1000)" you added right after the readInputRegisters call. Why you used it?
As a final note, please consider that based on official documentation here the readInputRegisters function returns..."0 on success; exception number on failure". As it's failing, please print its value as well.

I used the "half duplex" example from the Modbus Master library and modified the program according to my need. If I print instead of error value, it repeats the same voltage value.

Any solution found on this ?

source: Stack Exchange

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

sort: votes


text:
What is the difference between the two sensors?
I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.

They seem pretty similar. One uses surface-mount components and the other through-hole components. But my guess would be that they do pretty much the same thing. I'd prefer the first one, as it have some bypass capacitors on it, which could make it's signal a bit more stable.

It would be helpful if you would provide spec sheets or at least part numbers and sources for the 2 boards. Otherwise we have to do some guesswork from the images provided.

Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look.
They seems to both be FC-51 modules: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them.
The potentiometer is there to determine the triggering level so that when powered you can have a LOW signal on the OUT pin when the threshold is reached.

How do you know, that the output signal is digital? Wouldn't it be also possible, that the output voltage may be analog and the potentiometer controls the gain? I don't know, how I should be able to tell from the pictures.

Because those sensors are quite common and called FC-51 https://codetipste.blogspot.com/2017/04/ir-sensor-arduino.html?m=1.

Not to mention I stated "they seem totally equivalent by their look": without further information that is my best guess...

Ah, ok. Good, that you included the part number (FC-51), so that we have a reference. +1

How can i find the positive and negative terminal of transmitter and receiver of sensor in first pic?@RobertoLoGiacco

Power it up and use a multimeter maybe?

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


text:
i2c code hanging - tried all connections
I'm trying to connect a TCA9548a breakout to my nano (also tried using an uno), but it can't recognise it - using the i2c scanner it just hangs on 'scanning...'
I've tried everything suggested in similar posts - checking connections, adding/not adding pullups (this nano I think already has them) and checking other i2c devices using same setup (which work fine). If I connect another i2c device, without the TCA, and have the i2c scanner working well and finding it, then connect SCL from the TCA (whether or not SDA is also connected) the scanner hangs.
When I was checking connections with the tca connected, it did work just once, finding it. Haven't been able to repeat that though since, I can't remember exactly what I was doing at the time.
Any help please?
Thanks in advance
i2c scanner:
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(115200);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(1000);           // wait 5 seconds for next scan
}

tca9548a scanner:
#include "Wire.h"
extern "C" {
#include "utility/twi.h"  // from Wire library, so we can do bus scanning
}

#define TCAADDR 0x74

void tcaselect(uint8_t i) {
  if (i > 7) return;

  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

// standard Arduino setup()
void setup()
{
    while (!Serial);
    delay(1000);

    Wire.begin();

    Serial.begin(115200);
    Serial.println("\nTCAScanner ready!");

    for (uint8_t t=0; t<8; t++) {
      Serial.println("selecting");
      tcaselect(t);
      Serial.println("selected");
      Serial.print("TCA Port #"); Serial.println(t);

      for (uint8_t addr = 0; addr<=127; addr++) {
        if (addr == TCAADDR) continue;

        uint8_t data;
        if (! twi_writeTo(addr, &data, 0, 1, 1)) {
           Serial.print("Found I2C 0x");  Serial.println(addr,HEX);
        }
      }
    }
    Serial.println("\ndone");
}

void loop()
{
}

The arduino wire library has the bad habit to hang when the hardware i2c bus is wrong. If you use for example a cable instead of short seperate wires, or if the scl is connected to gnd or when pullup resistors are missing. The arduino nano has no pullup resistors, but the Wire library enables the internal pullup resistors, and that should work for short wires. Do you have a voltage meter to measure the scl and sda? They should be near 5v when the i2c bus is not used.

Use the first scanner sketch to detect the tca multiplexer. Please forget that second sketch that calls twi_writeTo directly. That is an example from adafruit and I thing they made a terrible mistake by using the Wire library like that. Once the tca chip is working, then you can use the function tcaselect and scan each bus from the tca multiplexer.

@Jot Neither sketch detects it. I've just got it connected with the simple blink sketch running on the nano, and a 2K87 pullup from SCL to the Nano +5v, and finding it's only at 1.4V. Is the tca broken perhaps?

It might be broken. Does the tca VIN pin have 5v? On the backside of the tca module are solder pads with tiny connections for the pullup resistors for sda and scl. They are 10k and are default enabled. If you have the tca module on its own (nothing connected) and apply 5v to it, then you can measure the sda and scl pins. If they are low, then it is broken.

OK. I've stupidly already soldered it and can't get to that side anymore. Is there a connection the other side to definitively tell me the same thing? Thanks

Do you have the possibillity to monitor the scl line with an oscilloscope?

@Sim Son no unfortunately not - what would that tell me if I did though?

Detecting the kind of an i2c failure with the software itself is nearly impossible in most cases (e.g. considering the error codes returned by the interface in your code barely help finding a solution). Monitoring the signals externaly can exhibit several problems and help identify the device that causes a problem. Some classics with I2C: SCL keeps low -> likely a clock-stretching slave (does the master support clock-stretching?); bad signal -> capacitance/bus-length/fequency too high; SD remains high -> wrong master configuration (?!)...

so, there are several observations that reliably can only be done with an oscilloscope. I for myself can't remember to ever have found the root of a i2c-related problem without an oscilloscope or a logic analyzer

@SimSon OK many thanks for the info. If you put that as an answer I will mark it correct


text:
Ultra Long Range (200-500km) Arduino Communication using a Gibson Girl
I came across this article on Hackaday showing a simple AM transmitter sending a morse code tone 700km!
I'm looking into a EPIRB for myself while deep in the bush / outback hunting or camping, just to send a message to my wife. (a true EPIRB wouldn't be useful to let her know I'm all good, or ask her to call my mate to come pull my truck out of a bog hole)
I plan on sending short text messages via Morse Code, or probably just 8 bit ascii - so speed is not important. If a 50 character message takes 5 minutes to send - so be it... It's meant for check ins, not rapid messaging.
I'll take care of the screen and keyboard side of it - but just interested if anyone has any thoughts or experience using a long range AM signal generator like in the link, and interfacing an Arduino as a transceiver...
https://hackaday.com/2014/12/19/gibson-girl-emergency-beacon-built-from-a-wind-up-flashlight/

40 meters is considered one of the most reliable all-season long distance communication (DX) bands.  7.023 MHz  https://www.youtube.com/watch?v=9Oicqr28xLk  you may need a directional coupler or VSWR meter to trim each 20m wire length for best results

SPOT Gen3 Satellite GPS Tracker can have you send a message that all is okay, besides calling in an SOS. But it can only send a single type of message, so it's can send any arbitrary text. You could agree with your wife to some message schema, like regular "I'm okay" message will only be send at 20:00h. All other times mean, that I would require some non-emergency help.

Not sure if I would trust my life on a self made AM transmitter. But as an addition would be a good idea. Depending on your location you might need to have a license to transmit (HAM-license in the USA).


text:
Ensure board is always on the same port?
I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

My experience is that the Serial-to-USB converters (of which Arduino is one) have are assigned a COM port according to the USB port they are plugged into. So if you always to connect it to the same physical USB port it will have the same number. However this number will not be the same with a different Arduino or on a different computer.

Normally, the COM port number wont change, but you cannot simply rely on this.
Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.
Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.
And, btw. it's not related to VB.net


text:
Arduino with Ethernet Shield with PC to upload data to Microsoft Azure
i am a student doing a project related to datalogging. My project is a rehabilitation device that uses 2 rotary encoders to record data for rotation and linear movement of a human arm. The data extract is store inside the PC, but my supervisor wants me to upgrade it, he gave me an Arduino Ethernet Shield to attach it on Arduino Mega and he wants me to upload the data obtained from the device to Microsoft Azure database. I'm still new in both Arduino Ethernet Shield and Azure...can anyone help me?
What can i do with the Ethernet Shield? I mean we normally use the USB cable to work with Arduino, so this mean I have to connect both?
Thanks in advance!

what Azure service? does it support non encrypted access

I'm still learning about Azure service, Azure has various features. 1 of the features is the database.

Assuming that you mean the SQL Database of Azure, a quick google search found me this library, which might work for you. You should start with the provided examples, as mostly they are a good starting point for a new library. There might be more to use out there. You just have to search for it. Try keywords involving sql / mysql combined with Arduino.

thank you very much, I will follow the example and try out.


text:
Not able to control DC motor speed with l298N & pwm pins
I am using arduino uno to control dc motor speed with L298N. But the problem is that the motor is only going at max speed. PWM pin doesn't work for some reason.
I heard many people had some problem but haven't found the solution yet.
code:-
#include <L298N.h>

#define ENA 9
#define IN1 8
#define IN2 7

L298N motor(ENA, IN1, IN2);

void setup() {
// Setup pin mode

//used for display information
  Serial.begin(9600);

}

void loop() {
//Drive Motor Forward
  motor.setSpeed(10);
  motor.forward();
  delay(500);
  motor.setSpeed(100);
  motor.forward();
  delay(500);
  motor.setSpeed(255);
  motor.forward();
  delay(500);

}

I only see the motor move at full speed every time. I connected 5V of Arduino to +12V pin of motor driver and Arduino is powered with my laptop USB.
I am using 4.5V toy dc motor for test - DC motor
What could be wrong here?

The l298n output to the motor has a large voltage drop, and because of that it will not work with 5v. The 5v pin of the arduino can not supply enough current for a motor. What motor is it? Can you give a link to the motor?

added dc motor link, I am using those toy dc motor for the test. It doesn't need much voltage so I though it will be fine.

That is a small motor. With a mosfet driver (no voltage drop) it might work with the 5v pin.

this motor is just for test. Later I want to control 12V high torque motor so for that, I am using this module.

Using 5V pin (!) of an USB-powered Arduino (!!) as a motor power supply (!!!) can easily kill your Arduino.

Similar problem solved: I had a similar problem with the motors running att full speed with analogwrite values higher than 127 and not running at 127 or below.
After some research i found out that only some pins works for pwm reference for analogWrite(), but your ENA is on pin 9, and that should work.

Modifying the library code file L298N.cpp. Insert 2 lines in setSpeed():
void L298N::setSpeed(unsigned short pwmVal)
{ _pwmVal = pwmVal;
  if (_ismoving == true)                   // +++
    analogWrite(_pinEnable, _pwmVal);      // +++
}

Problem solved!

Try to use this code, without the library, and be sure to connect every pin to the correct Arduino output. If everything is okay it should work. Check the tutorial here
int IN3 = 5;
int IN4 = 4;
int ENB = 3;
void setup()
{
 pinMode (ENB, OUTPUT);
 pinMode (IN3, OUTPUT);
 pinMode (IN4, OUTPUT);
}
void loop()
{

  digitalWrite (IN3, HIGH);
  digitalWrite (IN4, LOW);
  analogWrite(ENB,55);
  delay(2000);
  analogWrite(ENB,105);
  delay(2000);
  analogWrite(ENB,255);
  delay(2000);
  analogWrite(ENB,0);
  delay(5000);
}

I did try that code also but didn't work. I think there is problem in the enable pin of driver itself.


text:
Calculating the time between the signal when its ON and when it gets OFF
class Channel
{
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display()
        {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
          //  Serial.print(",");
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs-4);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0)
        {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process()
          {
            int s = digitalRead(_pin);
            if (s != _state)
              {
                _state = s;
                if (s == LOW)  // Fell
                  {
                    _fall = millis();
                    _count++;
                    display();
                  }
                else
                  {
                    _rise = millis();
                  }
                }
            }
        void begin()
        {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 3,5 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

void setup()
{
    Serial.begin(115200);
    Serial.println("Channel,Minutes,Seconds,Count");
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].begin();
      }
}

void loop()
{
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].process();
      }
}

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.
In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below

bro that 10 digit is the 0xFFFFFFFF maximum value that an unsigned 32 bit integer can attain.

@Vaibhav: No, the maximum value is 4294967295. The value he is seeing is −4. C.f. Reezy's answer.

You have not yet explained why you have put the bug in there. I mean the "secs-4" instead of "secs".

The values which I get in seconds is four seconds more than the actual value. So I used "sec-4" instead of seconds

I suspect secs is 0 sometimes, because of _rise being 0? In that case unsigned int subtraction causes this: secs(0) - 4 = -4 % 2^32, resulting in your 4294967292

Oh, but there will be at least one second for which the signal will last. (I'm getting 4294967292 three to four times for a single ON and OFF transition). Is there any other possibility that might cause this to appear?

I suggest tracer bullets, i.e. print out all the variables in the Display method.

Yeah but still seconds cant be zero in my case there will be atleast 4 to 5 seconds, so even if I remove that "-4", still I would be getting this number right?


text:
problem in uploading the code
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Have you been able to upload before or did this problem occur all of a sudden?

Also like mentioned in the ide you should increase verbosity during upload. Maybe there are some hints where to look for a solution...

Try to upload your code without any device connected to Uno. Disconnect all IO pins. Upload the code via onboard USB port.

It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

RX/TX UART port used
USB port broken
USB cable broken
Arduino broken
USB port drivers not properly installed
Problem inside IDE
...

To troubleshoot you could try:

Disconnect RX/TX jumpers
Try another USB port
Remove other USB devices
Try another USB cable
Try another Arduino
Try another PC/laptop
Reinstall IDE
Reinstall USB drivers


text:
Adafruit esp32 Feather Failing to compile
So yesterday, I was able to upload/compile given example code to the Esp32 Huzzah board. Today I couldn't even compile. Even carefully using the tutorial adafruit provides.
I was getting errors as given below. How do I fix this?
C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o):(.literal.main_task+0x14): undefined reference to `app_main'

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o): In function `main_task':

/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/esp32/cpu_start.c:503: undefined reference to `app_main'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial9availableEv+0x0): undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4peekEv+0x0): undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4readEv+0x0): undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5flushEv+0x0): undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEh+0x0): undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEPKhj+0x0): undefined reference to `uartWriteBuf'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::available()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::peek()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::read()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::flush()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char const*, unsigned int)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWriteBuf'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Adafruit ESP32 Feather.

So it turns out the problem is that you're using the esp32 1.0.1 library provided by espressif. I'm assuming you're using the Arduino IDE board manager URL: https://dl.espressif.com/dl/package_esp32_index.json
To fix this, don't use 1.0.1. Use 1.0.0! Remove 1.0.1 and install 1.0.0. That should get it to compile properly without the uart, app_main errors.


text:
can an ISR change the value passed by pointer while the subroutine is executing?
So I am working on a project where the board plays a song on a buzzer using PWM and I want the song to stop when i press an external button
typedef enum stateType_enum{
waitPress, debouncePress, waitRelease, debounceRelease
} stateType;
volatile stateType state = waitPress;
volatile bool deviceOn = false;

int main(void){
   sei();
   while(1) {

   switch(state){
     case waitPress:
       break;
     case debouncePress:
       delayMs(100);
       state = waitRelease;
       break;
     case waitRelease:
       break;
     case debounceRelease:
       delayMs(100);
       state = waitPress;
       break;
   }

   if(deviceOn){
       triggerAlarm(&deviceOn);
   }
   _delay_ms(100);
}

ISR(PCINT0_vect){
   if(state == waitPress){
      state = debouncePress;
   }
   else if (state == waitRelease){
      deviceOn = !deviceOn;
      state = debounceRelease;
   }
}

My real question is, can I send the deviceOn as a pointer to the song?

Which arduino board do you use and which version of the arduion ide? please show a full sketch, I want to see the function triggerAlarm. Please try to explain what you want to achieve. You can send anything to the song, but that depends on what you want, which I don't understand. Can you change everything and use millis instead of delays?

Please show triggerAlarm()... why do you want to pass it if its argument is a global variable? I think there's no need for that.


text:
Arduino Bluetooth to Control Joystick Issue
I am trying to control a robot, where I have one HC05 module as a master connected to an Arduino Uno with an attached joystick. This Arduino sends data signals that will run blocks of code on the slave Arduino, which will have four servo motors connected to it, but for testing purposes, only two are connected. This Arduino also has an HC05 Bluetooth module connected to it, but it is configured as a slave. I have tried everything to get the Bluetooth functionality to work, but it does not work! If you are interested in the background of this, this is for my Rapid Assembly and Design project for school, which I have a report on soon. We are creating a robot that can operate on land and traverse the sea, so we are making it waterproof as well.
P.S. both modules are HC05 modules.
Master Code:
#include <SoftwareSerial.h>
int yPin = A0;
int xPin = A1;
int buttonPin = 2;
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const int RX_PIN = 10;
const int TX_PIN = 9;
SoftwareSerial BL(RX_PIN, TX_PIN);
const int BLUETOOTH_BAUD_RATE = 9600;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  BL.begin(39600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  xPosition = analogRead(xPin);
  yPosition = analogRead(yPin);
  buttonState = digitalRead(buttonPin);
  /*if (buttonState == 1) {
    if (xPosition >= 450 & xPosition <= 550) {
      if (yPosition >=450 & yPosition <= 550) {
        Serial.write("a1 ");
        bluetooth.write("a1");
      }
      if (yPosition > 550) {
        Serial.write("a2 ");
        bluetooth.write("a2");
      }
      if (yPosition < 450) {
        Serial.write("a3 ");
        bluetooth.write("a3");
      }
    }
    if (yPosition >= 450 & yPosition <= 550) {
      if (yPosition >= 450 & yPosition <= 550) {
        Serial.write("b1 ");
        bluetooth.write("b1");
      }
      if (xPosition > 550) {
        Serial.write("b2 ");
        bluetooth.write("b2");
      }
      if (xPosition < 450) {
        Serial.write("b3 ");
        bluetooth.write("b3");
      }
    }
  }
  delay(100);
} */
  if (buttonState == 1) {
    if (xPosition >= 450 & xPosition <= 550) {
      if (yPosition >= 450 & yPosition <= 550) {
        BL.write("a1");
        BL.print("a1");
        Serial.print("a1");
        Serial.write("a1");
      }
      if (yPosition > 550) {
        BL.write("a2");
        BL.print("a2");
        Serial.print("a2");
        Serial.write("a2");
      }
      if (yPosition < 450) {
        BL.write("a3");
        BL.print("a3");
        Serial.print("a3");
        Serial.write("a3");
      }
    }
    if (yPosition >= 450 & yPosition <= 550) {
      if (xPosition >= 450 & xPosition <= 550) {
        BL.write("b1");
        BL.print("b1");
        Serial.print("b1");
        Serial.write("b1");
      }
      if (xPosition < 450) {
        BL.write("b2");
        BL.print("b2");
        Serial.print("b2");
        Serial.write("b2");
      }
      if (xPosition > 550) {
        BL.write("b3");
        BL.print("b3");
        Serial.print("b3");
        Serial.write("b3");
      }
    }
  }
}

Slave Code:
// Global Area
#include <Servo.h>
#include <SoftwareSerial.h>
int xPin = A1; // X connects to analog pin
int yPin = A0; // Y connects to analog pin
int buttonPin = 2; // Digital input pin for joystick state
int xPosition = 0; // Digital input pin for joystick X
int yPosition = 0; //  Digital input pin for joystick Y
const int RX_PIN = 10;
const int TX_PIN = 9;
int motorBRPin = 3;
int motorBLPin = 4;
int motorPRPin = 6;
int motorPLPin = 5;
int buttonState = 0; // Joystick state variable
Servo motor_br; // Declaration of servo with name of motor
Servo motor_pr;
Servo motor_bl;
Servo motor_pl;
SoftwareSerial BL(RX_PIN, TX_PIN);
const int BLUETOOTH_BAUD_RATE = 9600;
String state = "";

void setup() {
  Serial.begin(9600); // Begin serial monitor
  BL.begin(9600);
  pinMode(xPin, INPUT); // Declaring xPin as an input
  pinMode(yPin, INPUT); // Declaring yPin as an input
  pinMode(buttonPin, INPUT_PULLUP); // Declaring buttonPin as an input
  motor_br.attach(motorBRPin); // Telling servo which pin our servo motor is attached to
  motor_bl.attach(motorBLPin);
  motor_pr.attach(motorPRPin);
  motor_pl.attach(motorPLPin);
  }
void loop() {
  xPosition = analogRead(xPin); // Declaring the value of xPosition; The value given by the xPin read by the board at the analog input pin
  yPosition = analogRead(yPin); // Declaring the value of yPosition; The value given by the yPin read by the board at the analog input pin
  buttonState = digitalRead(buttonPin); // Declaring the value of buttonState;
  //Printing for reference
  /*Serial.print("X: ");
  Serial.print(xPosition);
  Serial.print(" | Y: ");
  Serial.print(yPosition);
  Serial.print(" | Button: ");
  Serial.println(buttonState);*/
  // If statements, if joystick is not pressed and is being pushed up, the motor will run clockwise at full speed.
  /*if (buttonState == 1) {
    if (xPosition >= 450 & xPosition <= 550) {
      if (yPosition >= 450 & yPosition <= 550) {
        motor_br.write(90);
        motor_bl.write(90);
      }
      if (yPosition > 550) {
        motor_br.write(0);
        motor_bl.write(0);
      }
      if (yPosition < 450) {
      motor_br.write(0);
      motor_bl.write(0);
      }
    }
    if (yPosition >= 450 & yPosition <= 550) {
      motor_br.write(90);
      motor_bl.write(90);
      motor_pr.write(90);
      motor_pl.write(90);
      if (xPosition < 450) {
        motor_br.write(0);
        motor_bl.write(0);
        motor_pr.write(0);
        motor_pl.write(0);
      }
      if (xPosition > 550) {
        motor_br.write(180);
        motor_bl.write(180);
        motor_pr.write(180);
        motor_pl.write(180);
    }

    }

    /*else if (xPosition < 450) {
      motor_br.write(0);
      motor_bl.write(0);
      motor_pr.write(0);
      motor_pl.write(0);
    }
    else if (xPosition > 550) {
      motor_br.write(180);
      motor_bl.write(180);
      motor_pr.write(180);
      motor_pl.write(180);
    }
    else if (yPosition >= 450 & yPosition <= 550) {
      motor_br.write(90);
      motor_bl.write(90);
    }
    else if (yPosition < 550) {
      motor_br.write(180);
      motor_bl.write(180);
    }
    else if (yPosition > 450) {
      motor_br.write(0);
      motor_bl.write(0);
    }
  }
  if (buttonState == 1) {
    if (xPosition >= 450 & xPosition <= 550) {
      motor_br.write(90);
      motor_bl.write(90);
      motor_pr.write(90);
      motor_pl.write(90);
    }
    else if (xPosition < 450) {
      motor_br.write(0);
      motor_bl.write(0);
      motor_pr.write(0);
      motor_pl.write(0);
    }
    else if (xPosition > 550) {
      motor_br.write(180);
      motor_bl.write(180);
      motor_pr.write(180);
      motor_pl.write(180);
    }
  }
  else if (buttonState == 0) {
    if (xPosition >= 450 & xPosition <= 550) {
      motor_br.write(90);
      motor_bl.write(90);
      motor_pr.write(90);
      motor_pl.write(90);
    }
    else if (xPosition < 450) {
      motor_br.write(0);
      motor_bl.write(0);
      motor_pr.write(0);
      motor_pl.write(0);
    }
    else if (xPosition > 550) {
      motor_br.write(180);
      motor_bl.write(180);
      motor_pr.write(180);
      motor_pl.write(180);
    }
  }*/
    while (BL.available()) {
      state = BL.read();
      state = Serial.read();
      Serial.print(state);
    }
    if (state == "a1" or "b1") {
      motor_br.write(90);
      motor_bl.write(90);
      state = "";
    }
    if (state == "a2") {
      motor_br.write(0);
      motor_bl.write(0);
      state = "";
    }
    if (state == "a3") {
      motor_br.write(180);
      motor_bl.write(180);
      state = "";
    }
    if (state == "b2") {
      motor_br.write(0);
      motor_bl.write(0);
      state = "";
    }
    if (state == "b3") {
      motor_br.write(180);
      motor_bl.write(180);
      state = "";
    }
    state = "";
  }

can you specify the problem you are facing.

You use 2 very different baudrates for master and slave. Though I don't know, if that really matters, as long as you don't spam the interface. Why are you sending the data twice on the master, once as ASCII and once as byte data (by using print/write)? And why are you setting the state variable twice on the slave, once from the Bluetooth connection and once from the hardware Serial?

It seems, that you mixed the master and slave code together. What should the joystick code do at the slave (which should be the robot from your description)?

How did you connect everything? Please provide schematics or a wiring diagram


text:
how to write an int to RFID tag and when read then store that in an array
The writing code is from the MFRC522 Example below:
I have added an array to store the value but it does not store it as the same value written to it in the writing. instead it stores it as byte values.
I am fairly new so would appreciate any help.

/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Enter the weight, ending with#"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

}

and the reading code is :
/*
 * Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

int weightArray[2];
int counter = 0;

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read

}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.println("Detected");

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
/*  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");
*/
  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);
    }

  for(int i = 0; i < sizeof(weightArray) / sizeof(weightArray[1]); i++) {
    Serial.print(weightArray[i]);
  }

  counter++;

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//
````````````````````````````````````

OK, so you posted some code.  But in order for people to help you, please also include a question.

First you are not writing int value during write as, buffer is defined as byte type. Your are just type casting it char* during serial read for storing data. And Your are writing just first 16 value in your CARD, so you might not get the expected results.
byte data type provides only 8 bit or 1 byte of memory location.
int data type provides 2 bytes or 4 bytes of memory location.


text:
Water tank false trigger
I am trying to make a simple water overflow protection system for my home. I have created it using BC547 and NodeMCU (ESP8266). I have a simple circuit like this:

The problem here is I have 2 wires going into the tank. Which suppose to complete the circuit as soon as water touch both the wires. But the problem here is its by default complete the circuit without even touching, this is happening only in my rooftop water tank. I tried this circuit locally on my desk first and it is working fine. I feel the problem can be humidity inside the tank? Can this be a reason for false trigger?
Here is how I have my code.

    #define RELAY_1 D1
    #define TANK_CONNECTION D4
void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println("Started");
  secondsTick.attach(1, ISRwatchdog);

  //Set relay pins to outputs
  pinMode(RELAY_1, OUTPUT);
  pinMode(TANK_CONNECTION, INPUT);

  digitalWrite(RELAY_1, relay_on);
  delay(100);

}

void loop() {
  tankFull();
  delay(100);
}

void tankFull(){

  Serial.println(digitalRead(TANK_CONNECTION));
   if(!digitalRead(TANK_CONNECTION) && relay_on == 0){
      Serial.println(motorOnCount);
      motorOnCount++;
      motorOffCount = 0;
      if(motorOnCount >= 10){
        Serial.println("Motor Turn OFF");
        digitalWrite(RELAY_1, HIGH);
         if (client.connected()) {
            client.publish(motor_status, "off", true);
            client.publish(tank_full, "on", true);

          }
        motorOnCount=0;
        relay_on = 1;
      }
      delay(100);
   } else{
      motorOffCount++;
       if (client.connected()) {
          client.publish(tank_full, "off", true);
       }
      //Serial.println(motorOffCount);
      if(motorOffCount>=100){
        motorOffCount=0;
        motorOnCount = 0;

      }
   }
}

Obviously this is not the full code. I am just trying to share the pattern of its working for basic understanding of the setup I have.
Any one have idea about why its always shows circuit complete even without touching the wires. I have tried with 5v as well and 3.3v as well which are present on NodeMcu Board. But none of them worked properly.

try pinMode(TANK_CONNECTION, INPUT_PULLUP); since you need a pullup resistor with that circuit

OK. And value of resistor will also make a difference here?

With the INPUT_PULLUP you enable the internal pullup resistor of the MCU. Mostly this is something in the range of 10kOhm, but this is not critical here. The value of the resistor at the base of the transistor also shouldn't be critical. The transistor has only have a considerable less impedance when turned on, than the internal pullup resistor. 1kOhm seems ok. You can try smaller values, when it doesn't activate correctly after you actived the internal pullup resistor

Please try the INPUT_PULLUP. If that works, I will formulate a proper answer.

Sure I will try that in sometime and update you regarding this.

Water isn't as conductive as you might think or some conductive sediment way be bridging the connection, instead look into water level switches which don't have those issues.

@ratchetfreak I understand that. But the problem is, my both the wires are in AIR not in water yet. And yet its showing water tank full! So air looks conductive here :)

@user3201500 which is why I mentioned the conductive sediment

@ratchetfreak any suggestions for water level switch, I will be more happy if I can get some idea about how much water I have in my tank.

I'd suspect it won't be much EMI proof. And if you have long wires the INPUT_PULLUP might not be enough.

@KIIV yes they are long wires. And true, INPUT_PULLUP didn't work as well.

@chrisl any other suggestion? Because the one you gave is enough. :( No solution I can find around. But I have seen a thousand of alarms and other things work on same concept.

Sugestion is to move the transistor as close to the sensor as possible. That means 3wires (two for the power and one signal). Well, basically use something like arduino Water Sensor.

Certainly the issue is from EMI but not from the collector side as from the transistor base even the wires are shorter on that side as I understand from the comments.
It's a common mistake to let the transistor base floating, see here a different application but with the same cause and result, the transistor is turning on apparently with no reason. With the base floating the EMI current has no other path than through the transistor base where is amplified by beta ( 110 to 800 for BC547).
Put a 10Kohm resistor between the transistor base and emitter to  let a path for EMI currents to the ground. Try different values, smaller if you still have false triggering, higher if the sensor is not turning on the transistor.
Of course, use  INPUT_PULLUP but the internal resistor is to high 30 to 100 kohm, better use an external resistor arround 10k or lower form the transistor collector to 3V3 to ensure a good noise margin on the collector side to.

simulate this circuit – Schematic created using CircuitLab


text:
changing state of an LED using a pushbutton leads to unstable result
I am trying to run this code:
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState = HIGH && lastButtonState != buttonState) {
    flag = !flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

on this SimulIDE model:

<circuit reactStep="50" animate="0" type="simulide_0.1" noLinStep="10" noLinAcc="5" speed="1000000">

Node-16:
<item labelrot="0" y="-204" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-220" labelx="-16" labely="-24" Show_id="false" objectName="Node-16" itemtype="Node" id="Node-16" rotation="0"/>

Arduino Uno-4:
<item hflip="1" Show_id="true" valLabely="0" itemtype="Arduino" vflip="1" labelx="0" objectName="Arduino Uno-4" labely="-20" y="-244" Ser_Port="false" labelrot="0" rotation="0" Program="../../Google Drive/Active projects/SRL/Students/Damian2019/Simulation/20190409/noDelay_20190409/noDelay_20190409.ino.standard.hex" Ser_Monitor="false" id="Arduino Uno-4" valLabelx="0" Mhz="16" valLabRot="0" x="-148"/>

Resistor-3:
<item Unit=" O" hflip="1" Show_id="false" valLabely="6" itemtype="Resistor" Show_res="true" vflip="1" labelx="-12" objectName="Resistor-3" labely="-24" y="-164" labelrot="0" rotation="-90" Resistance="100" id="Resistor-3" valLabelx="-16" valLabRot="0" x="-220"/>

Push-2:
<item labelrot="0" y="-308" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-100" labelx="-16" labely="-24" Show_id="false" objectName="Push-2" itemtype="Push" id="Push-2" rotation="0"/>

Connector-5:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Resistor-3-lPin" labelx="-16" objectName="Connector-5" labely="-24" y="-148" endpinid="Arduino Uno-4-GND0" enodeid="Circ_eNode-6" labelrot="0" pointList="-220,-148,-220,-108,-140,-108" rotation="0" id="Connector-5" valLabelx="0" valLabRot="0" x="-220"/>

Connector-11:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-rnod" labelx="-16" objectName="Connector-11" labely="-24" y="-308" endpinid="Arduino Uno-4-V5V" enodeid="Circ_eNode-12" labelrot="0" pointList="-84,-308,44,-308,44,-148,4,-148" rotation="0" id="Connector-11" valLabelx="0" valLabRot="0" x="-84"/>

Connector-9:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-lnod" labelx="-16" objectName="Connector-9" labely="-24" y="-308" endpinid="Node-16-0" enodeid="enode-15" labelrot="0" pointList="-116,-308,-220,-308,-220,-204" rotation="0" id="Connector-9" valLabelx="0" valLabRot="0" x="-116"/>

Connector-15:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Arduino Uno-4-PD7" labelx="-16" objectName="Connector-15" labely="-24" y="-172" endpinid="Node-16-1" enodeid="enode-15" labelrot="0" pointList="-140,-172,-172,-172,-172,-204,-220,-204" rotation="0" id="Connector-15" valLabelx="0" valLabRot="0" x="-140"/>

Connector-17:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Node-16-2" labelx="-16" objectName="Connector-17" labely="-24" y="-204" endpinid="Resistor-3-rPin" enodeid="enode-15" labelrot="0" pointList="-220,-204,-220,-180" rotation="0" id="Connector-17" valLabelx="0" valLabRot="0" x="-220"/>

PlotterWidget-13:
<item modal="false" childrenRect="" normalGeometry="" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="200" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="200" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="200" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" MinVolt="-500" fullScreen="false" windowTitle="" windowIcon="" maximumWidth="1000" objectName="PlotterWidget-13" toolTip="" toolTipDuration="-1" focus="false" MaxVolt="500" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="200" minimumHeight="200" size="" focusPolicy="0" itemtype="Plotter" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

SerialPortWidget-14:
<item modal="false" childrenRect="" normalGeometry="" SettingsProp="COM1,0,3,0,0,0" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="170" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="141" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="313" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" fullScreen="false" windowTitle="Settings" windowIcon="" maximumWidth="450" objectName="SerialPortWidget-14" toolTip="" toolTipDuration="-1" focus="false" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="0" minimumHeight="0" size="" focusPolicy="0" itemtype="SerialPort" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

</circuit>

and I expect the LED to be turned on-off everytime I push the button, however the result is unstable:

I would appreciate if you could help me know if there is something wrong with my code or circuit and I should expect the same behavior on an actual hardware, or this is a simulation issue?
P.S.1. All file can also be downloaded from here.
P.S.2. I'm using this example from Arduino.org website.
P.S.3. I also tried using an actual Arduino, also implementing the suggestions below. However the issue is not resolved. You may see the video here.

You need the state-change-detection: https://www.arduino.cc/en/Tutorial/StateChangeDetection

Certain Changes in your code:
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH && lastButtonState != buttonState) {
    lastButtonState = buttonState;
    flag =!flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

Secondly your hardware model is not good.
ANODE of LED must be connected to PIN13 and Cathode to GND. And switch must be placed between 3.3 V and Pin7 only.
In your model by closing switch you are shorting 3.3V and GND. If you had provided an external pullup then you should use at minimum a 4.7K resistor value. 100ohm never works.
I don't have software for Design so I used Paint and made a sketch for you.

simulate this circuit – Schematic created using CircuitLab

ah my bad the lastButtonState = buttonState; was in the actual code but I dropped it accidentally in the example. would you be kind to draw the correct circuit? I'm not sure if I understand exactly what you mean.

The OP is using 5V, not 3.3v. And how is his circuit's switch shorting 3.3V/5V to ground? If pin7 were an output, and LOW, it would be a low resistance path to ground. It might be a good idea to put a 1K resistor on Pin7.

In your diagram, you need a current-limiting resistor on the LED or it will both draw too much current from pin13 and over-drive the LED (But I think the OP is using the built-in LED on pin 13 rather than adding an external LED.)

There's still a problem in the code: lastButtonState will always be HIGH, because it is inside the if(buttonState == HIGH) block.

I identify a few problems here:

The 100 Ohm pulldown resistor for the button is way too low. 1 kOhm to 100 kOhm is typically used here.
if( buttonState = HIGH ) does not compare, it assigns buttonState to HIGH (overwriting the value read with digitalRead(buttonPin)). Use the compare-for-equality operator == here, otherwise the if just checks if buttonState has been assigned a "truthlike" value (incidentally, HIGH is one of them).
As others have already commented, lastButtonState must be set somewhere after the if-block!

Since many Arduinos do have pullup resistors built in, I'd say: drop the resistor completely, instead initialize the button input pin (7) to use its built-in pullup resistor ... this will invert the logic and you'll have to connect the button between pin 7 and GND (i.e. swapping button and resistor), though:
    pinMode(buttonPin, INPUT_PULLUP);

This will have the same result as if you replaced the 100 Ohm resistor with a 20 kOhm resistor after swapping button and resistor -- but that resistor is now inside the Arduino. (Take care if you use "Arduino-compatible" boards; sometimes they lack the pullup resistors or have them fixed!).
There still is one problem: bouncing. Pressing a mechanical button leads to the contacts inside the button to bounce a bit against each other, leading to a very fast HIGH-LOW-HIGH-LOW-etc signal before it settles on the target state. You can alleviate this a bit by adding a delay(5) at the end of your loop(), but using a button library (e.g. Button, available in the Arduino IDE Library Manager) that debounces the signal will lead to better results most of the time.
This will lead to this code (also including the ternary operator hint by Michel Keijzers):
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW && lastButtonState != buttonState) {
    flag = !flag;
    digitalWrite(ledPin13, flag ? LOW : HIGH);
  }

  lastButtonState = buttonState;
  delay(5);
}

This should do the trick (I didn't try it, though).

OMG how could I make such a mistake!!! Thanks for pointing it out. one issue you should consider is that Arduino uno doesn't have INPUT_PULLDOWN. Apparently only Zero has this? I get the error INPUT_PULLDOWN was not declared in this scope

ok. it seems the pinMode(buttonPin, INPUT_PULLDOWN); is equivalent of pinMode(pin, INPUT); digitalWrite(pin, LOW); and pinMode(buttonPin, INPUT_PULLUP); is pinMode(pin, INPUT); digitalWrite(pin, HIGH); and that syntax doesn't work properly on some versions of Arduino IDE.

@Foad You're right, according to https://www.arduino.cc/en/Tutorial/DigitalPins INPUT_PULLDOWN seems to be rather seldom... but INPUT_PULLUP should work. Using this would invert the logic on the button pin, though. I'll edit to reflect that.

could you be kind to 1. draw the circuit using the pullup resistor 2. point me a good button library? thanks again.

@Foad I added a link to the most simple button library with debouncing from the Arduino IDE Library Manager; documentation is on its github page. Drawing the circuit must have to wait until I'm back home.

There are already great answers, but I also found out about the interrupt functionality:
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

some point:

no matter using interrupt or the methods above tho process will not achieve stable / deterministic result. The issue lies in the hardware of the push-button and there will be fluctuations which can be interpreted by the MCU. One way to alleviate is to use delay.
The
attachInterrupt has four modes LOW, Change, FALLING and RISING. The FALLING and RISING modes are the one to be used. the other two also lead to very unpredictable result.
Only pins 1 and 2 can be used for interrupts.
There is also the option to mix the two methods which you can see here, but I'm not sure if it will improve the stability.

I used this video and information on this page.

This is a comment (but could not use text alignment in a comment):
Instead of
if (flag){
  digitalWrite(ledPin13, LOW);
} else {
  digitalWrite(ledPin13, HIGH);
}

You can use:
digitalWrite(ledPin13, flag ? LOW : HIGH);

(It is functionally 100% equal though).

nice. I did not know we have ternary operator also here On Arduino language.

Actually the Arduino IDE is very similar to C++. The ternary operator is from the C language.

Very nice that Arduino language is compliant with the common C/C++ compilers.

Also several libraries are written in C++ (so you can use OO/classes); however some features are better to skip (like the Boost library if it works at all), because of dynamic memory management versus having only a few KB SRAM available.

I do not understand why they down voted you. I appreciate your support anyway.

Probably because it should be a comment (but code alignment is only possible inside an answer).

@Foad You could think of the Arduino sketch file as a part of a standard C/C++ file. Prior to compiling, the sketch is just inserted into the main file of a standard GCC build tree, included library files and hardware libraries are just copied next to it. Then gcc takes over; you could see its output if you enable verbose compiling in the Arduino IDE preferences.

@jsotola basically int 0, 1, bool false, true and LOW, HIGH are the same?

@orithena is it avr-gcc behind the scene?

@Foad Which gcc exactly is used depends on the board selected (for my boards, it's gcc-xtensa, but I only use ESP8266 boards ^^). Verbose compile output will show the exact compiler binary that is used.

@orithena how/where do I set the verbos option?

@jsotola it could be dangerous to assume values for LOW and HIGH, what if ST decides LOW is 25 and HIGH is 38? Not likely, but I wouldn't want my code to be depending on the values of LOW and HIGH.

@Foad See the screenshot at https://www.arduino.cc/en/Main/Preferences, "Show verbose output during [x] compilation".