body:
I'm trying to send an image from SPIFFS to my external server. When pictures are taken, they are saved into "/pics/" directory within SPIFFS. Ultimately, I'd like to post all the images saved onto "/pics/x.jpg" (x is the a number in increasing order - 7.jpg, 8.jpg, 9.jpg, etc...) to my external server as they come in. Currently, I can access all the images within the internal esp server. Right now, I'm trying to send a single image, "6.jpg" from "/pics/" to my external server. Unfortunately, I'm not seeing anything on the external server side. The http post code occurs in "void setup()".
The complete Arduino code is below:

    // Program header files
    #include <Wire.h>
    #include <WiFi.h>
    #include <WebServer.h>
    #include <ArduCAM.h>
    #include <SPI.h>
    #include "FS.h"
    #include "SPIFFS.h"
    #include "memorysaver.h"

    #define AP_SSID "apssid"
    #define AP_PASSWORD "password"

    #define WIFI_SSID "wifissid"
    #define WIFI_PASSWORD "password"

    #if !(defined (OV2640_MINI_2MP)||defined (OV5640_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_PLUS) \
        || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) \
        ||(defined (ARDUCAM_SHIELD_V2) && (defined (OV2640_CAM) || defined (OV5640_CAM) || defined (OV5642_CAM))))
    #error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
    #endif

    const int ArduCAM_Power = 32; // Controls power for ArduCAM

    const int CS = 5; // GPIO5 as Slave Select for ArduCAM
    int wifiType = 0; // 0: Station    1: AP

    static const size_t bufferSize = 2048;
    static uint8_t buffer[bufferSize] = {0xFF};
    static const int fileSpaceOffset = 700000;

    byte buf[256];
    static int i = 0;
    static int k = 0;
    uint8_t temp = 0, temp_last = 0;
    uint32_t len = 0;
    bool is_header = false;

    const String fName = "/res.txt"; // Whatever last resolution that was submitted, will be stored in the file
                                    // If power goes out, it will use the last setting stored onto that file
    int fileTotalKB = 0;
    int fileUsedKB = 0;
    int fileCount = 0;
    String errMsg = "";
    int imgMode = 1; // 0: stream    1: capture
    int resolution = 3;
    // resolutions:
    // 0 = 160x120
    // 1 = 176x144
    // 2 = 320x240
    // 3 = 352x288
    // 4 = 640x480
    // 5 = 800x600
    // 6 = 1024x768
    // 7 = 1280x1024
    // 8 = 1600x1200

    WiFiClient client;

    WebServer server(80);

    #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
    ArduCAM myCAM(OV2640, CS);
    #endif

    void start_capture()
    {
      myCAM.clear_fifo_flag();
      myCAM.start_capture();
    }

    // Updates properties file with resolution
    void updateDataFile()
    {

      File f = SPIFFS.open(fName, FILE_WRITE);
      if(!f)
      {
        Serial.println("Property file failed to open");
      }
      else
      {
        Serial.println("========= Writing to Property file =========");

        f.println(resolution);
        Serial.println("Data file updated");
        f.close();
      }

    }

    void myCAMsaveToSPIFFS()
    {
      // Reserves space when memory is full
      if((fileTotalKB - fileUsedKB) < fileSpaceOffset)
      {
        String maxStr = "========= Maximum Data Storage Reached =========";
        Serial.println(maxStr);
        errMsg = maxStr;
        return;
      }

      String str;

      // Flush the FIFO
      myCAM.flush_fifo();
      // Clear capture done flag
      myCAM.clear_fifo_flag();
      // Start capture
      myCAM.start_capture();

      Serial.println("Start capture.");
      while(!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
      Serial.println("Capture done!");

      // Increase file count since a capture was done
      fileCount++;

      len = myCAM.read_fifo_length();
      Serial.print("The FIFO length is: ");
      Serial.println(len, DEC);

      if(len >= MAX_FIFO_SIZE) // 8M
      {
        Serial.println("Over size!");
      }
      if(len == 0) // 0 KB
      {
        Serial.println("Size is 0 KB.");
      }

      str = "/pics/" + String(fileCount) + ".jpg";

      File f = SPIFFS.open(str, FILE_WRITE);
      if(!f)
      {
        Serial.println("Property file failed to open");
      }
      else
      {
        Serial.println(str);
      }

      i = 0;
      myCAM.CS_LOW();
      myCAM.set_fifo_burst();
      while (len--)
      {
        temp_last = temp;
        temp =  SPI.transfer(0x00);
        //Read JPEG data from FIFO
        if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
        {
          buf[i++] = temp;  //save the last  0XD9
          //Write the remain bytes in the buffer
          myCAM.CS_HIGH();
          f.write(buf, i);
          //Close the file
          f.close();
          Serial.println("CAM Save done!");
          is_header = false;
          i = 0;
        }
        if (is_header == true)
        {
          //Write image data to buffer if not full
          if (i < 256)
            buf[i++] = temp;
          else
          {
            //Write 256 bytes image data to file
            myCAM.CS_HIGH();
            f.write(buf, 256);
            i = 0;
            buf[i++] = temp;
            myCAM.CS_LOW();
            myCAM.set_fifo_burst();
          }
        }
        else if ((temp == 0xD8) & (temp_last == 0xFF))
        {
          is_header = true;
          buf[i++] = temp_last;
          buf[i++] = temp;
        }
      }

    }

    //////////////////////////////////////////////////////////////////////////////////////////////////
    //    Retrieves a stored jpg file and sends to browser based on url: http://IPaddress/1.jpg     //
    //////////////////////////////////////////////////////////////////////////////////////////////////
    bool loadFromSPIFFS(String path)
    {
      String dataType = "text/plain";
      if(path.endsWith("/"))
      {
        path += "index.htm";
      }

      if(path.endsWith(".src"))
      {
        path = path.substring(0, path.lastIndexOf("."));
      }
      else if(path.endsWith(".jpg"))
      {
        dataType = "image/jpeg";
      }

      File dataFile = SPIFFS.open(path.c_str(), FILE_READ);
      if(server.hasArg("download"))
      {
        dataType = "application/octect-stream";
      }

      if(server.streamFile(dataFile, dataType) != dataFile.size())
      {

      }

      dataFile.close();
      return true;
    }

    /////////////////////////////////////////////////////////////
    //  sets the HTML used for the resoultions drop down       //
    /////////////////////////////////////////////////////////////
    String getDropDown()
    {
      String webString = "";
      webString += "<select name=\"rez\">\n";
      webString += "   <option value\"0\"  ";

      if (resolution == 0)
        webString += " selected=\"seleted\" ";
      webString += ">160x120</option>\n";

      webString += "   <option value=\"1\" ";
      if (resolution == 1)
        webString += " selected=\"seleted\" ";
      webString += ">176x144</option>\n";

      webString += "   <option value=\"2\" ";
      if (resolution == 2)
        webString += " selected=\"seleted\" ";
      webString += ">320x240</option>\n";

      webString += "   <option value=\"3\" ";
      if (resolution == 3)
        webString += " selected=\"seleted\" ";
      webString += ">352x288</option>\n";

      webString += "   <option value=\"4\" ";
      if (resolution == 4)
        webString += " selected=\"seleted\" ";
      webString += ">640x480</option>\n";

      webString += "   <option value=\"5\" ";
      if (resolution == 5)
        webString += " selected=\"seleted\" ";
      webString += ">800x600</option>\n";

      webString += "   <option value=\"6\" ";
      if (resolution == 6)
        webString += " selected=\"seleted\" ";
      webString += ">1024x768</option>\n";

      webString += "   <option value=\"7\" ";
      if (resolution == 7)
        webString += " selected=\"seleted\" ";
      webString += ">1280x1024</option>\n";

      webString += "   <option value=\"8\" ";
      if (resolution == 8)
        webString += " selected=\"seleted\" ";
      webString += ">1600x1200</option>\n";

      webString += "  </select>\n";

      return webString;
    }

    void camCapture(ArduCAM myCAM)
    {
      WiFiClient client = server.client();

      len  = myCAM.read_fifo_length();
      if (len >= MAX_FIFO_SIZE) // 8M
      {
        Serial.println("Over size.");
      }
      if (len == 0 ) // 0KB
      {
        Serial.println("Size is 0.");
      }

      myCAM.CS_LOW();
      myCAM.set_fifo_burst();

      if (!client.connected()) return;

      i = 0;
      while ( len-- )
      {
        temp_last = temp;
        temp =  SPI.transfer(0x00);
        //Read JPEG data from FIFO
        if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
        {
          buffer[i++] = temp;  //save the last  0XD9
          //Write the remain bytes in the buffer
          if (!client.connected()) break;
          client.write(&buffer[0], i);
          is_header = false;
          i = 0;
          myCAM.CS_HIGH();
          break;
        }
        if (is_header == true)
        {
          //Write image data to buffer if not full
          if (i < bufferSize)
          {
          buffer[i++] = temp;
          }
        else
        {
          //Write bufferSize bytes image data to file
          if (!client.connected()) break;
          client.write(&buffer[0], bufferSize);
          i = 0;
          buffer[i++] = temp;
        }
        }
        else if ((temp == 0xD8) & (temp_last == 0xFF))
        {
          is_header = true;
          buffer[i++] = temp_last;
          buffer[i++] = temp;
        }
      }
    }

    void serverCapture()
    {
      delay(1000);
      start_capture();
      Serial.println("CAM Capturing");

      int total_time = 0;

      total_time = millis();
      while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
      total_time = millis() - total_time;
      Serial.print("capture total_time used (in miliseconds):");
      Serial.println(total_time, DEC);

      total_time = 0;

      Serial.println(F("CAM Capture Done."));
      total_time = millis();
      camCapture(myCAM);
      total_time = millis() - total_time;
      Serial.print("send total_time used (in milliseconds): ");
      Serial.println(total_time, DEC);
      Serial.println("CAM send Done!");
    }

    void serverStream()
    {
      WiFiClient client = server.client();

      String response = "HTTP/1.1 200 OK\r\n";
      response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
      server.sendContent(response);

      while (1)
      {
        start_capture();
        while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
        size_t len = myCAM.read_fifo_length();
        if (len >= MAX_FIFO_SIZE) // 8M
        {
          Serial.println(F("Over size."));
          continue;
        }
        if (len == 0 ) // 0 KB
        {
          Serial.println(F("Size is 0."));
          continue;
        }

        myCAM.CS_LOW();
        myCAM.set_fifo_burst();

        if (!client.connected()) break;
        response = "--frame\r\n";
        response += "Content-Type: image/jpeg\r\n\r\n";
        server.sendContent(response);

        while (len--)
        {
          temp_last = temp;
          temp =  SPI.transfer(0x00);

          //Read JPEG data from FIFO
          if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
          {
            buffer[i++] = temp;  //save the last  0XD9
            //Write the remain bytes in the buffer
            myCAM.CS_HIGH();;
            if (!client.connected()) break;
            client.write(&buffer[0], i);
            is_header = false;
            i = 0;
          }
          if (is_header == true)
          {
            //Write image data to buffer if not full
            if (i < bufferSize)
            {
              buffer[i++] = temp;
            }
            else
            {
              //Write bufferSize bytes image data to file
              myCAM.CS_HIGH();
              if (!client.connected()) break;
              client.write(&buffer[0], bufferSize);
              i = 0;
              buffer[i++] = temp;
              myCAM.CS_LOW();
              myCAM.set_fifo_burst();
            }
          }
          else if ((temp == 0xD8) & (temp_last == 0xFF))
          {
            is_header = true;
            buffer[i++] = temp_last;
            buffer[i++] = temp;
          }
        }
        if (!client.connected()) break;
      }
    }

    void handleNotFound()
    {
      String ipAddr = WiFi.localIP().toString();
      if(wifiType == 1)
      {
        ipAddr = WiFi.softAPIP().toString();
      }

      Serial.print("Server URI: ");
      Serial.println(server.uri());

      if(server.uri().indexOf(".jpg") != -1)
      {
        loadFromSPIFFS(server.uri());
        return;
      }

      //// Default HTML
      String message = "\n";
      message += "\n";
      message += "<form action=\"http://" + ipAddr + "/submit\" method=\"POST\">";
      message += "
ESP32 Arducam Mini
\n";
      if (errMsg != "")
      {
        message += "
" + errMsg + "
";
      }

      if (imgMode == 0) // stream mode
      {
        message += "

Video Streaming

 \n";
        message += "

\n";
        imgMode = 1; // set back to capture mode so it doesn't get stuck in streaming mode

      }
      else
      {
        message += "
";
        message += getDropDown();

        message += " <input type=\"radio\" id=\"strm\" name=\"imgMode\" value=\"stream\" ";

        if (imgMode == 0)
        {
          message += " checked ";
        }
        message += "> Stream \n";

        message += " <input type=\"radio\" id=\"capt\" name=\"imgMode\" value=\"capture\"  ";
        if (imgMode == 1)
          message += " checked ";
        message += "> Capture \n";

        message += "  <input type='submit' value='Submit'  >\n";
        message += "    Refresh";
        message += "     Clear Data\n";

        message += "
\n";

        fileTotalKB = (int)SPIFFS.totalBytes();
        fileUsedKB = (int)SPIFFS.usedBytes();

        if (fileCount > 0)
        {
          int percentUsed = ((float)fileUsedKB / (float)(fileTotalKB - fileSpaceOffset)) * 100;
          String colorStr = "green";
          if (percentUsed > 90)
            colorStr = "red";

          message += "
";
          message += "
   space used: " + String(percentUsed) + "%
";
          message += "

\n";

        }

        message += "

";
        int colCnt = 0;
        for (int i = 1; i <= fileCount; i++)
        {
          message += "" + i + ".jpg	\n";

          colCnt++;
          if (colCnt >= 10) //  columns
          {
            message += "

";
            colCnt = 0;
          }
        }
        message += "

\n";

        //useful for debugging max data storage
          /*
            message += "

Total Bytes: 	";
            message += fileTotalKB;
            message += "

Used Bytes: 	";
            message += fileUsedKB;
            message += "

Remaing Bytes: 	";
            message += (fileTotalKB - fileUsedKB);
            message += "

\n";
          */
          /*
            float flashChipSize = (float)ESP.getFlashChipSize() / 1024.0 / 1024.0;
            message += "
chipSize: ";
            message += flashChipSize;
          */

          message += "

\n";

      }

      message += "</form> \n";
      message += "\n";

      server.send(200, "text/html", message);
    }

    void setCamResolution(int reso)
    {
      switch (reso)
      {
        case 0:
          myCAM.OV2640_set_JPEG_size(OV2640_160x120);
          resolution = 0;
          break;

        case 1:
          myCAM.OV2640_set_JPEG_size(OV2640_176x144);
          resolution = 1;
          break;

        case 2:
          myCAM.OV2640_set_JPEG_size(OV2640_320x240);
          resolution = 2;
          break;

        case 3:
          myCAM.OV2640_set_JPEG_size(OV2640_352x288);
          resolution = 3;
          break;

        case 4:
          myCAM.OV2640_set_JPEG_size(OV2640_640x480);
          resolution = 4;
          break;

        case 5:
          myCAM.OV2640_set_JPEG_size(OV2640_800x600);
          resolution = 5;
          break;

        case 6:
          myCAM.OV2640_set_JPEG_size(OV2640_1024x768);
          resolution = 6;
          break;

        case 7:
          myCAM.OV2640_set_JPEG_size(OV2640_1280x1024);
          resolution = 7;
          break;

        case 8:
          myCAM.OV2640_set_JPEG_size(OV2640_1600x1200);
          resolution = 8;
          break;

      }
    }

    void clearData()
    {
      errMsg = "======  Data Storage Cleared =========";
      File dir = SPIFFS.open("/pics");
      while (dir.openNextFile())
      {
        SPIFFS.remove(dir.name());
      }

      fileCount = 0;
      fileTotalKB = 0;
      fileUsedKB = 0;

      handleNotFound();
    }

    void handleSubmit()
    {
      errMsg = "";
      Serial.println( "--- Form Submited ---");
      Serial.println( "Server args " + server.args());

      if (server.args() > 0 )
      {
        for ( uint8_t i = 0; i < server.args(); i++ )
        {

          // can be useful to determine the values from a form post.
          Serial.println( "Server arg " + server.arg(i));
          Serial.println( "Server argName " + server.argName(i) );
          if (server.argName(i) == "imgMode")
          {
            Serial.println(" Image Mode: " + server.arg(i));

            if (server.arg(i) == "stream")
            {
              imgMode = 0;
            }
            else
            {
              imgMode = 1; // capture mode
            }
          }

          if (server.argName(i) == "rez")
          {

            if (server.arg(i).toInt() != resolution)
            {

              setCamResolution(server.arg(i).toInt());

              updateDataFile();

              //// IMPORTANT: removing or reducing the delay can result in dark images
              delay(1500); // add a delay to allow the white balance to adjust to new resolution
            }
          }
        }
      }

      if (imgMode == 1) // capture
      {
        myCAMsaveToSPIFFS();
      }

      handleNotFound();

    }

    void setup()
    {
      SPIFFS.begin();
      delay(10);

      Wire.begin();
      Serial.begin(115200);
      SPI.begin();
      SPI.setFrequency(4000000); //4MHz
      pinMode(CS, OUTPUT);

      pinMode(ArduCAM_Power, OUTPUT);
      digitalWrite(ArduCAM_Power, HIGH);

      Serial.println();

      // Check for properties file
      File f = SPIFFS.open(fName, FILE_READ);

      if(!f)
      {
        // No file exists. Format and create properties file.
        Serial.println("Please wait for SPIFFS to be formatted.");

        SPIFFS.format();
        Serial.println("SPIFFS Formatted!");

        f = SPIFFS.open(fName, FILE_WRITE);
        if(!f)
        {
          Serial.println("Properties file failed to open.");
        }
        else
        {
          Serial.println("========= Writing to Property file =========");

          f.println(resolution);
          f.close();
        }
      }
      else
      {
        Serial.println("Properties file exists! Reading...");

        while(f.available())
        {
          String str = f.readStringUntil('\n');

          Serial.println(str);

          resolution = str.toInt();
        }

        f.close();
      }

      uint8_t vid, pid;
      uint8_t temp;

      while(1)
      {
        //Check if the ArduCAM SPI bus is OK
        myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
        temp = myCAM.read_reg(ARDUCHIP_TEST1);
        if (temp != 0x55) {
          Serial.println(F("SPI interface Error!"));
          delay(2);
          continue;
        }
        else
          break;
      }

      #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
      //Check if the camera module type is OV2640
      myCAM.wrSensorReg8_8(0xff, 0x01);
      myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
      myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
      if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
        Serial.println(F("Can't find OV2640 module!"));
      else
        Serial.println(F("OV2640 detected."));
      #endif

      //Change to JPEG capture mode and initialize the OV2640 module
      myCAM.set_format(JPEG);
      myCAM.InitCAM();

      setCamResolution(resolution);
      myCAM.clear_fifo_flag();

      if (wifiType == 0)
      {
        if(!strcmp(WIFI_SSID,"SSID"))
        {
          Serial.println(F("Please set your SSID"));
          while(1);
        }
        if(!strcmp(WIFI_PASSWORD,"PASSWORD"))
        {
          Serial.println(F("Please set your PASSWORD"));
          while(1);
        }
        // Connect to WiFi network
        Serial.println();
        Serial.println();
        Serial.print(F("Connecting to "));
        Serial.println(WIFI_SSID);

        WiFi.mode(WIFI_STA);

        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

        while (WiFi.status() != WL_CONNECTED)
        {
          delay(500);
          Serial.print(F("."));
        }

        Serial.println(F("WiFi connected"));
        Serial.println("");
        Serial.println(WiFi.localIP());
      }
      else if (wifiType == 1)
      {
        Serial.println();
        Serial.println();
        Serial.print(F("Shared AP: "));
        Serial.println(AP_SSID);
        Serial.print(F("The password is: "));
        Serial.println(AP_PASSWORD);

        WiFi.mode(WIFI_AP);

        WiFi.softAP(AP_SSID, AP_PASSWORD);

        Serial.println();
        Serial.print("AP IP Address is: ");
        Serial.println(WiFi.softAPIP());
      }

      File normPicture = SPIFFS.open("/pics/6.jpg", FILE_READ);
      uint32_t jpgLen = normPicture.size();

      Serial.print("Sending image of ");
      Serial.print(jpgLen, DEC);
      Serial.println("bytes");

      // Prepare request
      String start_request = "";
      String end_request = "";
      start_request = start_request + "\n" + "--AaB03x" + "\n" + "Content-Type: image/jpeg" + "\n" + "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"6.jpg\"\n" + "Content-Transfer-Encoding: binary\n\n";
      end_request = end_request + "\n--AaB03x--\n";
      uint32_t extra_length;
      extra_length = start_request.length() + normPicture.size() + end_request.length();
      //Serial.println("Extra length:");
      //Serial.println(extra_length);
      long leng = jpgLen + extra_length;

      // Connect to server
      Serial.println("Starting connection to external server!");
      if (client.connect("172.xx.xx.x", 80))
      {
        Serial.println("Connected");
        client.print("POST /www/upload.php HTTP/1.1");
        client.println("Host: 172.xx.xx.x" );
        client.println("Content-Type: multipart/form-data; boundary=AaB03x");
        client.print("Content-Length: ");
        client.println(extra_length);
        client.println();
        client.print(start_request);
        Serial.println("Connected1");

        while(normPicture.available())
        {
          client.write(normPicture.read());
        }

        Serial.println("END REQUEST");
        client.println(end_request);

      }
      else
      {
        Serial.println("Connection failed!");
      }

      // Setup handlers for internal server
      server.on("/capture", HTTP_GET, serverCapture);
      server.on("/stream", HTTP_GET, serverStream);
      server.on("/submit", handleSubmit);
      server.on("/clear", clearData);
      server.onNotFound(handleNotFound);
      server.begin();
      Serial.println("Internal Server started");

      File dir = SPIFFS.open("/pics");
      while(dir.openNextFile())
      {
        fileCount++;
      }

      fileTotalKB = (int)SPIFFS.totalBytes();
      fileUsedKB = (int)SPIFFS.usedBytes();

    }

    void loop()
    {
      server.handleClient();

      //delay(15000);
    }

My php code (upload.php) is below:

    <?php
    if (!empty($_FILES) && isset($_FILES['fileToUpload'])) {
        switch ($_FILES['fileToUpload']["error"]) {
            case UPLOAD_ERR_OK:
                $target = "upload/";
                $target = $target . basename($_FILES['fileToUpload']['name']);

                if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)) {
                    $status = "The file " . basename($_FILES['fileToUpload']['name']) . " has been uploaded";
                    $imageFileType = pathinfo($target, PATHINFO_EXTENSION);
                    $check = getimagesize($target);
                    if ($check !== false) {
                        echo "File is an image - " . $check["mime"] . ".
";
                        $uploadOk = 1;
                    } else {
                        echo "File is not an image.
";
                        $uploadOk = 0;
                    }

                } else {
                    $status = "Sorry, there was a problem uploading your file.";
                }
                break;

        }

        echo "Status: {$status}
\n";

    }
    ?>

I don't believe that I need any html code, since the php file receives the image and sends it to the "uploads/" folder in "www/uploads/" from my external server. My upload.php file is located in "www/".

UPDATE1: I believe my error is either the client headers, or when writing the image to send to the external server. I get an error 400 226 on the external server when trying to send the image. The 400 for a bad client request, and I believe the 226 is the amount of bytes sent/received.

Thanks!

title: Arduino HTTP post image to external server

Answers: 0


body:
I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of **simulated byte**, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).

So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.

My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.

I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) *seemed* to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)

Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?

The breadboard looks like this:

[![BreadBoard Image][1]][1]

  [1]: https://i.stack.imgur.com/k0Gwe.png

title: LED on same Pin as Toggle Switch, not illuminating

Answers: 2

body:
LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.

You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.

So:

    Vout = (Vin - Vled) * (R2 / (R1 + R2))

         = (5 - 2) * (1000 / (200 + 1000))

         = 3 * (1000 / 1200)

         = 3 * 0.833

         = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.

You're between those two voltages - in the "dead zone".

The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.

body:
This is your circuit that does not work:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/k6vcW.png)

<!-- End schematic -->

There are many ways to use a single pin. Some circuits are with a diode and some circuits need to turn off the led to read the switch. The most simple solution might be this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/QrCme.png)

<!-- End schematic -->

When the switch is not closed, the LED is a weak pullup (perhaps too weak). By using INPUT_PULLUP for D7, the pullup is stronger and D7 can read the switch.
As an extra it is possible to turn the LED on when the switch is open. But you have to be sure to switch between OUTPUT + LOW and INPUT_PULLUP in the code or else there is a shortcut.


body: How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

title: How to start serial monitor on Windows startup

Answers: 1

body:
You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.

Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.

For Windows 10 you can make a program run at startup by following [these](https://social.technet.microsoft.com/Forums/en-US/f0005629-0377-4e4b-82cc-26aff7b95884/how-do-you-add-new-startup-programs-in-wndows-10?forum=WinPreview2014General) instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.


body:
I am trying to create smart clock with alarm using an Arduino Uno.

My problem is when I set the alarm, I can't set the alarm again. Every time I must power off my Arduino and then power on in order to set the alarm again.

I am using:
Arduino Uno
LCD 16*2
buttons
buzzer and LED
RTC

My code works like this:
At the beginning it will let you to set date and time by buttons and you can set alarm too.
When it reaches the alarm time, it turns on the melody of buzzer and LEDs turn on.

but

I want to turn off the alarm so I can set another alarm.

This is my code:

<!-- language-all: lang-C++ -->

    #include "RTClib.h"
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int alarmState = 0;
    int alarmSnooze = 0;
    int btnSet = 0;
    int btnSel = 0;
    int alarmValue = 0;
    int alarmCounter = 0;
    boolean turnOffAlarm = false;
    boolean settingAlarm = false;
    int counter = 0;
    boolean initialCount = true;
    boolean alarmSet = false;
    int timeArray[6]; // 0=Hour, 1=Minutes, 2=day, 3=Day of Week, 4=Month, 5=Year;
    int timeCounter = 0;
    int alarmArray[2];
    char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    RTC_DS1307 rtc;    // Create a RealTimeClock object
    DateTime now; // Read data from the RTC Chip

    //////////////////////////
     ///difine button////
    int  b6=6;
    int b7=7;
    int b8=8;
    int b9=9;
    ////////////////////

    ///melody///
    #include "pitches.h"

    const int piezoPin = 13; //piezo
    const int rPin = A0;  //red LED
    const int gPin = A1;  //green LED
    const int bPin = A2;  //blue LED
    const int pPin = 6;  //pushbutton

    int ledState = 0;
    int ledOn = false;

    // notes
    int melody[] = {
      NOTE_F5,NOTE_D5,NOTE_AS4,NOTE_D5,NOTE_F5,NOTE_AS5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
      NOTE_F5,NOTE_F5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_AS5,NOTE_F5,NOTE_D5,NOTE_AS4,
      NOTE_D6,NOTE_D6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_F6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_DS6,
      0,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
      NOTE_F5,NOTE_AS5,NOTE_AS5,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_G5,NOTE_G5,NOTE_C6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_AS5,NOTE_A5,
      NOTE_F5,NOTE_F5,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_C6,NOTE_AS5
    };

    // durations: 2 = half note, and 8/3,4,6,8,12. It appears that 8/2.9 is more accurate than 8/3.
    float noteDurations[] = {
      6,12,4,4,4,2,6,12,4,4,4,2,
      8,8,8/2.9,8,4,2,8,8,4,4,4,4,4,
      6,12,4,4,4,2,8,8,4,4,4,2,
      8,8,8/2.9,8,4,2,8,8,4,4,4,2,
      4,4,4,8,8,4,4,4,4,8,8,8,8,4,4,
      8,8,8/2.9,8,8,8,2,8,8,4,4,4,2
    };

    // calculates the number of elements in the melody array.
    int musicLength=sizeof(melody)/sizeof('NOTE_F5');

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

    void setup()
    {

      pinMode(pPin, INPUT);
      pinMode(rPin, OUTPUT);
      pinMode(gPin, OUTPUT);
      pinMode(bPin, OUTPUT);

      Serial.begin(9600);
      lcd.begin(16, 2);
      pinMode(10, OUTPUT);
      rtc.begin(); // Start the RTC library code
      rtc.adjust(DateTime(0, 0, 0, 0, 0, 0));
    }
    void loop()

    { alarmState = digitalRead(b9);
      alarmSnooze = digitalRead(b6);
      btnSet = digitalRead(b7);
      btnSel = digitalRead(b8);

      if (timeCounter == 0)
      {
        if(initialCount == true){
          counter=0;
          initialCount = false;
        }
        setHour();
      }
      else if (timeCounter == 1)
      {
        if(initialCount == true){
          counter=0;
          initialCount =false;
        }
        setMinute();
      }
      else if (timeCounter == 2)
      {
        if(initialCount == true){
          counter= 1;
          initialCount=false;
        }
        setDay();
      }
      else if (timeCounter == 3)
      {
        if(initialCount == true){
          counter = 0;
          initialCount =false;
        }
        setDOW();
      }
      else if (timeCounter == 4)
      {
        if(initialCount==true){
          counter=0;
          initialCount=false;
        }
        setMonth();
      }
      else if (timeCounter == 5)
      {
        if(initialCount==true){
          counter=0;
          initialCount=false;
        }
        setYear();
      }
      else if (timeCounter == 6)
      {
        rtc.adjust(DateTime(2000+timeArray[5], timeArray[4], timeArray[2], timeArray[0], timeArray[1], 0));
        timeCounter++;
        delay(200);
      }
      else if (timeCounter > 6){
        if(alarmState == LOW&&settingAlarm==false){
          now = rtc.now();
          digitalClockDisplay();
        }
        else if(alarmState == HIGH||settingAlarm==true)
        {
          settingAlarm = true;
          if(alarmValue==0){
            if(initialCount==true)
            {
              lcd.clear();
              alarmCounter=0;
              initialCount=false;
            }
            setAlarmHour();
          }
          else if(alarmValue==1){
            if(initialCount==true)
            {
              alarmCounter=0;
              initialCount=false;
            }
            setAlarmMinute();
          }
          else if(alarmValue>1){
            alarmSet = true;
            settingAlarm = false;
          }
        }
        if(alarmArray[0]==now.hour()&&alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==LOW){
           for (int thisNote = 0; thisNote < musicLength; thisNote++) {
          // blink the three LEDs in sequence
          if (thisNote%3==0){
            digitalWrite(rPin, HIGH);
            digitalWrite(gPin, LOW);
            digitalWrite(bPin, LOW);
          }
          else if (thisNote%3==1){
            digitalWrite(rPin, LOW);
            digitalWrite(gPin, HIGH);
            digitalWrite(bPin, LOW);
          }
          else if (thisNote%3==2){
            digitalWrite(rPin, LOW);
            digitalWrite(gPin, LOW);
            digitalWrite(bPin, HIGH);
          }

          // calculate the note duration. change tempo by changing 2000 to other values
          int noteDuration = 2000/noteDurations[thisNote];
          tone(piezoPin, melody[thisNote],noteDuration);

          // to distinguish the notes, set a minimum time between them.
          // the note's duration + 30% seems to work well
          float pauseBetweenNotes = noteDuration * 1.30;

          //split the delay into two parts and check to see
          //whether the pushbutton is pressed to turn off
          //the sound and light
          delay(pauseBetweenNotes/2);
          if(digitalRead(pPin)==HIGH) {
            break;
          }
          delay(pauseBetweenNotes/2);
          if(digitalRead(pPin)==HIGH) {
            break;
          }

        }
          digitalWrite(13, HIGH);

        }

        else if(alarmArray[0]==now.hour() && alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==HIGH){
          noTone(13);
          digitalWrite(13, LOW);
          digitalWrite(rPin, LOW);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, LOW);
          turnOffAlarm = true;
        }
      }
    }

    void nextValue(){
      btnSel=LOW;
      // Update array value with counter
      timeArray[timeCounter] = counter;
      counter=0;
      initialCount = true;
      timeCounter++;
      delay(200);
      lcd.clear();
    }
    void nextAlarmValue(){
      btnSel=LOW;
      // Update array value with counter
      alarmArray[alarmValue] = alarmCounter;
      alarmCounter=0;
      initialCount = true;
      alarmValue++;
      delay(200);
      lcd.clear();
    }

    void setAlarmHour(){
       if(alarmCounter==24){
        alarmCounter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set alarm hour");
      lcd.setCursor(7,1);
      lcd.print(alarmCounter);
      if (btnSet==HIGH)
      {
        alarmCounter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextAlarmValue();
     }
    }

    void setAlarmMinute(){
      if(alarmCounter==59){
      alarmCounter=0;
      lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set alarm minute");
      lcd.setCursor(7,1);
      lcd.print(alarmCounter);
      if (btnSet==HIGH)
      {
        alarmCounter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextAlarmValue();
     }
    }

    void setDOW(){
      if(counter==7){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set day of week");
      lcd.setCursor(7,1);
      lcd.print(days[counter]);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }
    void setHour()
    {
      if(counter==24){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set hour");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set minutes
    void setMinute()
    {
      if(counter==60){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set minute");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set date
    void setDay()
    {
      if(counter==32){
        counter=1;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set day");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set month
    void setMonth()
    {
      if(counter==12){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set month");
      lcd.setCursor(7,1);
      lcd.print(months[counter]);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set year
    void setYear()
    {
      lcd.setCursor(0,0);
      lcd.print("Set year");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    void digitalClockDisplay(){
      // digital clock display of the time
      long hours;
      String amOrPm = "";
      if(now.hour() > 12){
        hours = now.hour() - 12;
        amOrPm = "PM";
      }
      else if(now.hour()==0){
        hours=12;
        amOrPm = "AM";
      }
      else{
        hours = now.hour();
        amOrPm = "AM";
      }
      lcd.setCursor(0,0);
      lcd.print(days[timeArray[3]]);
      lcd.print(" ");
      lcd.print(months[timeArray[4]]);
      lcd.print(" ");
      lcd.print(now.day());
      lcd.print(" ");
      lcd.print(now.year());
      lcd.setCursor(0,1);
      lcd.print(hours);
      printDigits(now.minute());
      printDigits(now.second());
      lcd.print(" ");
      lcd.print(amOrPm);
    }

    void printDigits(int digits){
      // utility function for digital clock display: prints preceding colon and leading 0
      lcd.print(":");
      if(digits < 10)
        lcd.print('0');
      lcd.print(digits);
    }

title: arduino LCD help

Answers: 2

body: It looks like you haven't reset your state variable *turnOffAlarm* after you turn off the alarm.

body:
Since the question is tagged [code-review]

1.
        char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

 This should be a `const` array of `const char *`, not of `char *`.

        const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

 Same goes for `months`.

3.
        int  b6=6;
        ...
        const int piezoPin = 13;
        ...

 Why some of your pins are `const` and others are not? I don't see any attempts or reasons to change the value of `b6` in the code. Why is it not `const`?

4.

        int melody[] = { ... };
        float noteDurations[] = { ... };

   Both are supposed to be be `const`, apparently.

5.
        // calculates the number of elements in the melody array.
        int musicLength=sizeof(melody)/sizeof('NOTE_F5');

 Really? What is `'NOTE_F5'`? What did your compiler tell you about it? Did you just ignore the compiler's message?

 Should be

        const int musicLength = sizeof melody / sizeof *melody;

 I'd prefer `unsigned` or `size_t`, but let's not open this can of worms.

6. In a single-file sketch all global variables (i.e. the ones that really need to be global) should be declared either `const` or `static` (or placed in an anonymous namespace). Declaring a global variable that is not `const` or `static` requires a good reason for doing so.


body:
If I'm programming a pin change interrupt I can call attachInterrupt at various points in my code and change what function is called when the interrupt occurs.

The overflow and compareA/B interrupt calls are defined by the ISR macro which is evaluated at compile time, which therefore can't be changed at run time. One solution would be to make that function consist of a single line, which invokes a function pointer. If I'm reading the code correctly, this is how attachInterrupt is implemented. Short of mucking with the interrupt vector table (which seems like a bad idea, or at least very hard to debug if you screw it up), is there another way to redefine the overflow or compare interrupt functions?

title: How do I redefine the overlfow of compare interrupts in Arduino programming?

Answers: 1

body:
What about using a `switch` statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?

    uint8_t status = 0;

    void myInterruptFn() {
      switch(status) {
        case 0:
          // do something
          status = 1;
          break;
        case 1:
           // do something else
           status = 0;
           break;
       }
    }


body:
I am using an ESP8266 [board][1] and I had it plugged in to my computer via usb. I reached accross the board to press the reset button, and it felt like my finger got stung. The best I can figure, I touched the VIN and Gnd pins with my finger, and, I didn't think this at first, the reset pin. Whenever I try to open a serial port all that shows, and at a different baud rate then I specified, is this error message

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

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

Everything I find online says that this means that the reset pin is causing problems. Although this is the first time a 7 showed up, it used to be a 6. Also, the computer doesn't seem to have a problem uploading the sketches, but they don't seem to run.

I have tried re-flashing the firmware, but just now when I was typing this out, I thought to upload Blink, just to say I could, and it worked, but it isn't sending anything to the computer of serial, at all. I own two of these boards, but the problem happened across both making me think that something happened to my computer.

Any help is appreciated.

Edit: I am running Win 10, using Vscode to upload sketches, and arudino IDE v1.8.7 to monitor serial. I have many Serial.print() lines, and Serial.begin(115200)

  [1]: http://chrome-extension://klbibkeccnjlkjkiokjodocebajanakg/suspended.html#ttl=Amazon.com: HiLetgo 2pcs ESP8266 NodeMCU LUA CP2102 ESP-12E Internet WiFi Development Board Open Source Serial Wireless Module Works Great with Arduino IDE/Micropython (Pack of 2PCS): Gateway&pos=0&uri=https://www.amazon.com/HiLetgo-Internet-Development-Wireless-Micropython/dp/B010N1SPRK/ref=sr_1_1_sspa?keywords=esp8266&qid=1554693478&s=gateway&sr=8-1-spons&psc=1

title: ESP 8266 serial error

Answers: 0


body:
I am working on RFID. I am sending data through serial monitor and the Serial.available is not identifying the data after the first time, its working perfectly fine only once after reopening the comport.

I have tried all the possible changes I could do in the code. I want that when I run this code, then after entering the data in serial monitor it should show "Scan the mifare card" and after scanning the card it should perform read or write action.

    #include <SPI.h>//include the SPI bus library
    #include <MFRC522.h>//include the RFID reader library

    #define SS_PIN 10  //slave select pin
    #define RST_PIN 9 //reset pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
    MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will hold the card information

    void setup()
     {
            Serial.begin(9600);        // Initialize serial communications with the PC
            SPI.begin();               // Init SPI bus
            mfrc522.PCD_Init();
            //while (! Serial); // Wait untilSerial is ready - Leonardo
            //Serial.println("Enter data");
     }

    String incomingStr;
    byte blockcontent[16];
    int count=0;
    String arr2[6];
    int arr3[6];
    int u2=0;
    String arr[16];
    int arr1[16];
    int u=0;
    int y;
    char action;
    //int newc=0;

    void loop()
    {
     // Serial.println("bahar");
      if (Serial.available())
        {
          doReceive();
          int newc=0;
          while(newc==0)
           {
             if ( ! mfrc522.PICC_IsNewCardPresent())
                {
                   if(count==0)
                       {
                           Serial.println("Scan your mifare card %");
                           count++;
                       }
                }
            else
                {
                   newc=1;
                }
           }

         if ( ! mfrc522.PICC_ReadCardSerial())
           {
             return;
           }
         if(action=='%')
           {
             doWrite();
           }
         else if(action=='$')
           {
             doRead();
           }
         else if(action=='^')
           {
             for (byte i = 0; i < mfrc522.uid.size; ++i)
               { // read id (in parts)
                  Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
                  Serial.print(mfrc522.uid.uidByte[i], HEX);
               }
             Serial.print("*");
           }
      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
      Serial.flush();
       }
    }

    void doReceive()
    {
       incomingStr = Serial.readString();
       int sto=incomingStr.indexOf(')');
       action=incomingStr.charAt(sto+1);
       y=sto+2;
       for(int j=0;j<sto;j++)
        {
          if(incomingStr.charAt(j)!= ' ')
           {
             //Serial.print(incomingStr.charAt(j));
             //arr[u]=arr[u].concat(incomingStr.charAt(j));
             arr2[u2]+=incomingStr.charAt(j);
           }
         else
           {
             //Serial.println(arr[u]);
             u2++;
           }
        }
      for(u2=0;u2<6;u2++)
        {
          arr3[u2]=arr2[u2].toInt();
          key.keyByte[u2]=arr3[u2];
          //Serial.println(key.keyByte[u2]);
        }
     }
    void doWrite()
    {
      int block=1;
      for(int i=0;i<incomingStr.length();i=i+16)
      {
        if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
          {
            block=block+1;
          }
        for(int u=0;u<16;u++)
          {
            blockcontent[u]=0;
            //Serial.println(arr1[u]);
          }
        String s1=incomingStr.substring(y+i,y+16+i);
        s1.getBytes((char *) blockcontent, 30);
        writeBlock(block, blockcontent);
        block=block+1;
      }
      Serial.println("Data written successfully*");
    }
    void doRead()
    {
      int block=1;
      for(int i=0;i<4;i++)
        {
          if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
            {
              block=block+1;
            }
          byte readbackblock[18];
          readBlock(block, readbackblock);//read the block back
          //Serial.print("Block contains: ");
          for (int j=0 ; j<16 ; j++)//print the block contents
            {
               Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
            }

         //Serial.println();
         block=block+1;
        }
      Serial.println("*");
     }

title: Serial.available is working only for the first time

Answers: 2

body:
First of all try to add these debugging prints here to see if this while loop is becoming infinite:

      while(newc==0)
       {
         if ( ! mfrc522.PICC_IsNewCardPresent())
            {
               if(count==0)
                   {
                       Serial.println("Scan your mifare card %");
                       count++;
                       **Serial.println("test0")*
                   }

            }
        else
            {
               newc=1;
               **Serial.println ("newc=1")**
            }
       }

body:
`arr2` have size `6`. Have you made sure that here

    ...
    for(int j=0;j<sto;j++)
    {
      if(incomingStr.charAt(j)!= ' ')
       {
         arr2[u2]+=incomingStr.charAt(j);
       }
     else
       {
         u2++;
       }
    }
    ...

you are not writing beyond the bounds of that array?

Moreover, you never explicitly set the initial value of `u2` before starting this cycle - whatever was left in global variable `u2` from the previous uses will serve as the staring value for this cycle.

Judging by cursory examination of the rest of your code, only the very first call to `doReceive` will begin this cycle with `u2 == 0`. After that every time you call `doReceive`, you will start this cycle with `u2 == 6`, definitely overflowing the array and destroying the content of adjacent memory locations. The behavior is undefined.

I guess it is a "global variables strike again" kind of situation. Why on Earth is `u2` made a global variable???

It is quite possible that you can "fix" your code by simply adding `u2 = 0;` before the above cycle. But even after that the code will remain in a rather precarious state.


body:
The code is for a DC motor position control PID system. I need the angle I need to move to "setpoint" and change it throughout the process. Though it is only changing once and then nothing happens if I insert a new value unless I upload the code again. I need help in finding the problem, thank you.

Code:

```c
double count = 0; //set the counts of the encoder
double angle = 0;//set the angles
boolean A,B;
byte state, statep;

double pwm = 9;// this is the PWM pin for the motor for how much we move it to correct for its error
const int dir1 = 6;//these pins are to control the direction of the motor (clockwise/counter-clockwise)
const int dir2 = 7;

double    setpoint = 0;
double Kp = 0.2;// you can set these constants however you like depending on trial & error
double Ki = 0.25;
double Kd = 1;

float last_error = 0;
float error = 0;
float changeError = 0;
float totalError = 0;
float pidTerm = 0;
float pidTerm_scaled = 0;// if the total gain we get is not in the PWM range we scale it down so that it's not bigger than |255|
String readString;

void setup() {
   Serial.begin(9600);
  pinMode(2, INPUT);//encoder pins
  pinMode(3, INPUT);
  attachInterrupt(0,Achange,CHANGE);//interrupt pins for encoder
  attachInterrupt(1,Bchange,CHANGE);

  pinMode(pwm, OUTPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);

}

void loop(){

   if (Serial.available()) { //Check if the serial data is available.
    delay(3);                  // a small delay
    char c = Serial.read();  // storing input data
    readString += c;         // accumulate each of the characters in readString
  }

  if (readString.length() >0) { //Verify that the variable contains information

   Serial.println(readString.toInt());  //printing the input data in integer form
    setpoint = readString.toInt();   // here input data is store in integer form

  }
   PIDcalculation();// find PID value

  Serial.print("         ");
Serial.print(setpoint);
Serial.print("         ");

  if (angle > setpoint+0.5) {
    digitalWrite(dir1, LOW);// Forward motion
    digitalWrite(dir2, HIGH);
  }
else if  (angle < (setpoint-0.5)) {
    digitalWrite(dir1, HIGH);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  else{
      digitalWrite(dir1, LOW);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  analogWrite(pwm, pidTerm_scaled);

  Serial.println("WHEEL ANGLE:");
  Serial.print(angle);  // here input data is store in integer form;
  delay(100);

}

void PIDcalculation(){

  angle = (0.9 * count);//count to angle conversion
  error = setpoint - angle;

  changeError = error - last_error; // derivative term
  totalError += error; //accumalate errors to find integral term
  pidTerm = (Kp * error) + (Ki * totalError) + (Kd * changeError);//total gain
  pidTerm = constrain(pidTerm, -155, 155);//constraining to appropriate value
  pidTerm_scaled = abs(pidTerm);//make sure it's a positive value

  last_error = error;
}

void Achange() //these functions are for finding the encoder counts
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}

void Bchange()
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}
```

title: Input value constantly

Answers: 0


body:
I'm using RTC DS1307 and OLED on an Arduino MEGA together.

When I try to use a rtc code like
`rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));`
or `DateTime now = rtc.now();` the OLED display starts not showing what i wish in "void loop".

The summary of the code is below:

<!-- language: lang-c -->

    #include "Arduino.h"
    #include "U8g2lib.h"
    #include "U8x8lib.h"
    #include "RTClib.h"
    #include "Wire.h"
    #include "SPI.h"
    U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);   // Adafruit Feather M0 Basic Proto + FeatherWing OLED
    RTC_DS1307 rtc;
    void setup() {

      Serial1.begin(57600);
     if (! rtc.isrunning()) {
        Serial1.println("RTC is NOT running!");
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
         }
         if (! rtc.begin()) {
        Serial1.println("Couldn't find RTC");
        while (1);
      }
      Serial1.end();

      Serial2.begin(9600);
      while (!Serial2) {
        ; // wait for Serial2 port to connect. Needed for native USB port only
      }
      u8g2.begin();

      u8g2.clearBuffer();
      u8g2.setFont(u8g2_font_6x13_te);
      u8g2.drawStr(30, 25, "WELCOME!");
      u8g2.sendBuffer();
      delay(2000);
      Serial2.setTimeout(1100);
    }

    void loop() {
     u8g2.clearBuffer();
      u8g2.setFont(u8g2_font_6x13_te);
      u8g2.drawUTF8(0,12,"EepromA");
      u8g2.setCursor(55,12);
      //u8g2.print(EepromA);
      u8g2.setCursor(100,12);
      u8g2.print("EepromA");
      u8g2.drawUTF8(0,22,"EepromB");
      u8g2.setCursor(55,22);
     // u8g2.print(EepromB);
      u8g2.setCursor(100,22);
      u8g2.print("EepromB");
      u8g2.drawUTF8(0,32,"EepromC");
      u8g2.setCursor(55,32);
    //  u8g2.print(EepromC);
      u8g2.setCursor(100,32);
      u8g2.print("EepromC");
      u8g2.sendBuffer();
          delay(50);

    }

It seems like it is about i2c of Arduino Mega but how to solve the problem?
Note: After a search on the website I found some similar problems, I have removed R2 and R3 pull-up resistors on RTC module, this did not solve it.

title: Using RTC DS1307 and OLED on Arduino MEGA

Answers: 0


body:
I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.

After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.

 **Receiver**

    #include <SoftwareSerial.h>

    SoftwareSerial softwareSerial(9, 10);
    String str;

    void setup()
    {

   Serial.begin(9600);
   softwareSerial.begin(9600);

    }

    void loop()
    {

   while (softwareSerial.available() > 0) {

  char inChar = softwareSerial.read();

  if (inChar == '$') {

   str.trim();
   Serial.println("received command" + str);
   memset(&str, 0, sizeof(str));
   Serial.flush();
   softwareSerial.flush();
  }
  else {
   str = str + inChar;
  }

  }

    }

**Sender**

    #include <SoftwareSerial.h>

    SoftwareSerial swSer1(22, 23, false, 256);
    String str;

    void setup() {

   Serial.begin(9600);
   swSer1.begin(9600);

    }

    void loop() {

      String sendCmd = "MSG1$";
      Serial.println("Sending ");
      Serial.println(sendCmd );
      char copy[50];
      sendCmd.toCharArray(copy, 50);
      swSer1.write(sendCmd);
      delay(1000);

    }

Here my question is where i am going wrong in this project. Please guide me.

**Note :** DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.

title: Arduino Uno & ESP32 communication using RS485

Answers: 2

body: Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.

body: I don't think you can use pins 9 and 10 they are connected to the internal mSPI flash, uart0 is connected to FTDI usb chip, use uart2 on 16 and 17.


body:
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:**
[![stacktrace][1]][1]

  [1]: https://i.stack.imgur.com/N5Tks.png

title: ESP12E Soft WDT reset stack trace leads to libraries

Answers: 2

body:
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:

1. Use the right library for the right job
2. NEVER mess with the WDT
3. NEVER mix sync + async code
4. 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.

body:
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...


body:
I'm a newbie to this forum so kindly excuse me for any errors.

I'm using an Arduino Uno and Max485 (RS-485 to TTL) to communicate with a Power meter, but I'm able to receive the data from the Power Meter only once and then it prints "Error" continuously. I need to reopen the Serial Monitor to get the new reading but again the issue persists thereafter. Reading parameter is voltage.

I am using **ModbusMaster** library. Please refer to the code below.

    #include <ModbusMaster.h>

    uint16_t vl1, v11;
    uint8_t result1;
    float v1;

    ModbusMaster  node;
    #define MAX485_DE      2
    #define MAX485_RE_NEG  3

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

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

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

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

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

      Serial.begin(9600);

      node.begin(1, Serial);

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

    }

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

      delay(1000);

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

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

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

This is the output I get from the Serial Monitor

    Voltage:221.21
    Error
    Error
    Error

FYI, Meter communication details as follows:

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

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

title: Unable to read data more than once via Modbus RTU

Answers: 0


body:
I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.[![][1]][2]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/IbWei.jpg
  [2]: https://i.stack.imgur.com/SJf45.jpg

title: What is the difference between the two sensors?

Answers: 1

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

  [1]: https://www.google.com/amp/s/surtrtech.com/2018/01/27/how-to-use-the-fc-51-infrared-proximity-obstacle-avoidance-sensor-with-arduino/amp/


body:
I'm trying to connect a [TCA9548a breakout][1] to my nano (also tried using an uno), but it can't recognise it - using the [i2c scanner][2] it just hangs on 'scanning...'

I've tried everything suggested in similar posts - checking connections, adding/not adding pullups (this nano I think already has them) and checking other i2c devices using same setup (which work fine). If I connect another i2c device, without the TCA, and have the i2c scanner working well and finding it, then connect SCL from the TCA (whether or not SDA is also connected) the scanner hangs.

When I was checking connections with the tca connected, it did work just once, finding it. Haven't been able to repeat that though since, I can't remember exactly what I was doing at the time.

Any help please?

Thanks in advance

i2c scanner:
~~~
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

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

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

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

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

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

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

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

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

#define TCAADDR 0x74

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

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

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

    Wire.begin();

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

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

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

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

void loop()
{
}
~~~~

  [1]: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout/wiring-and-test
  [2]: https://playground.arduino.cc/Main/I2cScanner/

title: i2c code hanging - tried all connections

Answers: 0


body:
I came across this article on Hackaday showing a simple AM transmitter sending a morse code tone 700km!

I'm looking into a EPIRB for myself while deep in the bush / outback hunting or camping, just to send a message to my wife. (a true EPIRB wouldn't be useful to let her know I'm all good, or ask her to call my mate to come pull my truck out of a bog hole)

I plan on sending short text messages via Morse Code, or probably just 8 bit ascii - so speed is not important. If a 50 character message takes 5 minutes to send - so be it... It's meant for check ins, not rapid messaging.

I'll take care of the screen and keyboard side of it - but just interested if anyone has any thoughts or experience using a long range AM signal generator like in the link, and interfacing an Arduino as a transceiver...

https://hackaday.com/2014/12/19/gibson-girl-emergency-beacon-built-from-a-wind-up-flashlight/

title: Ultra Long Range (200-500km) Arduino Communication using a Gibson Girl

Answers: 0