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:
Arduino Hardware serial pins with RS485
I tried asking a question in my earlier post - SerialEvent with RS485 communication it helped me understand Hardware serial and Software serial but i had few more questions for which i started this new thread. Now i didn't write any code yet, but i will be using same code as my earlier post if i get expert inputs.
My Project - I have 6 Arduino nano which will do some simple task, mostly its one way communication at a time, like once master send message to slave i don't want immediate response slave will push button or something and then it will send response to master. So its rare that i will have two way communication at same time.
RS485 - I am going to use RS485 as distance is around 40ft.
Now my questions -
1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.
2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.
3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.
I would appreciate your inputs, which will make me decide to go on right path. Sorry i didn't post any code because my post is more to understand correct path to be followed...

https://en.wikipedia.org/wiki/RS-485

@Juraj thanks for answer but i don't think it answer any of my questions, i know function of RS-485 what i am looking for more in terms with Arduino nano with its hardware pin.

the MAX485 chip on the adapter does the RS485, not the Nano. Nano communicates only with that MAX485. if you use hardware serial for RS485 communication, how will you debug your code without Serial?

@Juraj i might have asked question incorrectly, from what i understood if i use Pin 0 & 1 which are hardware serial i don't have to use Software serial. Which you can see in my post i mentioned. Now what i wanted to know is weather i can use that SerialEvent approach for my project or not, along with RS485 which uses MAX485.

if you use hardware serial for the rs485 modules, you can't use it for Serial Monitor. USB is wired to the only one hardware serial of the 328p

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.

Thanks!!! this really helps me to follow correct direction.

source: Stack Exchange

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

sort: votes


text:
Morse Interpreter-Microphone Problem
I am working on a morse interpreter. I can now use light-sensor and a regular key as input device and want to add a mic to the system. I recieve the input convert it to text and show it on nokia 5110 lcd. And also whilst input, an led and a buzzer turns on and off simultaneously. When I use mic the led works just as it should but I do not get any correct input to the lcd. I attached Out and Gnd pins of mic just as I would attach the key and vcc to 5v.
The following is the code which I use
#define RST 12
#define CE  11
#define DC  10
#define DIN  9
#define CLK  8

#include "font.h";

unsigned long signal_len,t1,t2; //time for which button is pressed
int inputPin=2; //input pin for push button
int ledPin=4; //output pin for LED
String code=""; //string in which one alphabet is stored

void LcdWriteString(char *characters){
  while(*characters) LcdWriteCharacter(*characters++);
}

void LcdWriteCharacter(char character){
for(int i=0;i<5;i++) LcdWriteData(ASCII[character-0x20][i]);
LcdWriteData(0x00);
}
void LcdWriteData(byte dat)
{
  digitalWrite(DC, HIGH); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, dat); //transmit serial data
  digitalWrite(CE, HIGH);
}
void LcdWriteCmd(byte cmd)
{
  digitalWrite(DC, LOW); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
  digitalWrite(CE, HIGH);

}
void setup()

{
  Serial.begin(9600);
  pinMode(inputPin, INPUT_PULLUP); //internal pullup resistor is used to simplify the circuit
  pinMode(ledPin,OUTPUT);

    pinMode(RST, OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(DC, OUTPUT);
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  digitalWrite(RST, LOW);
  digitalWrite(RST, HIGH);

  LcdWriteCmd(0x21);  // LCD extended commands
  LcdWriteCmd(0xA9);  // set LCD Vop (contrast)
  LcdWriteCmd(0x04);  // set temp coefficent
  LcdWriteCmd(0x14);  // LCD bias mode 1:40
  LcdWriteCmd(0x20);  // LCD basic commands
  LcdWriteCmd(0x0C);  // LCD normal video

  for(int i=0;i<504;i++)LcdWriteData(0x00);
}

void loop()
{
NextDotDash:
  while (digitalRead(inputPin) == HIGH) {}
  t1 = millis();                            //time at button press
  digitalWrite(ledPin, HIGH);               //LED on while button pressed
  while (digitalRead(inputPin) == LOW) {}
  t2 = millis();                            //time at button release
  digitalWrite(ledPin, LOW);                //LED off on button release
  signal_len = t2 - t1;                     //time for which button is pressed
  if (signal_len > 50)                      //to account for switch debouncing
  {
    code += readio();                       //function to read dot or dash
  }
  while ((millis() - t2) < 500)           //if time between button press greater than 0.5sec, skip loop and go to next alphabet
  {
    if (digitalRead(inputPin) == LOW)
    {
      goto NextDotDash;
    }
  }
  convertor();                          //function to decipher code into alphabet
}
char readio()
{
  if (signal_len < 150 && signal_len > 20)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (signal_len > 150)
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}
void convertor()
{
  static String letters[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                             ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "E"
                            };
  int i = 0;
  if (code == ".-.-.-")
  {
    Serial.print(".");        //for break
    LcdWriteCharacter(".");
  }
  else
  {
    while (letters[i] != "E")  //loop for comparing input code with letters array
    {
      if (letters[i] == code)
      {
        Serial.print(char('A' + i));
        LcdWriteCharacter(char('A' + i));
        break;
      }
      i++;
    }
    if (letters[i] == "E")
    {
      Serial.println("");  //if input code doesn't match any letter, error
      LcdWriteCharacter("");
    }
  }
  code = "";                            //reset code to blank string
}

print the signal_len

Please don't use goto, unless you really really need it. Using this can lead to big problems. There is a reason, why it is seldomly used in C/C+. You can just put the convertor() inside the if, where the goto is, and add a break after it.

Depending on what "mic" you use, you may also need a pre-amplifier

I attached Out and Gnd pins of mic just as I would attach the key and
  vcc to 5v.

This can't work. Unlike the key, the microphone is an analog device that
will output a continuously varying analog signal. If you expose it to a
pure tone it will output a sine wave. If you sing a note in front of it,
it will pick not only the sine but also a lot of harmonics. In any case,
it will also pick the ambient noise.
What you need to do is somehow determine the amplitude of the sound
signal, then compare that to some threshold in order to decide whether
the amplitude is high enough to be considered “on”. You could use a
diode-based peak detector and a comparator. Doing all this in code is
kind of tricky. You may want to take a look at this sound-level meter
sketch, but note that a software peak detection could be
simpler than the true-RMS intensity detection implemented in that
sketch.

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


text:
7 LED Number Display
I need to write a string of number such as 1234567 on a 7 LED display. For example 1 will be lit up on display for 0.5 seconds, it will turn off then 2 will light up and so on. In the end I need to display "-" for 2 seconds. I also added the image of the given task.
The following is the code I wrote.
I would like to ask if it is the correct, and are there any flaws.
  const int LEDa=13;
  const int LEDb=12;
  const int LEDc=11;
  const int LEDd=10;
  const int LEDe=9;
  const int LEDf=8;
  const int LEDg=7;

  int i;
  int a;

  void setup() {

    pinMode(LEDa, OUTPUT);
    pinMode(LEDb, OUTPUT);
    pinMode(LEDc, OUTPUT);
    pinMode(LEDd, OUTPUT);
    pinMode(LEDe, OUTPUT);
    pinMode(LEDf, OUTPUT);
    pinMode(LEDg, OUTPUT);

  }

  void loop() {
    int array[7]= {1,8,0,5,1,0,0};
    for(i=0;i<8;i++){
      a= array[i];
      }
        switch(a){
          case 1:
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 2:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 3:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 4:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 5:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDa,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDa,LOW);
          break;
          case 6:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 7:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 8:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          break;
          case 9:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          break;
          case 0:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDe,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDf,LOW);
          break;
          }
          if(i=8){
            digitalWrite(LEDg,HIGH);
            delay(2000);
            digitalWrite(LEDg,LOW);
            }
          }

So did you actually try to see if the code worked?  You are asking people simply to check the code for errors.

the switch is outside for

I have not yet constructed a circuit. This was an educational type of code that I needed to write. Besides asking fo error check I was wondering how can I make it more concise without the need of using cases, which in this case I got the answer for it.

You might be interested in my implementation. I’m using a shift register instead of a bunch of the Arduino’s pins, but it might give you some ideas. Check out the tests to see how it’s used. https://github.com/rubberduck203/digital-thermometer/blob/master/src/SevenSegment.cpp

my comment is kind of picky, but this is programming after all ...... following instructions exactly is important  ....... your description of the problem and the description in the picture differ ...... you  said it will turn off .... there is no such directive in the picture ...... perhaps, going from 1 to 2 means leave segment "b" on, turn off segment "c" and turn on segments "a","g" and "d"

I see 3 errors:

You define the array to have 7 elements, but in the for loop, you count 8 elements, by using i<8 (Array indizes start at 0, so 0 will be the first and 6 will be the last element). Currently you try to access an array element, that does not exist.
The if statement is also not useful here. In your current code you check for i being equal to 8, but it will never be 8 inside of the for loop, because you used the condition i<8. To display the last - after the number, you should put the code after the for loop.
In the same if statement you write i=8, but a single equality sign means assignment. The value 8 will be assigned to the variable i and this assignment is true everytime. If you want to test equality use == (double equality signs)

Tip: You can make your code smaller by defining functions for codes parts, that get repeated often (for example the code to turn off all LEDs).
Tip2: If you want the code to be very efficient, you can change the pins to use one single port. Then you can change all the pins of the port at once, by assigning a single byte to it. You can save these bytes in an array. This will make your code way shorter, but you also need a deeper understanding about port manipulations. You can choose, what you want to do.

It looks like it is mostly correct, although that is a very long-winded way to set 7 segments to multiple values. I would be more inclined to set up an array of bytes where 7 bits of each byte contain ones/zeros to control the LEDs. Then you could skip the massive switch statement and simply loop through the array of bytes.
One mistake: if(i=8) should be if (i == 8). (= is an assignment. You want the == comparison operator.) Your code won't work correctly until you fix that.


text:
Reading inside critical sections from ISR
Is it necessary to protect reads of volatile variables in critical sections when using interrupts? Or are critical sections only required when concurrently writing variables?
Here is an example of a variable written within an ISR which is protected with a critical section:
void loop() {
    portENTER_CRITICAL(&mux);
    uint other = variable_written_from_isr + 1;
    portEXIT_CRITICAL(&mux);
}

What will happen if an interrupt changes variable_written_from_isr while it is being read? Would anything worse that inconsistencies happen?
Here is an opposite example where a variable is written from an interrupt and read from the loop (or a task):
void IRAM_ATTR handleInterrupt() {
    portENTER_CRITICAL_ISR(&mux);
    uint other = variable_written_from_loop + 1;
    portEXIT_CRITICAL_ISR(&mux);
}

Please note that I aware of stdatomic. I am mainly interested in understanding the behavior of concurrent access in the context of interrupts.

What will happen if an interrupt changes variable_written_from_isr while it is being read? ..... there will be no interrupt because  portENTER_CRITICAL(&mux); disables interrupts

Thank you for pointing it out. I was expecting the interrupt execution to be delayed until the critical section is exited.

You should use critical sections around any operations that could potentially be affected by the execution of an ISR (or which could affect an ISR) that aren't atomic.
Simply put, an atomic instruction is one which can be represented by a single assembly language instruction. You can't interrupt during the execution of an assembly instruction, so anything that only takes one instruction can't be interrupted until it's complete.
Examples would be moving a value from one 8-bit variable (assuming an 8-bit architecture) into a register, storing an 8-bit value into memory, etc.
What instructions are likely to be atomic very much depends on the architecture that you are working on.  The only real way to be sure is to compile the code into assembly language and examine what is produced. Of course, that means learning the assembly language of your chosen architecture.
However: if in doubt, use a critical section. Better to be safe than sorry. But keep those critical sections as short as possible to not disturb the interrupts more than is needed.
For example, instead of starting a critical section, reading some volatile value, doing some calculations with it, and writing it elsewhere, you should use the critical section just to read the volatile value into a temporary variable. After the critical section, you can then do your calculations and things with it, while the interrupt is then free to be called again.

A non-atomic read in your main code of a 2-or-more-byte variable that can be written in an interrupt routine does need to be protected. In this case, the variable itself can't be corrupted, but the value read from it by your main code might be - in the case where the main code is reading the shared variable one byte at a time, and gets interrupted between two of those byte-reads.


text:
I can't send GPS data to server
I am trying to send gps location data every 3 seconds to mqtt server if it's updated but my device shows weird stack errors and resets. What i am missing?
I am using tinygps++ and pubsubclient as libraries.
LOOP:
void loop() {
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWifi();
  }
  if (WiFi.status() == WL_CONNECTED && !client.connected())
  {
    mqtt_connect();
  }
  client.loop();

  if (WiFi.status() == WL_CONNECTED && client.connected())
  {
    long now = millis();
    if (ss.available() > 0)
    {
      if (now - lastMsg > 3000) {
        lastMsg = now;
        gps.encode(ss.read());
        display.setTextSize(1);
        display.setTextColor(WHITE);
        display.setCursor(0, 0);
        display.println("Lat:" + String(gps.location.lat(), 6));
        display.setCursor(0, 10);
        display.println("Lng:" + String(gps.location.lng(), 6));
        Serial.print("Latitude  : ");
        Serial.println(gps.location.lat(), 5);
        Serial.print("Longitude : ");
        Serial.println(gps.location.lng(), 4);
        if (gps.location.isUpdated())
        {
          String pos = String(gps.location.lat(), 6) + ";" + String(gps.location.lng(), 6);
          client.publish(mqtt_output, pos.c_str());
          display.setCursor(0, 50);
          display.println("Data Sent");
          m_alert();
        }
        display.setCursor(0, 30);
        display.println("Satellites: " + gps.satellites.value());
        display.setCursor(0, 40);
        display.println("HDOP: " + gps.hdop.value());
        display.display();
      }
    }
  }
}

connectWifi :
void connectWifi() {
  Serial.println('\n');

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print("*"); Serial.print(' ');
  }
  w_alert();
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

mqtt_connect :
void mqtt_connect() {
  Serial.print(F("MQTT Connecting..."));

  char* clientId = "app";
  while (!client.connected()) {
    mqttConnectAttempt = millis();
    if (client.connect(clientId, mqtt_user, mqtt_pass)) {
      s_alert();
      Serial.println(F("connected"));
      String ready = "Connection Success!\r\n";
      client.publish(mqtt_output, ready.c_str());
      client.subscribe(mqtt_output);
    }
    else {
      Serial.print(F("Failure, rc="));
      Serial.print(client.state());
      Serial.println(F("Connecting Again in "));
      Serial.print(MQTT_PERIOD + " Seconds");
      delay(MQTT_PERIOD);
    }
  }
}

you are missing an explanation of what weird stack errors and resets means

reduce you code .... send a single fixed value to the MQTT server ...... what errors do you get?

Do you get any of your Serial.print output at all?


text:
BLE splitting string data
I am working with BLE 4.2 (ESP32) that sends IMU (accel, gyro, mag) data to my mobile app (Android). Unfortunately, I can send only 20 bytes in one packet.
This is the code I have: (I am connecting the float raw data (ax, ay,...my, mz...etc) read from the accelerometer.)
char myConcatenation[20];
char myStr[","];
.
.
.
 sprintf(myConcatenation,"%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f", ax, myStr, ay, myStr, az, myStr,gx,myStr, gy, myStr, gz, myStr, mx, myStr, my, myStr, mz, myStr, yaw, myStr, pitch, myStr, roll);
.
.
.
pCharacteristic->setValue(myConcatenation);

pCharacteristic->notify(); // Send the value to the app!

Do you know how to construct a code so I would notify the app with new data of 20 Byte length? For example, each packet constructed of every sensor reading:
1. (ax, ay, az)
2. (gx, gy, gz)
3. (mx, my, mz)
4. (yaw, pitch, roll)

Thank you for any advice and patience with my poor programming skills.

How is this related to arduino?

I am using Arduino IDE and I didn't know where else to put this. Sorry if it doesn't fit the thread topic.


text:
What are the better options to the basic Arduino Serial Plotter?
Arduino Serial Plotter does not allow analysis or saving of data. What are the best serial data graphing software (preferably free, but i don't mind if it's paid as long as it's better than the bare-bones Arduino Serial Plotter)?

It should work well with Arduino
It should allow plotting several variables on the same graph
Allow exporting data to CSV so i can show it in Excel.

you can print CSV to Serial Monitor or to SD card file and then process it

I tend to just save the serial data into a file: stty -F /dev/ttyACM0 raw 9600 && cat /dev/ttyACM0 > data.tsv, then graph it with gnuplot. But it's not real-time serial plotting, so I don't know if it could count as an answer...

you could write an app that does what you want using Processing .... http://processing.org ... there may be example programs that do what you want

If you are willing to install the 'Processing' JAVA environment take a look at: https://github.com/digamesystems/DigameSerialPlotter

Custom devices require custom solutions.
I suggest using Python (don't be scared).
This tutorial shows us how to read data from serial and save it to .csv file. You don't have to use a file. For example you can modify it to use an in memory list, and save just values from last 30 seconds. You can also read several values, and not just one.
import serial
import time
import csv

ser = serial.Serial('/dev/ttyACM0')
ser.flushInput()

while True:
    try:
        ser_bytes = ser.readline()
        decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        print(decoded_bytes)
        with open("test_data.csv","a") as f:
            writer = csv.writer(f,delimiter=",")
            writer.writerow([time.time(),decoded_bytes])
    except:
        print("Keyboard Interrupt")
        break

This tutorial (and this one) shows you how very quickly to show a sophisticated plot of the data you collected. You can even make a plot that shows several graphs and updates in real time.
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Don't be scared it's not black magic. It just takes few days to understand how things work.


text:
Can i use Arduino IDE with the Wemos D1 R2 AND also use its ESP8266 module to send AT commands?
I have recently started digging into ESP8266 and learned a little about AT commands and i would really like to add the Wi-Fi functionality in my electronics project, which already uses an Arduino UNO R3. I think it would be much easier to use the Wemos D1 R2 since it is basically an UNO + ESP8266. Here is a link to the official product information page: https://wiki.wemos.cc/products:d1:d1 and its schematic: https://wiki.wemos.cc/_media/products:d1:d1_v2.0.0.pdf
I would like to know if it's possible to use the Arduino IDE to program on the Wemos D1 as i do with the normal UNO but also at the same time, be able to send AT commands using its on-board ESP8266?

A year ago I ported my project from Uno with esp8266 (Uno WiFi Dev Ed) to Wemos D1 R2.
Wemos D1 R2 board has esp8266 as the only MCU. The AT firmware is an application running in the esp8266. An Arduino sketch with esp8266 boards package is an application too, so it replaces the AT firmware.
Instead of AT commands you will use for networking the WiFi library of the esp8266 arduino package. It is much simpler and there are many examples.
The esp8266 and the D1 R2 board have 3.3 V logic level on pins. So be careful with inputs and check if your devices will read the 3.3 V as HIGH.
In code use Dx constants matching the labels on the board. D1 R2 has less pins then Uno. I recommend to use I2C devices if possible. I had a Grove Base shield on D1 R2, so I have a mapping of D1 R2 pins to 'Uno' pins.
Some of the esp8266 pins are read at boot as boot configuration. Pins D3 (io 0)
and D4 (io 2) have pull-up on board and pin D8 (io 15) has pull-down on board. Not all devices will work on this pins. Here is a pin overview of the NodeMcu and Wemos boards.
The esp8266 has only one ADC pin. The A0 of the esp8266 can read 0 to 1 V. Wemos boards have a voltage divider on A0 so the board's pin can read 0 to 3.3 V. Don't read A0 in every loop. WiFi part of the esp8266 uses the ADC hardware too and continuous reading of A0 interferes with WiFi operations.
The Wemos D1 R2 has a strong power regulator 7 to 20 V for Vin and power jack. You can power devices from 5V and 3.3V pin. I use Grove relay modules powered from 5V pin and controlled by logic signal at 3.3 V.


text:
Is this Arduino UNO running at 12 MHz?
I am wondering if this Arduino UNO R3 clone is clocked at 12 MHz instead of the standard 16 MHz? On the board, you can see there is 12.000 written on the crystal oscillator.

But maybe it's not the MCU clock speed? I found this other clone, which has 2 crystal oscillators?! One is 12 MHz and the other one is 16 MHz.

I can't figure out what's happening with these boards... Are these sporting faster or slower speeds? The original Arduino UNO R3 has only one 16 MHz crystal oscillator.

look at the leftmost component between C5 and C6

The 12MHz crystal is for the USB interface.
The main MCU uses a very small 16MHz resonator, which you can see between C5 and C6.

The 16 MHz resonator, a 3-pin part, can be seen between C5 and C6 in the first picture.
The 12 MHz is for the CH340 as noted.
So it's not an Uno, but a clone ripoff, as an Uno would have a Atmega16U2 for the USB.


text:
What sensor do I use to measure the intensity of direct sunlight?
I'm trying to measure how bright the day is on a particular day to see how it affects plant growth. The brightest sun can be 120,000 lux. It possible to measure such a large brightness? What sensor do I use?
The best options I've found is the BH1750FVI since its sheet says, "[i]t is possible to detect min. 0.11 lx, max. 100000 lx"
However, it still doesn't go high enough.
Note: I live "only" 3,494 km (2171 miles) from the equator, and it can get fairly bright here.

You may not put a sensor in direct sunlight. That is too bright and too hot. Only a solar cell can deal with direct sunlight. For the accurate number of lux, use a accurate sensor under a semi-transparent filter. Extra care should be taken that the sensor does not get too hot.

I thing a simple LDR would work just as well. You won't get a nice calibrated LUX value, but you'd be able to compare different day and/or time, and see the difference in brightness.

PS the BH1750 can only measure up to 100000lx. That doesn't mean it can't handle more. It can, but will clip the value. The measurement also depends on the angle between the sensor and the sun as you can see in the graphs on page 3 of the datasheet. So you could aim the sensor slightly to the north, so the sensor values stay below the maximum value, and doesn't clip.

Maximum operating temperature for the BH1750FVI is 85  deg. Celsius.

You can use a photo resistor. It is also known as an  LDR (Light dependent resistors) and here is a great tutorial to do just that. You can also find a conversion from the 8-bit analog value to lumens if you wish. Here is a tutorial:
https://www.instructables.com/id/Measuring-Light-Using-Light-Sensor/
You can also use a LUX which is the advanced version of a LDR. Here is a tutorial:
https://www.instructables.com/id/How-to-Measure-LUX-With-Arduino/

What about SiLabs SI11xx Sensors? Some of them are designed for direct sunlight.


text:
Where can I find SerialMonitor.java in installed Arduino IDE 1.8.13?
I have found the git source for SerialMonitor (Arduino/app/src/processing/app/*) but unable to find it in the installed Arduino IDE. I am using Ubuntu 20.04 64-bit.
I want to make changes to it, not so much a terminal emulator but just perform simple ASCII control characters like backspace (0x08). Some advice on replacing it would be appreciated too; I guess it involves jar files (I am not a java developer).
I have read elsewhere about (and used) various other terminal-type programs, but of course they stop the IDE from uploading sketches. So not much good for development.
Or if anyone knows of an already-improved Serial Monitor, and how to install it for the IDE, then that could be perfect.

IDE development is not an Arduino topic. Java is compiled so you will not find the source codes in distribution. only the built-in Serial Monitor knows when the IDE uploads

@Juraj please advise where https://github.com/arduino/Arduino topic discussions take place, if not in arduino.stackexchange.com

https://groups.google.com/a/arduino.cc/forum/#!forum/developers

After some searching, I found that Building Arduino - Steps for First Time Setup was good. It was tricky to find; most searches for 'Build Arduino' assume it's a project with an Arduino, rather than the IDE.
By building this way, I could change the source, then inside the build folder run ant run. So, no need to actually know where it goes.
I had a problem with it grumbling about
Incorrect IDE installation folder:  Your copy of the IDE is installed in a subfolder of your sketchbook. Please move the IDE to another folder.
which would have been more useful if it had said WHAT settings needed changing.
It turns out that preferences.txt had a conflict with settings sketchbook.path and runtime.ide.path. I changed sketchbook.path. All is now good.

Ah, yes. The anonymous down-voters. Some people just don't want this knowledge shared,

You can't just "find and replace" that file.
Java isn't distributed as source code. It's compiled "bytecode" that isn't modifiable by a human.
You would need to download all the source code, make your changes to it, and then recompile it.
Or, simpler: just use a more capable serial terminal program, such as "Putty" or "TeraTerm" in Windows, or "Minicom" or "Screen" on Linux. I have no idea what is available for OS X.

Screen works out of box in OS X too.

A) I did mention that jar files could be involved
B) Perhaps I'm not human, but I have successfully patched binary distribution images to fix bugs that annoyed me e.g. Copy-protected games to stop diskette wearing out, Ashton Tate/Borland DBase III & IV,
C) I HAVE downloaded all the Ardiuno git repository; I though that that was obvious. If I haven't got ALL the source, I'm still prepared to do so. Not only can I run compilers, I write & modify both compilers and decompilers.
D) As mentioned, I have and can run more capable terminal programs, BUT THEY STOP THE IDE FROM UPLOADING SKETCHES

The ide is crude and it only provides crude facilities. If you don't like it then write your own. You sound more than capable.


text:
Where are the Arduino Function Unit Tests kept? I want to submit a fix for a faulty Arduino function
I have coded a fix for a major problem with the Arduino map function (in Arduino.h & arduino/avr/cores/arduino/WMath.cpp).
I submitted it as a comment to map function causes huge errors when mapping to small intervals due to integer truncation #10382 but heard nothing so far.
I thought it might be handled quicker if I can submit it as a Pull Request with Unit Tests to A) expose how and why map is faulty and B) show how my solution fixes the problem.

You should be submitting requests about the API to the API repository, not the core repository: https://github.com/arduino/ArduinoCore-API

I am not aware of any unit tests within the Arduino core. I suggest you commit the code change with no tests, add a small test sketch (mostly Serial.println()) within the “cover letter” of the pull request, and state the results you get with and without the patch applied.

@Majenko note that the API is fine. It's the code in the core that does not implement the API properly (assuming that arduino/avr/cores/arduino/WMath.cpp is in the core)


text:
Program Arduino via UART from ESP8266 SPIFFS
I have built a custom board that has an ATmega328p connected to an ESP8266 module via UART. I am currently programming the ATmega328p using a USBtiny programmer via an SPI header. The ESP8266 module is programmed via an FTDI cable connected the the UART.
Firmware for both are created in Arduino IDE.
I have set up a webserver on the ESP that allows for files to be uploaded to the SPIFFS via FTP. I would like to be able to upload a hex file for the ATmega and then have the ESP program the ATmega via the UART connection. A GPIO on the ESP controls a transistor that can pull the reset pin on the ATmega to ground.
I know I need a bootloader on the ATmega (e.g. optiboot), but I don't know what I need to make the ESP do to trigger the bootloader and flash the ATmega. I'm thinking I need something like:
void initialiseAtmegaFlash () {
  // Trigger the bootloader to accept incoming hex over UART
}

void flashHexToAtmega (File atmegaHex) {
  for (uint32_t i = 0; i < atmegaHex.size(); ++i) {
    // Handle timing of sending byte by byte over serial... or chunk by chunk?
  }
}

You need to start by understanding the STK500 protocol. Read and digest: http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf

you can use the dfu library from here https://github.com/jandrassy/arduino-firmware-wifilink#atmega328p-sketch-ota-upload-support

That dfu library looks like I need to initiate the upload from Arduino IDE on the same network. The STK500 protocol documentation looks like the sort of thing I need. I was hoping there might be a neat library already, but looks like the info I need to get the functionality.

https://github.com/ciminaghi/libdfu

did u managed to do it? If yes, kindly share the details with me also and the connections.

To answer my own question in case someone else ends up here, the library Juraj suggested (https://github.com/ciminaghi/libdfu) looks like it does the job. I also found another project doing something similar (https://github.com/rene-win/esp_avr_programmer). Also the STK500 docs linked to by Majenko (http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf) are really useful for understanding the nuts and bolts!


text:
Measure Vcc on ATtiny13a?
I am trying to figure out if I can measure the Vcc of attiny13a, but the code I use for arduino's and attiny85 does not work. This is where I got the code from. I know that it works by using the 1.1v reference and the ADC, and in the attiny13a datasheet it says that it has these, but I can't get it to work.

The code you linked to measures the 1.1 V internal reference using
Vcc as a reference. The ATtiny13A cannot do that. It does have a 1.1 V
internal reference, but it can only use it as a reference for the ADC,
not as a measured channel.
What you can do, if you don't mind adding extra hardware, is divide Vcc
with some resistors in order to get a voltage proportional to Vcc but
lower than 1.1 V. Then use the 1.1 V reference to measure that
voltage. In other words, measure a scaled-down Vcc against the
1.1 V reference instead of measuring the 1.1 V reference
against Vcc. The datasheet should help you with the details.

I tried this and it worked! I don't understand to much about the bit settings on the datasheet but with the help of a tutorial I got it to work Thankyou


text:
TinyGPS++ Question about gps.encode(ss.read())
I am trying to make an oled gps display, however when looking at multiple examples and other people's code, I am seeing that people are using different methods. I see some code that has gps.encode(ss.read()); and other people use if gps.encode(ss.read()). I am confused on why this is. Also, people either use .isUpdated, or .isValid, when checking for location/speed, etc. On the TinyGPS++ page it talks about these, but does not say what should be used for certain applications.

it's not really about what should be used for certain application ... it is about what does it do? ... the library takes serial input data and assembles it into a GPS data structure ... certain "flags" are set as the GPS data is assembled, if data has changed ... if a certain function is useful in your program, then use it ... there is no specific use for any of the functions ... so your best start is to learn what ss.read() does, then what gps.encode() does, and so on.

From http://arduiniana.org/libraries/tinygpsplus/
Validity, Update status, and Age
You can examine an object’s value at any time, but unless TinyGPS++ has recently been fed from the GPS, it should not be considered valid and up-to-date. The isValid() method will tell you whether the object contains any valid data and is safe to query.
Similarly, isUpdated() indicates whether the object’s value has been updated (not necessarily changed) since the last time you queried it.
Lastly, if you want to know how stale an object’s data is, call its age() method, which returns the number of milliseconds since its last update. If this returns a value greater than 1500 or so, it may be a sign of a problem like a lost fix.


text:
How to turn the digital pin to analog pin?
I am using a 10 IR sensor array and they use analog pins. I am using a motor shield for the Uno. So I cannot use the Mega. I have only five analog pins I need 8. How can I do it?

The Mega can take shields made for the Uno.

you have 6 analog input pins A0, A1, A2, A3, A4, A5. some Uno clones with SMD ATmega328p have A6, A7 accessible (maybe Robotdyn)

which sensors are you using? ... how are the sensors connected?

You might like to use a analog multiplexer.

Use an I2C or SPI connected ADC chip.

You can use an external A/D converter, there are a lot of varieties in a lot of price ranges for the Arduino. Check your favorite online source. That will require two of your existing analog pins for the I2C interface but you will gain back many more depending on your choice. If you choose to use SPI that will take 4 pins.


text:
Multi MFRC522 Slave AND only mifare read
Multiple MFRC522 Connections (https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi)
I only get from each slave with an ID card; I want to print a defined barcode on the slave address. Briefly; The MOSI line does not matter! Is the 2nd case daisy chain method in this link suitable for me? would like to ask you, dear friends, how should I go about it?
<Regards

what is ID card?

There is only one daisy chained example shown in the article. ;-) Do you know, that the slaves that are chained, must be able to transport the incomming (MOSI) data to the outgoing port (MISO). This is not the case for all slave devices. I do not think the MFRC522 allows this mode. Why not use the multi slave setup from the example before the daisy chain example? Then you will also be able to select the slave you want to read from.

Tomorrow, I will install 7 mfrc522.  SS pin (SDA) will not be enough.  Is it necessary to use the 74HC238?  I guess I should also connect pull-up (10k) to SDA and SCK wires .. I read the problem of impedance .. I will have a particular question;  Where do I get the name or code of the slave device.  Thanks for your answer

evet. geç oldu cevabım özür dilerim. Normal Seçici SS leri ayrı ayrı kullanarak sorunu çözdüm. Burada max. kaç adet bağlanır bilmiyorum. Ama; 5 adet şimdilik işimi görür gibi.


text:
Atmega 328P in Arduino
Does anyone know what it means by the Atmega 328p has 131 instructions? And could you give an example of how any one of these 131 instructions look like?
Thanks in advance!!

chapter 31 in http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

and https://en.wikipedia.org/wiki/Assembly_language

A CPU or MCU uses very basic instructions which are executed.
If you write code in a program language (like in Arduino IDE), the sketch is converted into many instructions (by the compiler and linker).
The instruction set can be found here.
An example is:
ADC Rd, Rr: Adds two registers and the contents of the C flag and places the result in the destination register Rd.
A CPU/MCU uses registers, which can be seen as very fast 'variables', mostly there are quite few of them, and all operators (like +, -, *, /) are carried out using these registers.
If you are just starting Arduino, it's not so useful to dive into this, the compiler/linker will take care of these 'details'; just be glad you don't have to write in assembly (anymore).

Thanks so much for your explanation!! It's very clear and just what I was looking for!

You're welcome!


text:
Can the DHT11 give reasonable readings?
I bought a batch of ESP8266-01 and DHT11 on ebay.
The sensors give data, but the datasheet say +/- 2 degrees. Who can live with that? Well, they claim the repeatability is 0.2 degrees, so I guess they could be calibrated.
But thet are not stable. They start a few degrees over room temperature, but gradually the reading is up to 33 degrees, more than 10 degrees too high.
Could it be the proximity of the ESP8266 giving off heat? Or are the sensors themselves heating up when reading at one read every two seconds?

I would suspect heat from the 8266.  Can you add a second sensor at a little bit of a distance and compare the two values as it runs for a bit

the sensor only uses microamps, it's not self-heating. you might try the DHT22; twice as good. try reading every 10 seconds and check the linearity.

I have ordered a handful of DS18B20 onewire sensors. I have had more success with these before, they are waterproof, and I can put more sensors on one ESP.

more than 10 degrees too high ... how do you know? ... you did not say that you used a thermometer to verify the reading

i'd suspect the physical placement of the sensor. perhaps its near an incandescent lamp or tube ?

@jsotola I know it's more than 10 degrees off, because I don't run my room temperature above 22C in winter. It's in the hallway now, near the front door, so no direct light either.

did you verify the reading with a thermometer?  ... strap the DHT11 to a thermometer and confirm the suspected discrepancy

It could be the ESP8266, try physically separating the DHT11, but I'm guessing that that will only help slightly.
Do you have some way of reliably calibrating the sensors? If not, then even if you are getting consistent readings, you'll have a hard time knowing how accurate your readings are.
While they're typically more expensive, it might be prudent to buy an infrared temperature sensor. If you have the budget, replacing the DHT11s with IR temperature sensors might just be a better solution, I saw that Sparkfun's MLX90614 was accurate within +/- 0.5 degrees Celsius. If you don't have the budget to replace your DHT11s, or don't want to be wasteful, perhaps you just buy one IR temperature sensor to use as a sanity check. These should be more reliable than DHT11s and you could even write a sketch to calibrate them based on the IR temperature sensor's readings.

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


text:
D1 Mini; is there a fuse?
While this board (listed on ebay as D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.
I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.
So something has burned between the 5V on the usb and the 5V on the regulator.
I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.
Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?
Or could the short between 5V and GND have caused a track to burn?

Hard to tell. Examine it closely with a magnifier and look for holes and cracks in components. There may be a diode there that has gone...

Looking at a possible schematic, yes, there is a diode (called D2 on the schematic) that would likely blow if you shorted 5V to GND.

Looks like it may be just left of the USB socket (small and black)...

I think I may have a D1 Mini somewhere here. If I can find it I'll have a look at blowing it up (AKA "destructive testing") to see what happens.

Found my D1 Mini. It's different to yours. Mine is genuine Wemos (version 2.3.0) and it does include a PTC fuse.

diodes on cheap wemos boards are barely adequate for the MCU and burn on high loads, not just shorts.

@Majenko Mine is similar to the one in the pic above, more pics here: https://imgur.com/a/xhx1ctn Any clue which one's the diode that needs replacing?

@adeelx Immediately to the left of the USB port is a ceramic capacitor. Directly above that is the diode.

It's remarkable how the maker managed to misalign the USB connector by that much and get away with it.

Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.

Indeed; I measure about 0,4v across the diode at the good board and 2.9v at the bad board.
I don't have SMD-diodes at hand, but I guess I'll solder a wire from the usb-end to plug into my breadboard while testing.

@Lenne Did you figure out which diode needs replacing? I'm in the same condition and would like to salvage the board if possible.

I came here because of a dead Wemos D1 Mini Pro. One which I managed to kill in exactly the same way (shorting out something while trying to measure a voltage - most likely I shorted the 5V and GND as well :) ).
The symptoms were identical - could power the board via 5V or 3V3, but not via USB. And they were solved after replacing the diode - or, more accurately, bypassing it, since I was unable to find an SMD Schottky to replace it with.
I won't tell you the rest of the story (where I first blamed it on the voltage regulator and replaced that), to save myself the embarassment :)

I can confirm that the component, which on my Mini clones (which have an almost identical layout) is the tiny black component pictured at the upper left corner of the USB shielding, is a diode and can be blown pretty easily by shorting +5 to Gnd. I did as you Lenne proposed and jumpered it with a tiny wire and recovered the device.

I've done exactly the same as the above folks. But I did find S4 diodes on ebay for $2.99/ 100. I've ordered them up. meanwhile I'll jumper around it.

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


text:
Where can I find the complete list of Arduino Serial Command & Query Strings?
I am planning to use the Arduino as a replacement for a USB-Controlled Digital I/O device, which will be integrated into an existing C++ software package that I created. I understand that the Arduino acts like a Serial device to a PC. Every serial device can be controlled by its own set of commands and queries. However, the only commands and queries that I've found for the Arduino involve flashing one-time programming to it from the "inside" rather than providing real-time automated control from the "outside."
Can anyone tell me where can I find the complete list of Arduino serial command & query strings? Thanks.

You probably want to write your own application-specif command interpreter on the Arduino. You may want to take a look at this Simple Arduino command line interpreter for inspiration.

The Arduino has no "standard" serial commands.
It is a programmable device which you have to program yourself. The only serial commands it can respond to are the serial commands you yourself program it to respond to.
There are projects around that provide a serial interface, but they are generally designed for one specific purpose, and the commands or protocol they implement are unique to that project.
The closest to what you are asking for is the Firmata firmware, which comes with the IDE, and can be used to control the Arduino through the serial port using programs on your PC.


text:
Can I use arduino pro micro rx tx as digital pins
I'm using arduino pro micro Atmega32u4 5v 16Mhz
I want to use it to make a HID Keyboard and Mouse but I ran out of pins so I was wondering if I can use the RX and TX pins as digital input pins. Will it work? Will it affect the communication of the arduino  to the computer?

Should be fine. Communication is done natively in USB with the ATmega32u4, TX and RX (D0, D1) are free for other tasks.

RX/TX pins on Micro are Serial1

Not a problem on the Pro Micro. You tag also mentions Pro Mini. On those it could be a problem. If your code doesn't use Serial, then there is no problem there. But there could still be a problem during uploading the code. If for example a button is connected to either pin, and this button is pressed, it could block uploading, and could even cause a short if the other side of the button is directly connected to Vcc or GND.

Welcome to ASE.

Communication between the PC and the Arduino Pro Micro happens through the USB, unlike the Arduino Uno and Mega, which use the RX and TX lines.
In your case, the USB pins of the Micro are used to communicate with the PC. Hence, the RX and TX pins are available for digital input and output operations.

Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.
You can use those pins for digital operation with no problems, you just won't be able to use Serial1 for communication with serial peripherals.


text:
How to use PWM with DRV8870?
I'm using Arduino nano and I'm struggling working with the DRV8870 IC on PWM mode.
When I use analogWrite(_pin, duty_cycle); the motor makes weird noises.
I thought it's because of the PWM frequency so I tried to change it using
TCCR1B = TCCR1B & B11111000 | B00000011; but it didn't work out.
Texas Instruments wrote this in their pdf:
"When using PWM, switching between driving and braking typically works best. For example, to drive a motor forward with 50% of the maximum RPM, IN1 = 1 and IN2 = 0 during the driving period, and IN1 = 1 and IN2 = 1 during the other period."
drv8870_pdf

Are you sure you are changing correct timer? Only pins 9 and 10 are generated by Timer1

analogWrite(_pin, duty_cycle) will work properly only on pins that support PWM. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. Check the following link to find yours:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


text:
ESP12F works indefinitely, then gets stuck in unrecoverable hardware WDT "boot loop"?
I have a sketch running on a number of ESP12F modules (AiThinker). They can work for months on end, can be power cycled, can be moved around, etc. It is a complex sketch with multiple parts and is still using the 2.4.2 core.
What I've seen happen on an increasing number of these is that the modules can get stuck in some kind of boot loop, that I am suspecting is the hardware watchdog kicking in.
On resetting a faulty device the following is printed to the debug port at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

I think this equates to:

External pin reset or wake up from deep sleep
Booting from flash
SDIO High Speed V2 IO / UART1 (I have no been able to find any explaination to what this actually means, and many posts reccomend essentially ignoring!)

About 1.5 seconds later, the following is printed at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

The only difference here I think is that (3, 7) has changed to (3,6) which equatest to:

SDIO Low Speed V1 IO / UART1 (again, no idea what this means)

After this, every 5.5 seconds (roughly) the following is printed, this time at 115200:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

This is the same ouput as before, just output at a different baud rate.
This boot loop will continue indefinitely (I left one in this state for days to see if anything happened). Power cycling it just takes it back to the first debug messages, then just sits back in the boot loop.
No serial output from my actual sketch is ever seen. This, along with the 5.5ish second loop leads me to think that the hardware watchdog is triggering and not even allowing my sketch to run. Does that sound right?
This currently seems to be affecting around 5 out of 50 devices. Most are happily running along without a care. The affected devices can be reflashed, seemingly successfully, and will run as they should, but after about 5-10 power cycles they fall back into this loop. It's like the hardware has been permanently damaged and can never be relied on again!
Has anyone seen this behaviour before? What are people's opinions on what might have caused this? Can bad code permanently corrupt the hardware in the way I think I am seeing?


text:
Press button and Send Message Error
The problem is that sometime I don't even need to press the button and it sent message and keep on sending continuously.
What I want to do is that once the button is pressed, sent 1 message.
I cannot figure out why it is happening. Please help me to figure out.
 #define CUSTOM_SETTINGS
    #define INCLUDE_GPS_SHIELD
    #define INCLUDE_SMS_SHIELD
    #define INCLUDE_VIBRATION_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>
#define SW 8

/* Define a boolean flag. */

float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  pinMode(SW, INPUT);
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();

}

void Emergency() {

      /* Send SMS. */
      if(digitalRead(SW) == 1)
      {
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        //Vibration.start(1000,2000);

        delay(3000);
      }
}

void loop()
{
  Emergency();

  delay(1000);
}

This is how I connect the button. The Grey cable is for Ground, The red is for 5V and the orange is to pin8. Between Red and Grey there is resistor.

I don't have a coding answer for you, but your problem is almost certainly contact bounce. There are de-bounce settings, but these tend to be one-way. A better approach is to detect a press, delay for a short time then confirm the button is still pressed.

@Milliways I am quite new to this field. So can you advice me more how to figure it out. Thanks

There are plenty of references e.g. https://playground.arduino.cc/Learning/SoftwareDebounce

I am trying to puzzle out the wiring of your button. It looks like you have +5V -> Resistor -> GND and then also GPIO  -> GND, and alongside that Nothing -> Button -> GND. Learn how to wire a button!

The problem is because I didn't put the following lines and I changed to use physical push button to 1Sheeld provided button from mobile. The follwing is the working code.
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

/* Define a boolean flag. */
boolean isMessageSent = false;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
  PushButton.setOnButtonStatusChange(&Emergency);
}

void loop()
{

}

void Emergency(byte isButtonPressed) {
 if(isButtonPressed)
      {
        if(!isMessageSent)
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        isMessageSent = true; // This line
      }
      else{
        isMessageSent = false; // This line
      }


text:
Using C - How do I make my button press nearly instant without using interrupts
How can I make the press of a button nearly instant, WITHOUT using interrupts or millis() - and NO preset arduino functions, just C.
There is a delay at the end of my while loop of 500ms - perhaps the solution lies in breaking up the delay (NOTE: I need to keep the delays)

Why do you need to keep the delays? Use a variable and check it against the current time, and using state diagram(s) for the part(s) where you think you need the delay for.

Why don't you want interrupts? Interrupts are expected in almost every serious application on embedded devices!

That is the constraint - make the button press nearly instant without using interrupts or millis(). How do I check the variable against the current time using C and not built in Arduino functions?

you can always replace delay() with millis, that constraint sounds like a uni assignment or you getting stuck in an XY problem

millis() is a built in arduino function that I am unable to use due to the constraint.

Who set the constraint?

delay() is also a built in Arduino function.

due to the constraint .... this smells like school work

@jfpoilpret - actually, interrupts are not all that often directly used to act on user input.  The reason is that user input is often just about the lowest priority input to a system, so you deal with it when you get a chance, after the timing critical tasks.  If interrupts are used, it's to capture and record an event so that it doesn't vanish before it is polled - to take the PC example, to put key events into a buffer - but not to act on them.

For the question at hand with its constraints (whatever their merits or none), what you probably want to do is indeed to divide up the delay, and poll the input in between.  But the question is a bit non-specific for a stack exchange site.  Do give sufficient though to the possibility of contact bounce (if applicable) in your design

You can delay a small period, check button,  delay again.  Loop this until the full delay is achieved

I do this with many things, this is the correct answer.

So then mark it as the correct answer please

Thanks Chad, this is exactly what I did. Thank you for your correct answer.


text:
SOMETHING WRONG IN DHT22 PROGRAM showing error as expected unqualified id before'. ' token
I am using a arduino and dht22 sensor for my project purpose annd gettting error as expecte before unqualified '.' token
MY CODE IS :
#include <DHT.h>

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Wire.h>

#define DHTPIN 8
#define DHTTYPE DHT22

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int ldrpin=A0;
int ldr=0;

DHT dht(DHTPIN, DHTTYPE);

//
//
//
//
//
//
//
//

void setup()
    {

   lcd.begin(16, 2);
   Serial.begin (9600);
   DHT .begin();
     pinMode(ldrpin,INPUT);

}

//
//
//
//
//
//
//

void loop()
    {

  lcd.setCursor(0,0);

 //ldr
  ldr=analogRead(ldrpin);

//LDR DISPLAY
  Serial.println("LIGHT INTENSITY");
  Serial.println(ldr);
  Serial.print(" lx\t");
  delay(2000);

   lcd.clear();
    lcd.setCursor(0, 0);

   lcd.print("LIGHT INTENSITY");
    delay(200);
    lcd.print(ldr);
      delay(2000);

//dht22
delay(2000);

   int chk = DHT.read(DHTPIN);
    float humidity = DHT.humidity;
    float temperature = DHT.temperature;

//dht22 display
1.  Serial.println("Humidity: ");
2.    Serial.print(h);
3.    Serial.print(" %\t");
4.    Serial.println("Temperature: ");
5.    Serial.print(t);
  Serial.println(" *C ");

my error message is
Arduino: 1.6.4 (Windows 8.1), Board: "Arduino Uno"

LCD.ino: In function 'void setup()':
LCD:38: error: expected unqualified-id before '.' token
LCD.ino: In function 'void loop()':
LCD:80: error: expected primary-expression before '.' token
LCD:81: error: expected primary-expression before '.' token
LCD:82: error: expected primary-expression before '.' token
LCD:87: error: expected ';' before 'Serial'
LCD:88: error: expected ';' before 'Serial'
LCD:89: error: expected ';' before 'Serial'
LCD:90: error: expected ';' before 'Serial'
LCD:91: error: expected ';' before 'Serial'
expected unqualified-id before '.' token

This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
some one help me please!!

Don’t shout. No need for an ALLCAPS title


text:
yellow LED not turning off in traffic light simulation
I wanted to make a simulation of a traffic light, and since I don't have any sensors I used a button to change between the different states (red/stop and green/drive). When the states are changing I wanted to have a short yellow blink-
 just like normal traffic lights work. But in the first state(green), yellow doesn't turn off. In the second the same problem occurs, but if I press the button, that I connected to GPIO pin 2, the LED turns off. It makes no sense to me, as the switch sentence turn off the yellow LED before powering the others (in both cases). In addition, I can't wrap my head around the fact that the yellow LED turns off after I press the button once more, as I only have two cases in the switch sentence, but it now seems like there is three.
void loop() {
// Turn the green led on (GPIO PIN 11) if button pressed once. If button is pressed again switch to yellow then to red.

if(switchLedBtn.pressed()) {
colour = colour + 1;
if(colour > 3) {
  colour = 1;
 }
}

switch(colour) {

// Turn off red, turn on yellow in half a second, then power green (green(0), yellow(1) and red(2))
case 1: digitalWrite(ledPins[2], LOW); digitalWrite(ledPins[1], HIGH); delay(500); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[0], HIGH);
        break;

// Turn green off, turn yellow on for a second, then power red
case 2: digitalWrite(ledPins[0], LOW); digitalWrite(ledPins[1], HIGH); delay(1000); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[2], HIGH);
        break;

Please add some line breaks! Cramming multiple statements onto one line makes them very hard to read. And also post your complete code which I suspect is not much longer than what you posted already.

Got it, next time i ask i will include the whole code and try to make it easier to read

Your program runs in a tight loop - an extremely tight one which does all but nothing in any state but 1 or 2.  However what happens in these states is interesting.
Essentially what you have is

Quickly check for input - which won't be detected unless the bottom is being held down at this precise narrow slice of time between long delays
Turn on an LED, apparently from your comment the yellow one
Change the LEDs but recycle so quickly that this fact is generally invisible.

The result of this is that instead of a brief pulse of yellow, you will be seeing near constant yellow, because that is the only part of your loop which takes any time.
Probably what you want to do is to advance the state when you are done with your brief yellow flash.  But it's not possible to say what you should advance the state to, since it's unclear how you want this light to work.  If it is purely timer-based, then you don't need any input at all; while if the button is supposed to do something but a timer should also be used, then you have a more complicated problem.
Essentially, before you can write any code you must write in words or diagrams a comprehensive set of "rules" for what the system is supposed to do.


text:
RX/TX not working as intended
I am currently working on a project with a HC-06 module. I hooked it up accordingly like so:
Arduino -> HC-06
5V -> VCC
GND -> GND
TX -> RX
RX -> TX

and I ran this code:
void setup() {
  Serial.begin(9600);
}

void loop() {
   Serial.print("test");
   Serial.print("\n");

}

Strangely enough that does not work at all. When I am using neither with or without PC as the power source. When I am using SoftwareSerial like this it works like a charm:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(0, 1); // RX, TX

void setup() {
  mySerial.begin(9600);
}

void loop() {

   mySerial.print("test");
   mySerial.print("\n");

}

Can someone please explain why and of course how to fix that?

assuming you have double checked that the wiring (tx/rx) is the same between the two.   Also are you sure your upload completes when you use the hardware serial?  Many times if another device is attached to the hardware serial port, the programing will fail

You are using a Leonardo. Pins 0/1 aren't Serial, they're Serial1.  Serial is the built-in USB connection.
void setup() {
  Serial1.begin(9600);
}

void loop() {
   Serial1.print("test");
   Serial1.print("\n");

}


text:
Arduino MQTT Bluetooth
Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?


text:
Sending over a number from Arduino to Attiny85
I recently started my first arduino project, displaying a number on a 4x 7 segment display. I want to keep this code and use the display in other projects to display 4 digit numbers (creating a library and using segmentdisplay.write(number) maybe?).
Just displaying the number went really well, but I wanted to drive it with less I/O pins. Then I discovered shift registers, which reduced the number of necessary I/O pins to 3. But, the code needs to execute constantly to keep the 4 digits on the display via multiplexing. My solution to this was to run the sketch on attiny85, on which I programmed the code below. The only thing left to do is to change the value of 'getal' to a value that I read or calculate on the arduino. But I have no idea on how to achieve this, can I shift out data from the arduino to attiny85, which then updates 'getal's value? Any help is appreciated!
const int dataPin = 0;
const int latchPin = 1;
const int clockPin = 2;

const int Db = B00001111;
const int D1 = B00000111;
const int D2 = B00001011;
const int D3 = B00001101;
const int D4 = B00001110;
const int num0 = B11111100;
const int num1 = B01100000;
const int num2 = B11011010;
const int num3 = B11110010;
const int num4 = B01100110;
const int num5 = B10110110;
const int num6 = B10111110;
const int num7 = B11100000;
const int num8 = B11111110;
const int num9 = B11110110;

int D_4[4] = {D1, D2, D3, D4};
int D_3[4] = {Db, D2, D3, D4};
int D_2[4] = {Db, Db, D3, D4};
int D_1[4] = {Db, Db, Db, D4};
const int num[10] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

const int tallen[4] = {1000, 100, 10, 1};

int getal = 185;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  int lengte = findn(getal);
  switch (lengte) {
    case 1:
      displaynum(D_1);
      break;
    case 2:
      displaynum(D_2);
      break;
    case 3:
      displaynum(D_3);
      break;
    case 4:
      displaynum(D_4);
      break;
  }
}

int findn(int num) {
  int n = 0;
  while (num) {
    num /= 10;
    n++;
  }
  return n;
}

void displaynum(int *D_x) {
  for (int i = 0; i <= 3; i++) {

    digitalWrite(clockPin, LOW);
    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, LSBFIRST, D_x[i]);
    shiftOut(dataPin, clockPin, LSBFIRST, num[(getal / tallen[i]) % 10]);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
}

If you setup the display to run on a timer-driven interrupt, you can still do many other things and the display will update via the timer(say every 5ms)

I obviously know that buying a screen is cheaper, I just want to learn this.

While the tiny85 does not have a complete hardware I2C, I believe you can do a hardware-"assisted" I2C interface which may be more suitable for transferring a multi-byte value than asynchronous serial.  Beware though that debugging multiprocessor systems can rapidly become complicated; doing background operations on the main ATmega may ultimtely prove simpler.

As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my TinyWire library, that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.
Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the write() function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.

Could also use a chip with better resources, such as Attiny2313. 20 Pins, so a little larger than the '85, but you get a real serial port and SPI port.