message:
Arduino MKR GSM 1400 fails to start up without Serial Monitor

This question is similar to another question, but I have added more details. See: [MKR GSM 1400 Works only when connected to computer][1].

I have designed and built a custom board into which I plug an Arduino MKR GSM 1400. It's a basic IO abstraction level shifter as the system I am integrating to run on 24 V logic (done via opto-couplers). Everything is working perfectly and as-designed. I've added an I2C EEPROM.

When I boot the board from an external ATX supply +12 V line it doesn't complete setup. After I've left it for some time, I connect it to my PC USB port and open the serial monitor in the Arduino IDE and it simply completes the setup process and enters loop successfully.

Voltages are perfect. The 12-24 V supply is first fed through a standard 7810 (since I need +10 V for the analog lines of the controlled system) and then a 7805. The +5 V output of the 7805 is sent into the Vin of the Arduino. Measuring VIN with a DMM reads +5.07 V and VCC reads +3.33 V. I have a 3.7 V, 300 mAh 25C Li-Po connected to the battery port on the Arduino, to deal with the current requirements as specified in the documentation.

I thought this could be a power issue, so I also tried booting it with a 10 Ah USB Power bank that has 2 x 5 V, 2 A (3 A max) USB ports. Same result, until I connect the PC with the serial monitor.

Simplified Arduino Code:

```
#include <MKRGSM.h>
#include <Wire.h>

GSM gsm;
GPRS gprs;
GSMServer server(80);
GSMSSLClient client;
GSM_SMS sms;

void setup() {
  //Initialise Serial
  Serial.begin(9600);
  while(!Serial)
  {}
  Serial.println("Gineer.Industrial.GSM.Controller");
  Serial.println("www.gineer.co.za");
  Serial.print("Hardware Version: ");
  Serial.println(hwVersion);
  Serial.print("Software Version: ");
  Serial.println(swVersion);
  Serial.println();

  Serial.print("Connecting");

  bool connected = false;

  while (!connected) {
```
\>\>\> Here is where it gets stuck until I plug in the USB Serial Monitor, and then it continues happily.
```

    if ((gsm.begin(SIMpinNumber) == GSM_READY) &&
        (gprs.attachGPRS(SIMgprsAPN, SIMgprsLogin, SIMgprsPassword) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.print(".");
      delay(1000);
    }
  }
.
.
.
```
Interestingly, the +5 V output pin on the Arduino measures 4.68 V when not connected to the PC. I don't however use this pin as I have the 7805 on my board. All other voltages measure as above at all times.

  [1]: https://arduino.stackexchange.com/questions/69109/mkr-gsm-1400-works-only-when-connected-to-computer

body:
`while(!Serial) {}` will wait for a serial connection and in your program will block execution until it gets one.

Remove it and your program should continue without the serial monitor.


sender: user

message:
Can I use an internal clock on Wemos D1 Mini?

I have a working Wemos D1 Mini setup measuring temperature and sending it over wifi to my server. Now I'm using a battery powered unit, and playing around with power consumption optimization and how to reduce it.

One thing I need is time (current, either epoch or DST) - so I implemented NTP, but everytime my ESP is waking up after deep-sleep, it needs to reconnect to wifi, gather time, measure temperature, send results.

This [pdf states that ESP8266][1] has an internal clock. I'm having troubles finding anything beside "RTC shields on Wemos/Arduino" or "NTP on ESP8266" on the internet about something that is like an internal clock. There must be something, because otherwise it could not work (my understanding about clock and hardware is limited by now).

My question is: can I use NTP to update my internal clock, using it for some minutes (I think it will drift after some minutes), updating via NTP once in a while - to simply reduce network traffic and still use deep-sleep mode?

Any hints are welcome!

  [1]: https://www.espressif.com/sites/default/files/9b-esp8266-low_power_solutions_en_0.pdf

sender: assistant

body:
I think the answer to your question can best be summed up by one word: "Kinda".

The best reasoning is the [NodeMCU Lua documentation](https://nodemcu.readthedocs.io/en/master/modules/rtctime/) which states:

> Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, the RTC is not really a Real Time Clock in the normal sense of the word. While it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly between when the chip is running and when it is sleeping, meaning that any calibration performed while the chip is active becomes useless mere moments after the chip has gone to sleep. As such, calibration values need to be deduced across sleep cycles in order to enable accurate time keeping. [...]

So while it's called RTC it's not an RTC in the traditional sense - it's merely a timer that runs even when sleeping, but not with any degree of accuracy.

You can access the current RTC count with the [Non OS SDK](https://www.espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf) function

```
uint32_t system_get_rtc_time()
```

You can combine that with

```
uint32_t system_rtc_clock_cali_proc()
```

which gives you the number of uS per tick of the RTC timer.

There's no way to change the RTC timer count, so you will have to work out some "delta magic" to update your own internal time value (an epoch value is simplest) from the difference between successive calls to get the RTC count.

All somewhat tricky and the accuracy won't be great anyway, so you'll be wanting to use NTP to update that epoch value regularly.

But it could give you a "rough idea" of how long you've been asleep for, etc.

You would have to run some experiments to know how much the time drifts compared to the NTP value in real usage.


message:
What sensors do I need to detect magnetic "take off"?

I want to build a sensor using arduino (or any other esp) measuring the release of a leg on a floor panel. I've build a prototype using copper plates and a BBC Micro:bit, which works fairly well. But I want to use magnetic sensors, determining release of the leg.

My education on magnetic is - simple. I know it exists. I know it's one of four basic forces in nature (ha!). But I don't know how to measure it using electronic circuits (I'm new to this topic).

Imagine one person stands on a plate, wearing magnets on his foot (say "magnetic socks"). I want to immediately detect when the person raises his leg. What kind of sensors do I need?

body:
You have two options here, either a [Hall Effect sensor][1] or an [Inductive Sensor][2]. The hall effect sensor is probably the best option. This will likely need some calibration on your end to identify the exact value you record at "Take Off" for your setup.

  [1]: https://www.digikey.co.uk/product-detail/en/texas-instruments/DRV5053EAQLPGQ1/296-DRV5053EAQLPGQ1-ND/6571756?utm_adgroup=Sensors, Transducers&utm_source=google&utm_medium=cpc&utm_campaign=Shopping_Supplier_Texas Instruments_0296_Co-op&utm_term=&productid=6571756&gclid=CjwKCAjw1K75BRAEEiwAd41h1NSsMAKbPwn7d4kGXknV58L9C9S6-qA_JMbNzwtLQyFXLwBj6Mj8HhoCtRUQAvD_BwE
  [2]: https://uk.rs-online.com/web/p/inductive-proximity-sensors/7033739?cm_mmc=UK-PLA-DS3A-_-google-_-PLA_UK_EN_Automation_&_Control_Gear_Whoop-_-Inductive Proximity Sensors_Whoop-_-7033739&matchtype=&pla-336998392933&gclid=CjwKCAjw1K75BRAEEiwAd41h1EQjralUvAqwlkK-irIb1x8ZqSs966DNr1wRNdanZAHMXHYhl6QFRhoC3s4QAvD_BwE&gclsrc=aw.ds


message:
Why does my Wemos D1 Mini stops working while charging via solar?

I'm using an battery shield to recharge my battery. I want to use a solar panel, so I bought one (5V 240mA). I'm pretty sure, it won't recharge my battery fully, but that's not the point.
I've assembled my board with my shield, soldered the solar panel together with an schottky-diode and put it on USB (since the shield allows charging via USB). All fine, I get some electric power in the sun - yeah!

But my Wemos D1 Mini only runs for say 2-3 minutes and than ... dead? Restarting works, but only lasts again 2-3 minutes. This only happens while the battery shield is charging via solar. I already tested using any USB charging (my computer) - this simply works.

Basically I rebuild the circuit like described on [TheAustrian/Wemos-D1-Mini-BME280-Weather-Station][1] but only one solar panel attached and using the Wemos D1 Mini Battery Shield instead of the TP4056.

Any hints what's going on? Why can't I run the board while charging via solar? Did I miss something?

  [1]: https://github.com/TheAustrian/Wemos-D1-Mini-BME280-Weather-Station

body:
The TP4056 Module will output a max of 4.2V which is less than the 5V the Wemos D1 Mini is expecting on its 5V connection (Assuming you have connected the circuit as shown in the Github guide). When the solar panel is charging it's likely that the TP4056 is causing a driving issue on the supply of the Wemos causing it to potentially [Brownout][1] .

I would not connect the solar panel to the Wemos like this, I would have it connected to the battery then the battery connected to a 5V Step Up Power Converter like shown below (This reduces efficiency but give the MCU a stable supply),

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

My recommendation for the wiring,

[![enter image description here][3]][3]

  [1]: https://en.wikipedia.org/wiki/Brownout_(electricity)
  [2]: https://i.stack.imgur.com/1a7kc.jpg
  [3]: https://i.stack.imgur.com/yHbHf.png


message:
Unable to read Arduino+ESP8266 full get Response

Using below code I am able to invoke HTTP Get request, but I am not able to read full HTTP Response. Observing only output like( +IPD,0,141:HTTP/1.7. ). Please let me know how can I read full response?
Any Idea what is the issue?

    #include <SoftwareSerial.h>

    #define RX 2
    #define TX 3
    String WIFI_SSID = "xyz";       // Your WiFi ssid
    String PASSWORD = "xys";         // Password

    String HOST = "192.168.0.156";
    String PATH = "/test";
    String PORT = "8080";

    int countTrueCommand;
    int countTimeCommand;
    boolean found = false;

    SoftwareSerial esp8266(RX, TX);

    void setup() {
      Serial.begin(9600);
      esp8266.begin(9600);
      esp8266.println("AT");
      Serial.println(esp8266.read());
      sendCommandToESP8266("AT", 5, "OK");
      sendCommandToESP8266("AT+CWMODE=1", 5, "OK");
      sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
    }

    void loop() {
      String postRequest = "GET " + PATH  + " HTTP/1.1\r\n" +
                           "Host: " + HOST + "\r\n" +
                           "Accept: *" + "/" + "*\r\n" +
                           "\r\n";

      sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
      sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
      String cipSend = "AT+CIPSEND=0," + String(postRequest.length());
      sendCommandToESP8266(cipSend, 4, ">");
      sendData(postRequest);
      readESP8266(8000);
      sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
    }

    void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
      Serial.print(countTrueCommand);
      Serial.print(". at command => ");
      Serial.print(command);
      Serial.print(" ");
      while (countTimeCommand < (maxTime * 1))
      {
        esp8266.println(command);
        if (esp8266.find(readReplay))
        {
          found = true;
          break;
        }

        countTimeCommand++;
      }

      if (found == true)
      {
        Serial.println("Success");
        countTrueCommand++;
        countTimeCommand = 0;
      }

      if (found == false)
      {
        Serial.println("Fail");
        countTrueCommand = 0;
        countTimeCommand = 0;
      }

      found = false;
    }

    void sendData(String postRequest) {
      Serial.println(postRequest);
      esp8266.println(postRequest);
      delay(1500);
      countTrueCommand++;
    }

    void readESP8266(const int timeout)
    {
      String reponse = "";
      long int time = millis();
      while( (time+timeout) > millis())
      {
        while(esp8266.available())
        {
          reponse+=esp8266.readString();
        }
      }
      Serial.print(reponse);
    }

Output:

    Success
    1. at command => AT+CWMODE=1 Success
    2. at command => AT+CWJAP="xyz","xys" Success
    3. at command => AT+CIPMUX=1 Success
    4. at command => AT+CIPSTART=0,"TCP","192.168.0.156",8080 Success
    5. at command => AT+CIPSEND=0,56 Success
    GET /test HTTP/1.1
    Host: 192.168.0.156
    Accept: */*

    busy s...

    Recv 56 bytes

    SEND OK

    +IPD,0,141:HTTP/1.7. at command => AT+CIPCLOSE=0 Success

body:
Finally the HTTP Get request with Arduino Uno + ESP8266 Wifi shield which is working is below:

// This is a demo example using a public http server for testing both GET and POST requests

    #include <Arduino.h>
    #include <LiteESP8266Client.h>

    #define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

    LiteESP8266 radio;

    const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
    const char password[] PROGMEM = "abc";    //change it to your wifi password
    const char host[] PROGMEM = "192.168.0.156";
    const int port = 8080;

    const char http_get_request[] PROGMEM = "GET /test HTTP/1.1\r\n";
    const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
    const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
    const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
    const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
    const char http_content_length_header[] PROGMEM = "Content-Length: ";
    const char success[] PROGMEM = "success";
    const char failed[] PROGMEM = "failed";
    const char CRLF[] PROGMEM = "\r\n";
    const char error_data_null[] PROGMEM = "Error: data came back null.";

    void setupStationMode() {
      Serial.print("Setup station mode... ");
      if (radio.set_station_mode()) {
        Serial.println("success");
      } else {
        Serial.println("failed");
      }
    }

    void joinAP() {
      Serial.print("Join AP ");
      Serial.print(ssid);
      Serial.print("... ");
      if (radio.connect_to_ap(ssid, password)) {
        Serial.println("Success");
      } else {
        Serial.println("Failed");
      }
    }

    void establishTcpConnect() {
      Serial.print("Establish TCP Connection... ");
      if (radio.connect_progmem(host, port)) {
        Serial.println( "Success");
      } else {
        Serial.println( "Failed");
      }
    }

    void getHttpPacket() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println("Packet Received...");
          Serial.println(data);
        } else {
          Serial.println(error_data_null);
        }
      }
      free(data);
    }

    void httpGet() {
      Serial.println("Sending GET request... ");
      radio.send_progmem(http_get_request);
      radio.send_progmem(http_useragent);
      radio.send_progmem(http_host);
      radio.send_progmem(http_close_connection);
    }
    void setup() {
      delay(2000);
      radio.begin(9600,2,3);
      Serial.begin(9600);
      while (!Serial) {};

      setupStationMode();
      joinAP();
    }

    void loop() {
      establishTcpConnect();

      httpGet();
      getHttpPacket();
      }
Output:

    Setup station mode... success
    Join AP ⸮... Success
    Establish TCP Connection... Success
    Sending GET request...
    Packet Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 27
    Date: Fri, 07 Aug 2020 13:04:03 GMT
    Connection: close

    Greetings from Spring Boot!

But one issue I am facing is after few call the HTTP invocation is getting stopped probably memory being full. Will check this.


message:
ESP-NOW and WIFI and OTA at the same time on Sender and Receiver

I am trying to set up two ESP32s so that they can be updated via OTA and at the same time send sensor readings using ESP-NOW, from Sender Board to Receiver Board.

For this to work both boards must connect to wifi and simultaneously send messages over ESP-NOW.

I don't mind using a mode where a button is pressed and Wifi is only then enabled but switching wifi on and off seems to have intermittent success.

I have tried setting the channels to the same on both boards but this does not work.

In the example below I have stripped all the OTA code out and the code needed for ESP-NOW and just the line for WIFI enable

> WiFi.begin(ssid, password);

which when enabled causes the delivery to fail.

Here is my Sender Code:

            #include <esp_now.h>
            #include <WiFi.h>
            #include <Wire.h>
            #define ssid "MYNETWORKSSID"
            #define password "mynetworkpassword"

             const int sNine = 33;

             #define CHAN_AP 2

            uint8_t broadcastAddress[] = {0x24, 0x62, 0xAB, 0xDC, 0x70, 0x90};
            int hall;

            String success;

            typedef struct struct_message {
                int hall;
            } struct_message;
            struct_message hallReadings;

            // Callback when data is sent
            void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
              Serial.print("\r\nLast Packet Send Status:\t");
              Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
              if (status ==0){
                success = "Delivery Success :)";
              }
              else{
                success = "Delivery Fail :(";
              }
            }

            void setup() {
              // Init Serial Monitor
              Serial.begin(115200);
              WiFi.mode(WIFI_STA);
             WiFi.begin(ssid, password); // PROBLEMATIC LINE

              // Init ESP-NOW
              if (esp_now_init() != ESP_OK) {
                Serial.println("Error initializing ESP-NOW");
                return;
              }
              // Once ESPNow is successfully Init, we will register for Send CB to
              // get the status of Trasnmitted packet
              esp_now_register_send_cb(OnDataSent);

              // Register peer
              esp_now_peer_info_t peerInfo;
              memcpy(peerInfo.peer_addr, broadcastAddress, 6);
              peerInfo.channel = CHAN_AP;
              peerInfo.encrypt = false;

              // Add peer
              if (esp_now_add_peer(&peerInfo) != ESP_OK){
                Serial.println("Failed to add peer");
                return;
              }
            }

            void loop() {
              // getReadings();

               hallReadings.hall = analogRead(sNine);

              esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &hallReadings, sizeof(hallReadings));

              if (result == ESP_OK) {
                Serial.println("Sent with success");
              }
              else {
                Serial.println("Error sending the data");
              }
              delay(100);
            }

Here is my Receiver code:

    #include <esp_now.h>
    #include <WiFi.h>
    #include <Wire.h>

     const int sNine = 15;

    //Wi-Fi channel (must match the gateway wi-fi channel as an access point)
    #define CHAN_AP 2

    // Define variables to store incoming readings
    int incomingHall;

    //Structure example to send data
    //Must match the receiver structure
    typedef struct struct_message {
        int hall;
    } struct_message;

    // Create a struct_message to hold incoming sensor readings
    struct_message incomingReadings;

    void updateDisplay(){

      Serial.print(incomingReadings.hall);
    }

    // Callback when data is received
    void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
      memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
      incomingHall = incomingReadings.hall;
    }

    void setup() {
      // Init Serial Monitor
      Serial.begin(115200);
      // Set device as a Wi-Fi Station
      WiFi.mode(WIFI_STA);
      // Init ESP-NOW
      if (esp_now_init() != ESP_OK) {
        Serial.println("Error initializing ESP-NOW");
        return;
      }
      // Register for a callback function that will be called when data is received
      esp_now_register_recv_cb(OnDataRecv);
    }

    void loop() {

      updateDisplay();
      delay(100);
    }

body:
I do something similar on a ESP8266 retrieving time from a NTP-server.
Though it is just a "work around".

- I connect to the router retrieving the NTP-time.
- storing the time-information into RTC-RAM including a flag that indicates "time received"
- then do a software-RESET
- the setup-function checks this flag to decide if the ESP8266 shall connect to the router or shall keep WiFi OFF and activate ESP-NOW

if you want to use this for OTA it could "work" like this

sending a special ESP-NOW-Message initiating setting a flag "do_OTA" in RTC-RAM and then re-boot
the setup-function looks for this flag "do_OTA" to be set does what its name says
clearing the "do_OTA"-flag

What I don't know is writing new code into flash is a different thing than just re-booting through a software-reset. So maybe the content of the RTC-RAM gets lost through the update-process.

If so you could write the flag into flash using LittleFS

best regards Stefan


body:
Another method that works if you don't mind having both at the same time:

Instead of WiFi.begin(ssid, password);
I use WiFi.softAp(ssid,password,channel); for both Sender and Receiver.


body:
If you want to switch the softAP connection On/OFF you can do like StefanL38 suggests and have the Receiver transmit a ESP-NOW message with a value to the Sender, but you don't need a reboot. You can drop softAP and come up as STA or vise versa, for example.

```c++
    if(incomingid == 3){
      incomingValue = incomingReadings.Value;

      // to allow OTA, using Elegant OTA, haven't tried others.

    if(incomingValue == 1){
      WiFi.softAP(ssid,password,6);
      Serial.print("Connecting to ESP32 SSID ");
      Serial.println(ssid);
      IPAddress IP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(IP);
      WiFi.printDiag(Serial);
    }

      // to disconnect and allow ESP-NOW via Station mode.

   else if(incomingValue == 0){
      WiFi.softAPdisconnect(true);
      delay(1000);
      WiFi.mode(WIFI_STA);
      delay(1000);
      WiFi.printDiag(Serial); // STA Defaults to channel 1
      esp_wifi_set_promiscuous(true);
      esp_wifi_set_channel(6, WIFI_SECOND_CHAN_NONE); // channel 6 setup
      esp_wifi_set_promiscuous(false);
      WiFi.printDiag(Serial);
    }
  }
```


message:
Why is their need of response time needed in esp8266 AT commands?

I am writing an AT commands firmware for esp8266 via connecting it to atmega2560.
Now the question is how will I come to know the response time for AT commands for writing its firmware to read the response?
in fact prior to this thought, the question comes why is their need of response time in AT commands?
does response time concept is there in all modules where AT commands are used like gsm modules, HC05,etc.

body:
Your esp8266 firmware isn't required to wait before responding to the atmega2560, but the reality is that it simply *can't* respond in zero-time. The esp will take some processing to interpret the command that was sent to it and to create the reply to the atmega. And that is even if it doesn't have to wait for some distant server.

If the esp has to send a WiFi request to a server (which has the same constraints of processing time, plus other requests ahead of yours), that only adds to the esp's delay in responding to the atmega.

The bottom line is that the esp isn't required to wait any amount of time to respond; its just however much time it takes to acquire any data it needs, plus processing time to format it and send it back to the atmega.


message:
how to fix mirrored text on 3.2 inch IPS TFT LCD Display ILI9481 480X320 36 Pins for Arduino Mega2560

i am working on a project on my arduino mega2560. I want to show reading of the sensors on the TFT display, the problem is the text displayed on the screen is mirrored. Since i am very new to arduino i don't know how to fix the problem. I have check a few videos on youtube but nothing helped. I am using the example from the UTFT library arduino (AVR) => UTFT_DEMO_480x320

body:
The orientation of the display is controlled by the "Set Address Mode" command (0x36) at [line 42](https://github.com/dgolda/UTFT/blob/master/tft_drivers/ili9481/initlcd.h#L42) of the ILI9481 driver.

The current value is `0x0A` which is `00001010` in binary.  According to [the datasheet](https://www.displayfuture.com/Display/datasheet/controller/ILI9481.pdf) (8.2.25) bit 6 is "Column Address Order", and that is set to "Left to Right" currently.

Turning that bit on should reverse the column order for the display.

So changing those two lines of code to:

 LCD_Write_COM(0x36);
 LCD_Write_DATA(0x4A);

should have the desired effect.


body:
Had this same problem with everything mirrored/backward.  Not sure you're still trying, but for any others with this issue, here's how I addressed it..

If using the UTFT library from RinkyDink electronics, open up their initlcd.h file.  In the section for Memory Access Control (lines 85-86 in version I have), change the write to:

LCD_Write_DATA(0x08);

Bit 0 controls vertical flip, Bit 1 controls horizontal flip.


body:
I had the problem of a mirrored display. none of the solutions above worked. I found that the Line in the source code had the wrong driver defined.
change the line in the source code (file name "UTFT_Demo_480x320"
line# 32 to this: UTFT myGLCD(CTE40, 38, 39, 40, 41);
The new part is 'CTE40'. This works with the ILI9486.
You can find all of the different chip numbers in the file "UTFT.h'


message:
Arduino ESP8266 Wifi Shield GET request with LiteESP8266Client stops after few HTTP request

Below HTTP Get request is working but after few GET request(5-6) the code stops and once I press Arduino reset button then only it start working. Probably looks like something is causing OOM:

    // This is a demo example using a public http server for testing both GET and POST requests

    #include <Arduino.h>
    #include <LiteESP8266Client.h>

    #define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

    LiteESP8266 radio;

    const char ssid[] PROGMEM = "abcd";    //change it to your wifi SSID
    const char password[] PROGMEM = "abcd";    //change it to your wifi password
    const char host[] PROGMEM = "192.168.0.156";
    const int port = 8080;

    const char http_get_request[] PROGMEM = "GET /getLedStatus HTTP/1.1\r\n";
    const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
    const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
    const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
    const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
    const char http_content_length_header[] PROGMEM = "Content-Length: ";
    const char success[] PROGMEM = "success";
    const char failed[] PROGMEM = "failed";
    const char CRLF[] PROGMEM = "\r\n";
    const char error_data_null[] PROGMEM = "Error: data came back null.";
    const int ledPin=11;
    void setupStationMode() {
      Serial.print("Setup station mode... ");
      if (radio.set_station_mode()) {
        Serial.println("success");
      } else {
        Serial.println("failed");
      }
    }

    void joinAP() {
      Serial.print("Join AP ");
      Serial.print("... ");
      if (radio.connect_to_ap(ssid, password)) {
        Serial.println("Success");
      } else {
        Serial.println("Failed");
      }
    }

    void establishTcpConnect() {
      Serial.print("Establish TCP Connection... ");
      if (radio.connect_progmem(host, port)) {
        Serial.println( "Success");
      } else {
        Serial.println( "Failed");
      }
    }

    void getHttpPacket() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println("Response Received...");
          Serial.println(data);
          if(strstr(data, "ON") != NULL) {
            digitalWrite(ledPin, HIGH);
          }else{
            digitalWrite(ledPin, LOW);
          }
        } else {
          Serial.println(error_data_null);
        }
      }
      free(data);
    }

    void httpGet() {
      Serial.println("Sending GET request... ");
      radio.send_progmem(http_get_request);
      radio.send_progmem(http_useragent);
      radio.send_progmem(http_host);
      radio.send_progmem(http_close_connection);
    }
    void setup() {
      delay(2000);
      pinMode(ledPin, OUTPUT);
      radio.begin(9600,2,3);
      Serial.begin(9600);
      while (!Serial) {};

      setupStationMode();
      joinAP();
    }

    void loop() {
      establishTcpConnect();

      httpGet();
      getHttpPacket();
      }

Complete OUTPUT(See Last TCP call when it stopped):

    Setup station mode... success
    Join AP ... Success
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 3
    Date: Fri, 07 Aug 2020 13:47:47 GMT
    Connection: close

    OFF
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 3
    Date: Fri, 07 Aug 2020 13:47:53 GMT
    Connection: close

    OFF
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 3
    Date: Fri, 07 Aug 2020 13:47:58 GMT
    Connection: close

    OFF
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 3
    Date: Fri, 07 Aug 2020 13:48:04 GMT
    Connection: close

    OFF
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 3
    Date: Fri, 07 Aug 2020 13:48:10 GMT
    Connection: close

    OFF
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 2
    Date: Fri, 07 Aug 2020 13:48:16 GMT
    Connection: close

    ON
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 2
    Date: Fri, 07 Aug 2020 13:48:21 GMT
    Connection: close

    ON
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 2
    Date: Fri, 07 Aug 2020 13:48:27 GMT
    Connection: close

    ON
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 2
    Date: Fri, 07 Aug 2020 13:48:33 GMT
    Connection: close

    ON
    Establish TCP Connection... Success
    Sending GET request...
    Establish TCP Connection...

Probably looks like memory is not getting freed. I am using Arduino UNO + ESP8266 sheild

**Update 2**
Tried with other REST Server and same issue is observed:

    // This is a demo example using a public http server for testing both GET and POST requests

    #include <Arduino.h>
    #include <LiteESP8266Client.h>

    #define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

    LiteESP8266 radio;

    const char ssid[] PROGMEM = "abc";    //change it to your wifi SSID
    const char password[] PROGMEM = "abc";    //change it to your wifi password
    const char host[] PROGMEM = "httpbin.org";
    const int port = 80;

    const char http_get_request[] PROGMEM = "GET /get HTTP/1.1\r\n";
    const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
    const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
    const char http_host[] PROGMEM = "Host: httpbin.org\r\n";
    const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
    const char http_content_length_header[] PROGMEM = "Content-Length: ";
    const char success[] PROGMEM = "success";
    const char failed[] PROGMEM = "failed";
    const char CRLF[] PROGMEM = "\r\n";
    const char error_data_null[] PROGMEM = "Error: data came back null.";
    const int ledPin=11;
    void setupStationMode() {
      Serial.print("Setup station mode... ");
      if (radio.set_station_mode()) {
        Serial.println("success");
      } else {
        Serial.println("failed");
      }
    }

    void joinAP() {
      Serial.print("Join AP ");
      Serial.print("... ");
      if (radio.connect_to_ap(ssid, password)) {
        Serial.println("Success");
      } else {
        Serial.println("Failed");
      }
    }

    void establishTcpConnect() {
      Serial.print("Establish TCP Connection... ");
      if (radio.connect_progmem(host, port)) {
        Serial.println( "Success");
      } else {
        Serial.println( "Failed");
      }
    }

    void getHttpPacket() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println("Response Received...");
          Serial.println(data);
          if(strstr(data, "ON") != NULL) {
            digitalWrite(ledPin, HIGH);
          }else{
            digitalWrite(ledPin, LOW);
          }
        } else {
          Serial.println(error_data_null);
        }
      }
      free(data);
    }

    void httpGet() {
      Serial.println("Sending GET request... ");
      radio.send_progmem(http_get_request);
      radio.send_progmem(http_useragent);
      radio.send_progmem(http_host);
      radio.send_progmem(http_close_connection);
    }
    void setup() {
      delay(2000);
      pinMode(ledPin, OUTPUT);
      radio.begin(9600,2,3);
      Serial.begin(9600);
      while (!Serial) {};

      setupStationMode();
      joinAP();
    }

    void loop() {
      establishTcpConnect();

      httpGet();
      getHttpPacket();
      }

Output:

    Setup station mode... success
    Join AP ... Success
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200 OK
    Date: Fri, 07 Aug 2020 13:57:45 GMT
    Content-Type: application/json
    Content-Length: 238
    Connection: close
    Server: gunicorn/19.9.0
    Access-Control-Allow-Origin: *
    Access-Control-Allow-Credentials: true

    Response Received...
    {
      "args": {},
      "headers": {
        "Host": "httpbin"origin": "106.51.29.214",
      "url": "http://httpbin.org/get"
    }
    CLOSED
    ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
    Establish TCP Connection... Success
    Sending GET request...
    Response Received...
    HTTP/1.1 200 OK
    Date: Fri, 07 Aug 2020 13:57:57 GMT
    Content-Type: application/json
    Content-Length: 238
    Connection: close
    Server: gunicorn/19.9.0
    Access-Control-Allow-Origin: *
    Access-Control-Allow-Credentials: true

    Response Received...
    {
      "args": {},
      "headers": {
        "Host": "httpbin"origin": "106.51.29.214",
      "url": "http://httpbin.org/get"
    }
    CLOSED
    ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
    Establish TCP Connection... Success
    Sending GET request...
    Establish TCP Connection...

 Server side code

    package com.test.iot;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class HelloController {
        private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
        private String ledStatus="OFF";
        @RequestMapping("/test")
        public String index() {
            logger.info("invoked");
            return "Greetings from Spring Boot!";
        }
        @RequestMapping("/getLedStatus")
        public String getLedStatus() {
            logger.info("ledStatus");
            return ledStatus;
        }
        @RequestMapping("/toggleLedStatus")
        public String toggleLedStatus(){
            if(ledStatus.equals("ON")){
                ledStatus="OFF";
            } else {
                ledStatus="ON";
            }
            return String.format("New LED Status: %s", ledStatus);
        }
    }

body:
There is a bug on the library example webclient.ino on `getHttpPacket()` and `getHttpResponse()` that it didn't free the memory correctly, causing memory leak. I've updated the code on github repo.

Specifically on your `getHttpPacket()`, here is the corrected code:

    void getHttpPacket() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println(F("Response Received..."));
          Serial.println(data);
          if(strstr(data, "ON") != NULL) {
            digitalWrite(ledPin, HIGH);
          }else{
            digitalWrite(ledPin, LOW);
          }
          free(data);  // free the memory in every packet as Arduino does not have enough memory
        } else {
          Serial.println(error_data_null);
        }
      }
      // free(data);
    }

If you have further issue regarding the library, you can raise an "issue" on the github, and I will take a look.


message:
How do powering arduino both barrel jack and lipo battery together?

I have arduino mega and Lipo batterry [such this][1] and Lipo battery charger [5V USB Boost][2]. I am powering arduino normally from barrel Jack with an 9 Volt adaptor. But if there is power cut occur, I dont want to stop, I want powering arduino with Lipo battery. After power come back, arduino contunie to powering from barrel jack again at the same time battery start to charge. How can I succes this. Do you have any sample circuit?

After Majenko♦ comment, I've tried circuit but there is heating problem occur. More then 70 celsius. Is that normal?

Circuit

[![enter image description here][3]][3]

Termal Circuit

[![enter image description here][4]][4]

  [1]: https://karakoyelektronik.com/li-po/px425085-81660
  [2]: https://www.robolinkmarket.com/lityum-pil-sarj-devresi-5v-usb-boost-modul?_sgm_campaign=scn_8ac6d76ec4000&_sgm_source=6909&_sgm_action=click
  [3]: https://i.stack.imgur.com/4pvKa.jpg
  [4]: https://i.stack.imgur.com/hStJ6.jpg

body:
As is described in [this post from the arduino forum][1], There is a MOSFET switch in series with the USB connector +5V input line.  If the battery booster 5V output is connected to the USB input jack, then it will automatically power the UNO whenever power is disconnected from the barrel jack, and will be automatically disconnected whenever at least 7.0V is available at the barrel jack.

If you are experiencing over-heating problems, then you are probably overheating the linear regulator that steps down the barrel jack voltage to 5V.  You need about 7-7.5V at the barrel jack to overcome the 2-2.5V loss through the linear regulator, but anything higher than about 7.5V will just cause the linear regulator to get hotter.

  [1]: https://forum.arduino.cc/index.php?topic=122335.0


message:
Why is my CNC shield smoking? Is it safe to keep on for long periods of time?

I am working on a project that involves moving stepper motors, and the device will have to be on for upwards of hours. I am moving the bipolar NEMA17 stepper motors using a Protoneer CNC shield V3 on top of an Arduino UNO and DRV8825 stepper drivers. Though I haven't left the motors on for too long, whenever I do for longer periods, maybe 5 minutes or more, smoke starts being emitted around the 4 pins I connect my motors with. My question is that, if anyone has had a similar issue before, if they could explain why this occurs. I would also like to know if the stepper drivers are actually being protected by the heatsinks, because they can get ridiculously hot even after a few minutes and I'm worried that they wouldn't be able to last more than 15 minutes before exploding. Hopefully there's enough information here for someone to understand what's going on, but I'd glad to give more if that helps get a better idea of what's going on here. Thank you!

[![enter image description here][1]][1]

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

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/Q1Rzo.jpg
  [2]: https://i.stack.imgur.com/icduH.jpg
  [3]: https://i.stack.imgur.com/o7dXG.jpg

body:
Those NEMAs are big ones - i suspect too big for the little A4988 chips - which can only provide 2A when actively cooled and generally only for short periods. I wouldn't try to push more than 1.7ish Amps for any length of time.

You will also need to set the vREF correctly for the motors you are using - if this is not set you will either provide too little current or too much current.

Look up the specifications for the NEMAs you have - and upgrade the Stepper controller to something more like a [TB6600][1] that can handle greater current.

Also when the Steppers are not being used - disable (if you dont need them to hold) this will turn off the drivers and let them cool between runs/moves.

  [1]: https://uk.banggood.com/TB6600-Upgraded-Stepper-Motor-Driver-Controller-for-4A-940V-TTL-32-Micro-Step-2-or-4-Phase-of-4257-Stepper-Motor-3D-Printer-CNC-Part-p-1453122.html


message:
Is it possible to use Adafruit's Circuit Playground Express's 2MB storage in Arduino IDE?

I understand that the extra 2MB of memory is for circuit python.  However, I wouldn't mind having access to 2MB of storage and using the Arduino IDE/low level C to access it.  Is that possible?  If so, how?

body:
In their [guided tour][1] of the Adafruit Circuit Playground Express, it specifically states:
> You can use this in Arduino or CircuitPython to store files.

So yes, it is possible. As far as the how, according to [this guide][2] (also from Adafruit), that they have also made a library, [Adafruit SPI Flash][3], which has a bunch of examples showing how to read from, write to, and format the SPI flash whilst retaining compatibility with CircuitPython, among other things.

  [1]: https://learn.adafruit.com/adafruit-circuit-playground-express/guided-tour
  [2]: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/using-spi-flash
  [3]: https://github.com/adafruit/Adafruit_SPIFlash


message:
Which board to select in PlatformIO for ESP Wroom 32?

I'm quite new in this microcontroller topic and my next step is to make use of a wlan module, which is a [ESP WROOM 32][1].
As IDE I'm using Visual Studio + PlatformIO and I can't figure out how to access the module. Atm I use these parameters:

    [env:esp12e]
    platform = espressif8266
    board = esp12e
    framework = arduino
    monitor_speed = 74880

but I receive:

    (...)
    CURRENT: upload_protocol = esptool
    Looking for upload port...
    Auto-detected: /dev/ttyUSB0
    Uploading .pio/build/esp12e/firmware.bin
    esptool.py v2.8
    Serial port /dev/ttyUSB0
    Connecting......
    Chip is ESP8266EX
    Features: WiFi
    WARNING: Detected crystal freq 20.45MHz is quite different to normalized freq 26MHz. Unsupported crystal in use?
    Crystal is 26MHz
    MAC: 00:08:ff:00:00:00
    Uploading stub...
    Running stub...

    A fatal error occurred: Invalid head of packet (0x46)
    *** [upload] Error 2
    ============================================================================= [FAILED] Took 3.27 seconds =============================================================================
    The terminal process "platformio 'run', '--target', 'upload'" terminated with exit code: 1.

edit:
The ESP WROOM 32 is a NodeMCU 32 and the board config now is:

    [env:espwroom32]
    platform = espressif32
    board = nodemcu-32s
    framework = arduino
    monitor_speed = 115200

and to check if everything works:

    void setup() {
      pinMode(2, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(2, HIGH);
      delay(1000);
      digitalWrite(2, LOW);
      delay(1000);
    }

I also had problems that `I received Failed to connect to ESP32: Timed out waiting for packet header` nevertheless but [here][2] is a nicely explained workaround for that. Solution is, either you hold the `BOOT` button pressed while uploading the code or you sold a capacitor to specific pins on the board.
I just tried to hold the boot button and it's blinking now. Finally :)
I'm sure, a lot of further issues are only waiting on the way ^

  [1]: https://www.espressif.com/en/products/modules/esp32
  [2]: https://randomnerdtutorials.com/solved-failed-to-connect-to-esp32-timed-out-waiting-for-packet-header/

body:
The ESP WROOM32 is an ESP32, not an ESP8266. You have PlatformIO configured for an ESP8266, specifically the ESP12e, and there's no way that's going to work.

You'll want something more along these lines:
```
[env:espwroom32]
platform = espressif32
```

To choose the board - if you're using a breakout board, you'll need to be more specific about it - what model is it? ESP WROOM32 is just the name of the CPU module; PlatformIO needs to know the size of the flash storage in order to upload properly. Your link is to the entire Espressif ESP32 site. Otherwise, look through [PlatformIO's list of ESP32 boards][1] and find one that matches the amount of flash storage your board has.

You might want to read [PlatformIO's ESP32 documentation][2].

  [1]: https://docs.platformio.org/en/latest/platforms/espressif32.html#boards
  [2]: https://docs.platformio.org/en/latest/platforms/espressif32.html


message:
Problems Sending Signals to the Arduino-Uno via Keyboard

I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.

I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.

    #include <hidboot.h>
    #include <usbhub.h>
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #endif
    #include <SPI.h>

    int SKEY = 8;

    class KbdRptParser : public KeyboardReportParser
    {
        void PrintKey(uint8_t mod, uint8_t key);

      protected:

        void OnKeyDown  (uint8_t mod, uint8_t key);
        void OnKeyUp    (uint8_t mod, uint8_t key);
        void OnKeyPressed            (uint8_t key);
    };

    void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
    {
      MODIFIERKEYS mod;
      *((uint8_t*)&mod) = m;
      Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
      Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
      Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
      Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");

      Serial.print(" >");
      PrintHex<uint8_t>(key, 0x80);
      Serial.print("< ");

      Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
      Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
      Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
      Serial.println((mod.bmRightGUI  == 1) ? "G" : " ");
    };

    void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
    {
      Serial.print("DN ");
      PrintKey(mod, key);
      uint8_t c = OemToAscii(mod, key);

    }

    void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
    {
      Serial.print("UP ");
      PrintKey(mod, key);
    }

    void KbdRptParser::OnKeyPressed(uint8_t key)
    {
      Serial.print("ASCII: ");
      Serial.println((char)key);
    };

    USB Usb;
    HIDBoot<USB_HID_PROTOCOL_KEYBOARD>    HidKeyboard(&Usb);

    KbdRptParser Prs;

    void setup() {

     Serial.begin(9600);
    #if !defined(__MIPSEL__)
      while (!Serial);
      Serial.println("Start");

      if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

      delay( 1 );

      HidKeyboard.SetReportParser(0, &Prs);

    }

    void loop() {
     Usb.Task();
    }

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?

Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!

body:
Keyboards cannot be used quite like you wish - the keyboard will send a key (scan) code when a key is pressed and then repeat that code if the button continues to be pressed. There is a different code sent when the same key is released.

> The scancode for key release is obtained from it by setting the high
> order bit (adding 0x80 = 128). Thus, Esc press produces scancode 01,
> Esc release scancode 81 (hex).  For sequences things are similar:
> Keypad-/ gives e0 35 when pressed, e0 b5 when released. Most keyboards
> will repeat the make code (key down code) when the key repeats.

From: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html


message:
Why is this looping?

I am trying to do something very simple.  I want the LED to fade from full brightness to off.  This works... However, the LED turns back on to full brightness and fades again, in a loop.  I am not sure why.  I think I am missing something obvious.  Once the legThreeBrightness decrements to 0, nothing should happen...

    int legThreeBrightness = 255;

    void setup() {

        pinMode(3, OUTPUT);

    }

    void loop() {

        if (legThreeBrightness = 255){
            do {
                  analogWrite(3, legThreeBrightness);
                  delay(30);
                  legThreeBrightness = legThreeBrightness -5;
               } while (legThreeBrightness >= 0);
        }
    }

body:
This line:

    if (legThreeBrightness = 255){

assigns the value 255 to legThreeBrightness.  That is non-zero so it enters the block and runs the fade now that the variable has been set to 255.

If you just want to compare the value to 255 then use:

    if (legThreeBrightness == 255){

and that way when the loop function repeats it isn't there setting the value back to 255.  This way it will stay at 0.


message:
Counting to 1000 In Both cores execution time problem in esp32?

**I am trying to count to 1000 with single core and dual core with esp32 but the output(run time) dose not make sense, the time which takes a single core should be doubled compared to dual core in theory right?**

Here is the code

```
TaskHandle_t Task1;
TaskHandle_t Task2;
SemaphoreHandle_t baton;

int i = 0;
long l;

void setup() {

  Serial.begin(115200);
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);

  baton = xSemaphoreCreateMutex();
  l = millis();
  xTaskCreatePinnedToCore(
    Task1code, /* Function to implement the task */
    "Task1", /* Name of the task */
    10000,  /* Stack size in words */
    NULL,  /* Task input parameter */
    1,  /* Priority of the task */
    &Task1,  /* Task handle. */
    0); /* Core where the task should run */

//single core or dual core execution

//  xTaskCreatePinnedToCore(
//    Task2code, /* Function to implement the task */
//    "Task2", /* Name of the task */
//    10000,  /* Stack size in words */
//    NULL,  /* Task input parameter */
//    1,  /* Priority of the task */
//    &Task2,  /* Task handle. */
//    1); /* Core where the task should run */

}
void Task1code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);

    }if(i>1000){
      vTaskDelete(Task1);
    }
  }
}
void Task2code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);
    }if(i>1000){
      vTaskDelete(Task2);
    }
  }
}
void loop() {

}
```
The output I get for runtime

```
Single core :- 1033 ms
Dual core :- 701 ms
```
Without ```delay(1);``` command the result is even more obvious

```
Single core :- 39 ms
Dual core :- 40 ms
```
How can I make my algorithm show that single core takes twice time as dual core execution time I wan't both cores to work parallel not one after the other.

body:
Your must use the semaphore to protect the read/write access to `i`
(Only one task is allowed to modify the variable at a time)

    xSemaphoreTake(baton, portMAX_DELAY);
    i = i + 1;
    xSemaphoreGive(baton);

Additionally you should combine your `if` clauses. If both tasks increment `i`it could happen, that it will never has the value `1000`for the second task.


body: For multiple cores to provide any advantage, they must be able to work independently. If they require shared access to a resource - `i` in your experiment - only one core can actually be contributing to the job at any one time. But because there are multiple, they have the additional bookkeeping to negotiate access to the shared resource. Thus the total job takes longer than it would take one core with complete access to the resource and no overhead to manage access, to do the job by itself.


message:
Weird effect of AVR C on USB-serial communication

I recently decided to learn direct port manipulation instead of builtin arduino routines.

First I tried this piece of code

    void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    }
    void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println("on");
    delay(500);
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println("off");
    delay(500);
    }

This program on running instantly established connection with the serial monitor on my arduino IDE.

But when I try this code

    int main(void)
    {
    Serial.begin(9600);
    DDRB = B11111111;
    while(1)
    {
    PORTB = PORTB | 0x20;
    Serial.println("off");
    _delay_ms(500);
    PORTB = PORTB & 0xDF;
    Serial.println("on");
    _delay_ms(500);
    }
    }
But this program is taking some time, about 5-10 seconds to establish serial connection. Also delay() is not working too. When I use delay() instead of _delay_ms(), the entire arduino board freezes like a computer and stops blinking the LED instead LED is fully ON.

I tried is on several programs, while "setup-loop" program connects instantly, AVR C programs does not.

why does it happen?

body:
By defining your own `main()` you are circumventing the Arduino startup procedures.

Normally with Arduino code `main()` first runs an `init()` function before `setup()` and (repeatedly) `loop()`.  This `init()` function will configure, amongst other things, the timer for `millis()` and `delay()`.

This is the normal `main()` for a basic AVR-based board:

```
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}
```

It first initializes common functions, then board-specific ones (normally nothing), and if applicable, the USB interface (for ATMega32U4 based boards, like the Leonardo).

Only then does it go on to run your sketch.

If you want to use both your own `main()` and Arduino functions like `delay()` then you will have to call those initialization routines before running the rest of your code.


message:
Why are the Do While loops not stopping?

Ive been staring at this for a while now and I am going cross-eyed.  I am writing a simply program to change colors of a 3 color LED.  It is working, but then I noticed the LED would sometimes flash.  I did a variety of tests and eventually, using the serial monitor, found out the issue.  The brightness should count down to a brightness level of 0 and up to a level of 255.  However, *sometimes* it counts below 0 to -1 and *sometimes* it continues infinitely past 255.  I cant figure out why.  Below is the code and the serial monitor outputs.  The only way I can stop is by manually setting the value outside the loop.  You can see those lines commented out to allow for the error.

    int randLeg;  // var to pick a random leg

    // set all 3 legs to max brightness at start
    int legThreeBrightness = 255;
    int legFiveBrightness = 255;
    int legSixBrightness = 255;
    int delayTime = 15;
    int increment = 1;

    void setup() {

        Serial.begin(9600);

        // set pins as output
        pinMode(3, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(6, OUTPUT);

        // turn all the LEDs on
        analogWrite(3, legThreeBrightness);
        analogWrite(5, legFiveBrightness);
        analogWrite(6, legSixBrightness);

        randomSeed(analogRead(0));  // seed rand num generator

    }

    void loop() {

        randLeg = random(4, 7);  // pick a random leg

        switch (randLeg) {
        case 4:  //-1 for pin 3
            if (legThreeBrightness == 255){
              do {
                    Serial.println(legThreeBrightness);
                    analogWrite(3, legThreeBrightness);
                    delay(delayTime);
                    legThreeBrightness = legThreeBrightness - increment;
                 } while (legThreeBrightness >= 0);
                 //legThreeBrightness = 0;
            }
            else {
             do {
                    Serial.println(legThreeBrightness);
                    analogWrite(3, legThreeBrightness);
                    delay(delayTime);
                    legThreeBrightness = legThreeBrightness + increment;
                 } while (legThreeBrightness <= 255);
                 //legThreeBrightness = 255;
            }
          break;

        case 5:
            if (legFiveBrightness == 255){
              do {
                    ////Serial.println(legFiveBrightness);
                    analogWrite(5, legFiveBrightness);
                    delay(delayTime);
                    legFiveBrightness = legFiveBrightness - increment;
                 } while (legFiveBrightness >= 0);
                 //legFiveBrightness = 0;
            }
            else {
             do {
                    ////Serial.println(legFiveBrightness);
                    analogWrite(5, legFiveBrightness);
                    delay(delayTime);
                    legFiveBrightness = legFiveBrightness + increment;
                 } while (legFiveBrightness <= 255);
                 //legFiveBrightness = 255;
            }
          break;
        case 6:
            if (legSixBrightness == 255){
              do {
                    ////Serial.println(legSixBrightness);
                    analogWrite(6, legSixBrightness);
                    delay(delayTime);
                    legSixBrightness = legSixBrightness - increment;
                 } while (legSixBrightness >= 0);
                 //legSixBrightness = 0;
            }
            else {
             do {
                    ////Serial.println(legSixBrightness);
                    analogWrite(6, legSixBrightness);
                    delay(delayTime);
                    legSixBrightness = legSixBrightness + increment;
                 } while (legSixBrightness <= 255);
                 //legSixBrightness = 255;
            }
          break;
       }

    }

> 10 9 8 7 6 5 4 3 2 1 0 -1

and

> 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

body:
change `>=` and `<=` to `>` and `<` respectively.

You want it to stop at 0, but your do-while will do another round, since `0>=0` is true. So your code only stops at `-1` and `256`.

When `legThreeBrightness` is 256 it should be counting down, but your `if (legThreeBrightness == 255){` doesn't detect this, so the code will continue counting up. I'd probably change this line to `if (legThreeBrightness >= 255){` to prevent this from ever happening (which it shouldn't, but still).


body:
You have two issues related to bounds checking. For the sake of brevity, since all there LED branches of the switch statement are the same, I will refer to `legNumBrightness` instead of the individual `legThreeBrightness`, `legFiveBrightness`, `legSixBrightness` variables since this applies to all three (individually).

Because `do while` loops always run once before testing the condition, you have an issue with the value of `legNumBrightness` going out of bounds. i.e. when it is equal to 255, it decrements by one, until it is zero, and then because `0>=0` is still true (0 *is* equal to 0, after all), it decrements once more, so `legNumBrightness` is now `-1`. So on the next visit of that `legNumBrightness = 255`, the increments up by one branch is taken, until it reaches `255 <= 255`, which is again true, and hence will go to 256. As the if bounds test used is only that of `legNumBrightness == 255`, it will only decrement if the value is  exactly 255. Thus if it is not 255, it will keep incrementing until the maximum value of an `int` is reached (32767), overflow to -32768, and probably keep toggling between -32768 and 32767.

So to fix this, you need to change the `if (legNumBrightness == 255)` bound checking to
`if (legNumBrightness >= 255)`. Now, because of the `do while` loop, `legNumBrightness` will still sometimes go to `-1` and `256`, but can no longer overrun past 256. To fix the `-1` and `256` overrun, remove the `=` from the do while tests so they become `while (legNumBrightness > 0)` and `while (legNumBrightness < 255)` and thus will not try to increment or decrement when the boundary has been reached.

I would also recommend using a `while()` loop in preference to a `do while()` loop, so the condition is checked *before* running the loop content, but it does not appear necessary from brief testing of this logic.

e.g. for legThreeBrightness

```
 case 4:  //-1 for pin 3
        if (legThreeBrightness >= 255){
          do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness - increment;
             } while (legThreeBrightness > 0);
             //legThreeBrightness = 0;
        }
        else {
         do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness + increment;
             } while (legThreeBrightness < 255);
             //legThreeBrightness = 255;
        }
      break;
```


body:
I agree with @Gerben that you need to change `>=` and `<=` to `>` and `<` respectively, for the `do-while` loop check.

Secondly, your `if` statement expects `legThreeBrightness` (et al) to be 255 in order to decrement the brightness. Because of your `while` statement is over-running 255 because of  `<= 255`, the `if` statement will always execute the `else` part and because it is a `do-while` it will execute the loop once, incrementing `legThreeBrightness`.

To fix this, change the `if` statement to check for a value above 250:

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

    case 4:  //-1 for pin 3
        if (legThreeBrightness > 250){  // <---- Notice the > 250
          do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness - increment;
             } while (legThreeBrightness > 0);
             //legThreeBrightness = 0;
        }
        else {
         do {
                //Serial.println(legThreeBrightness);
                analogWrite(3, legThreeBrightness);
                delay(delayTime);
                legThreeBrightness = legThreeBrightness + increment;
             } while (legThreeBrightness < 255);
             //legThreeBrightness = 255;
        }
      break;

This is easy to check and you should see the problem disappear straight away.


message:
More effecient datalogging code

Background:
==============
I am using a Teensy 3.6 to data log over a dozen sensors. I am printing to Serial1 for local Serial access, Serial3 for remote access (via xbee, same data is on Serial1 as on Serail3, just different physical connection) as well as datalog to SDCard (CSV format). My code is expanding and is incredibly repetitive, and I am looking for a more efficient way of writing the following. I am trying to move a lot of the rest of my code to classes using [this][1] and [this][2] tutorial, but I'm not sure this is the best option for the datalogging as there are many more strings in this portion.

The variables we are dealing with:

 - Live sensor value (eOilTempF)
 - A visual flag for if the sensor is out of bounds (checkEngine)
 - A auditory alarm if it's further out of bounds (eOilTempAlarm)
 - The max value we've recorded (engineOilStats.maximum())
 - The minimum value (engineOilStats.minimum())

As well as all the little bits to make it attractive and human readable for the Serial stuff.

Code:
==============
Local serial:
-----------------

    Serial.print("Engine Oil Temp:\t");
    Serial.print(eOilTempF);
    Serial.print("F\t   ");
    Serial.print("Flag: ");
    Serial.print(checkEngine);
    Serial.print("\t Alarm:");
    Serial.print(eOilTempAlarm);
    Serial.print("\tMAX: ");
    Serial.print(engineOilStats.maximum());
    Serial.print(" F");
    Serial.print("\t\t\t\tAVG: ");
    Serial.print(engineOilStats.average());
    Serial.println(" F");

Xbee serial:
-----------------

    Serial3.print("Engine Oil Temp:\t");
    Serial3.print(eOilTempF);
    Serial3.print("F\t   ");
    Serial3.print("Flag: ");
    Serial3.print(checkEngine);
    Serial3.print("\t Alarm:");
    Serial3.print(eOilTempAlarm);
    Serial3.print("\tMAX: ");
    Serial3.print(engineOilStats.maximum());
    Serial3.print(" F");
    Serial3.print("\t\t\t\tAVG: ");
    Serial3.print(engineOilStats.average());
    Serial3.println(" F");

SD Card Logging:
-----------------

    logfile.print(eOilTempF);
    logfile.print(",");
    logfile.print(checkEngine);
    logfile.print(",");
    logfile.print(engineOilStats.maximum());
    logfile.print(",");
    logfile.print(engineOilStats.average());
    logfile.print(",");

tl;dr
==============
My datalogging section of my sketch is 567 lines of mostly repeated code, and I'm new at programming and need some tutorials/terms to google to make it more effecient.

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-classy-solution
  [2]: http://paulmurraycbr.github.io/ArduinoTheOOWay.html

body:
You can combine the [Streaming](https://github.com/janelia-arduino/Streaming) library with a wrapper class that sends data to multiple serial destinations.

Here's a little example:

```
#include <Streaming.h>

class DualSerial : public Print {
    private:
        Print *_dev1;
        Print *_dev2;

    public:
        DualSerial(Print &s1, Print &s2) : _dev1(&s1), _dev2(&s2) {}

        size_t write(uint8_t c) {
            _dev1->write(c);
            _dev2->write(c);
        }
};

DualSerial remote(Serial, Serial3);

void setup() {
    Serial.begin(115200);
    Serial3.begin(115200);
}

void loop() {
    // Both Serial and Serial3 will receive this
    remote << "The time is: " << millis() << endl;
    delay(1000);
}
```

The Streaming class will work with anything that inherits from the `Print` class, which includes the SD card's `File` class, so you can also use it for writing to the SD card:

```
logfile << eOilTempF << ","
        << checkEngine << ","
        << engineOilStats.maximum() << ","
        << engineOilStats.average() << endl;
```


message:
digitalwrite with function parameter as parameter

Firstly, excuse my poor English, this is not my native langage.

I'm trying to use an Arduino Uno to drive an 8 relay board from an MQTT Subscription. I ask for help because i'm some kind of beginner in arduino, i'm just a Linux addict.

The idea is to get a payload from PubSubclient and use it to manage relays.
For example, the payload '71' ask the relay 7 to turn on and '42' make the relay 4 to turn off.

All works fine until I wanted to write a function with two parameters : 'relay_number' and 'Action'

All parameters are received but the relay never goes up or down.

My code :

```
void callback(char* topic, byte* payload, unsigned int length) {

  Relay_Nb = (char)payload[0];
  Action = char(payload[1]);

  Serial.println(Relay_Nb);
  Serial.println(Action);

  RelayControl(Relay_Nb, Action);
}

void RelayControl(char Relay_Nb, char Action) {
  Serial.println(Relay_Nb);   // for debugging purpose
  Serial.println(Action);

  if ( Action == '0') {
    Serial.print("Bringing down Relay ");
    Serial.println(Relay_Nb);
    digitalWrite(Relay_Nb, LOW);
  } else if (Action == '1') {
    Serial.print("Bringing up Relay ");
    Serial.println(Relay_Nb);
    digitalWrite(Relay_Nb, HIGH);
  } else if (Action == '2') {
    // Relay temporisé (ouverture portail par ex)
    Serial.println("Bringing up, and down Relay ");
    digitalWrite(Relay_Nb, HIGH);
    delay(750);
    digitalWrite(Relay_Nb, LOW);
  }
}
```

I'm sure an old maker have the solution i'm searching for hours now.

Please help and don't hesitate to show me others ways.
Thanks.

body:
You are sending the parameter `Relay_Nb` as a character, and then using it as an integer.

You need to turn the character into an integer - and the simplest way is to subtract the ASCII value of `0` from it:

    Relay_Nb = payload[0] - '0';

But with that said, a note on how you have written your callback:

* You aren't checking the data is valid.

You should really be doing, at the very least, the following:

1. Check that the `length` parameter is at least `2`,
2. Check that the two data values are within the correct range for your function


message:
ESPTool 3-run stub fail error

I'm trying to program my NodeMCU ESP8266 ESP-12E module with AT commands. However, whenever I try and flash to my ESP8266 using ESPTool, I get a 3-run stub fail error. Can anyone tell me why I get this error and how to fix it?
I have my suspicions that it might be the fact that I haven't pulled any of the pins, but I've been told that GPIO0, GPIO2, GPIO15, and CH_PD are all already pulled to the proper positions by default. If that may be the reason behind this error, could someone explain to me how exactly I should pull the pins, whether it be with a circuit or through code?
If it helps, I'm trying to follow along with [this resource.][1]
The only thing the ESP is connected to is the computer with USB.

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

  [1]: https://www.instructables.com/id/Program-Any-ESP8266-Boardmodule-With-AT-Commands-F/
  [2]: https://i.stack.imgur.com/xcUiU.png
  [3]: https://i.stack.imgur.com/5l5yt.png

body:
Just wanted to update and let anyone who had a similar issue learn how I solved the problem.
My baud rate was set to 1152000 rather than 115200. Setting it to 115200 solved my problem.


message:
Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board?

I have just started my first project on Arduino. I have an Arduino Uno and an L293D motor shield.

I have installed the motor shield on the Arduino Uno board and the motor shield covers all pins of the Arduino Uno board. The motor shield is connected with four gear motors and one servo motor.

Can I use digital pins 2-13 to make some LED flashing circuit?

Which digital pins are used by the Motor shield and which pins are not used?

---

It is L293D motor shield. A0 and A5 are used in the code. Four DC motors and one servo motor is used.

body:
If this is the same board as seen on [Banggood][1] Which may also be seen at [Adafruit][2]
The schematic shows most of the digital pins in use

    D3  - PWM2B
    D4  - DIR_CLK
    D5  - PWM0B
    D6  - PWM0A
    D7  - DIR_EN
    D8  - DIR_SER
    D9  - PWM1A
    D10 - PWM1B
    D11 - PWM2A
    D12 - DIR_LATCH

The analogue pins A0-A5 are still free - these can be used as digital pins.

  [1]: https://uk.banggood.com/Motor-Driver-Shield-L293D-Duemilanove-Mega-U-NO-p-72855.html
  [2]: https://learn.adafruit.com/adafruit-motor-shield


message:
wdt reset cause:4, boot mode:(3,6)

I'm working on Python and nodeMCU with websocket connection.

So, I send a string from Python to nodeMCU and nodeMCU collects the string and decodes to set values to a stepper motor. Initial code worked fine before updating with stepper motor code. Now it triggers watchdog resets.

Here's my full code:-

```
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AccelStepper.h>

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 8  // clk+
#define stepPin 9  // cw+
#define motorInterfaceType 1

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

const char ssid[] PROGMEM ="PencoNetwork2";    //change it to your wifi SSID
const char password[] PROGMEM ="Penco1234567890";    //change it to your wifi password

AsyncWebServer server(80);
AsyncWebSocket ws("/test");

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println(WiFi.localIP());

  ws.onEvent(onWsEvent);
  server.addHandler(&ws);

  server.begin();

}

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){

    Serial.println("Data received: ");

    for(int i=0; i < len; i++) {
//          Serial.print((char) data[i]);
           String data_String = (String) data[i];

          int commaIndex = data_String.indexOf(',');
          int secondCommaIndex = data_String.indexOf(',', commaIndex+1);
          String firstValue = data_String.substring(0, commaIndex);
          String secondValue = data_String.substring(commaIndex+1, secondCommaIndex);
          String thirdValue = data_String.substring(secondCommaIndex+1); //To the end of the string

          int mDist = firstValue.toInt();
          int mspeed = secondValue.toInt();
          int mAccel = thirdValue.toInt();

          stepper.setMaxSpeed(mspeed);
          stepper.setAcceleration(mAccel);

          stepper.moveTo(mDist);
          stepper.runToPosition();
          delay(1000);
          stepper.moveTo(0);
          stepper.runToPosition();
          delay(1000);

    }

//    Serial.println();
  }
}

void loop(){

  }

 ```

It would be a great help pointing out my mistakes.

body:
You're calling `delay()` in the `onWsEvent()` callback. The [ESPAsyncWebServer][1] documentation specifically says not to do that in the '**Important things to remember'** section:

> You can not use yield or delay or any function that uses them inside the callbacks

When you call `delay()` or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.

The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in `loop()`.

For instance,
```
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){
```

and

```
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){
    flag_move_stepper = true;

    // you'll need to rewrite this code to share variables with `loop()` and do the work there
```

and

```
void loop(){
  if(flag_move_stepper) {
    flag_move_stepper = false;

    // do the work formerly in onWsEvent() here
  }

}
```

You'll need to make the variables you stored data in in the event handler available to `loop()` and move the stepper code there for this to work.

  [1]: https://github.com/me-no-dev/ESPAsyncWebServer


message:
Detecting an incoming 7.875 kHz pulse to use as trigger

I have written a code that detects an incoming pulse (square) of 7.875 kHz to trigger the output High for the entire duration of pulse, and trigger the output low if the pulse is off or not detected.

**CODE**

    // Define pins
    volatile int pulse1 = 2;    //incoming pulse 1 on pin 2

    const int ledPin = 13;   //output to trigger LED

    void setup() {

      pinMode(pulse1, INPUT);

      pinMode(ledPin, OUTPUT);

      // Timer Setup

      TCCR1A = 0;               // set entire TCCR1A register to 0
      TCCR1B = 0;               // same for TCCR1B
      TCNT1  = 65282;           // initialize counter value
      TCCR1B |= (1<<CS10);      // set prescaler to 8 bit
      TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

    }
    ISR(TIMER1_OVF_Vect){
      TCNT1 = 65282;
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV2, FALLING);
      }

    void loop() {
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, RISING);

    }

    // Interrupt routines

    void ISR_UV1(){
      digitalWrite(ledPin, HIGH);      // Send high signal
    }

    void ISR_UV2(){
      digitalWrite(ledPin, LOW);      // Send low signal
    }

Is it the correct approach, or am I doing it wrong. One last thing that is bothering me is, every time I connect a wire (not connected to anything) to the input pin 2, it sends a high signal, and keeps the signal high until the Arduino is reset.
The pulse is a square wave 50% duty cycle generated by a device. I dont need to measure it or count it. I am just using it as a trigger to send a HIGH signal when it occurs. So it stays on (occurs) for 25ms & turns off during which its freq. is 7.875MHz & then it is repeated by the device according to the device parameters. I am aware it is a very short pulse but for the purpose of project nothing else can be used as the trigger

Any help will be appreciated.

body:
I don't think, that your current approach will work. The logic seems flawed to me (though I cannot know, how exactly this code is embedded in your actual code) and the frequency is that high, that it will be difficult for the microcontroller to do much between the different interrupt triggers.

I would suggest 2 different approaches, based on the actual needs:

1. You can build a demodulator, which just gives you a high value, when your signal is there, and a low one, if it is not. Here you would need extra components.

2. You could feed the signal into one of the timers as clock source. Then the timer counts the pulses (actually twice the pulses, since the timer increments on every edge, rising or falling). You can use the overflow interrupt to get the value out of it. Lets say you use Timer 1 for the signal and still have Timer 0 for doing the Arduino time stuff (`delay()`, `millis()`, `micros()`). Then you can write an ISR for the Timer1 overflow interrupt. In there you take the current time and subtract the time of the last interrupt. Then you get the time, that it took the timer to overflow. Since you know, how many pulses are needed to overflow the timer, you now know the average frequency. If it is in the needed range, you set a simple single byte flag variable (be sure to declare it as `volatile`). You can tune the time for the average for example with the prescaler.

    In your main code you can then check for the flag being set and do stuff accordingly. Reset the flag, if you have done stuff, and save a timestamp. Check in your main code, if a specific time has passed since your last timestamp. If yes, that means, that the signal is lost. There you can act accordingly


body:
So i figured out what the problem was, I had to detach interrupts in the interrupt routines not in my main code. So basically these changes:

    void loop() {
      digitalWrite(ledPin, LOW);
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, CHANGING);

    }

& in the Interrupt routines:

    digitalWrite(ledPin, HIGH);      // Send high or Low dpending on the routine
    detachInterrupt(digitalPinToInterrupt(pulse1));

& basically this works like a charm, & there are still issues with the timer, but that will be solved in my main code with another sensor.


message:
Arduino ESP8266 GPS integration issue

I am facing issue in using 2 Serial communication device with Arduino uno. I am trying to use ESP8266, Neo 6M GPS module with Arduino UNO, but only one of device is working at a time. Is there any solution available to make this work? When I comment processGPS() and uncomment TCP related API and vice-versa then either of the device working. Any idea how we can make work both?

My code:

    // This is a demo example using a public http server for testing both GET and POST requests

    #include <Arduino.h>
    #include <LiteESP8266Client.h>
    #include "TinyGPS++.h"
    #include "SoftwareSerial.h"

    #define PACKET_MTU 500    // Standard network MTU is 500 bytes

    LiteESP8266 radio;

    const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
    const char password[] PROGMEM = "xyz";    //change it to your wifi password
    const char host[] PROGMEM = "192.168.0.156";
    const int port = 8080;

    const char http_get_request[] PROGMEM = "GET /getLedStatus HTTP/1.1\r\n";
    const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
    const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
    const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
    const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
    const char http_content_length_header[] PROGMEM = "Content-Length: ";
    const char success[] PROGMEM = "success";
    const char failed[] PROGMEM = "failed";
    const char CRLF[] PROGMEM = "\r\n";
    const char error_data_null[] PROGMEM = "Error: data came back null.";
    const int ledPin=11;
    // Choose two Arduino pins to use for software serial
    int RXPin = 5;
    int TXPin = 4;

    int GPSBaud = 9600;

    // Create a TinyGPS++ object
    TinyGPSPlus gps;

    // Create a software serial port called "gpsSerial"
    SoftwareSerial gpsSerial(RXPin, TXPin);

    void setupStationMode() {
      Serial.print(F("Setup station mode... "));
      if (radio.set_station_mode()) {
        Serial.println(F("success"));
      } else {
        Serial.println(F("failed"));
      }
    }

    void joinAP() {
      Serial.print(F("Join AP "));
      Serial.print(F("... "));
      if (radio.connect_to_ap(ssid, password)) {
        Serial.println(F("Success"));
      } else {
        Serial.println(F("Failed"));
      }
    }

    boolean establishTcpConnect() {
      Serial.print(F("Establish TCP Connection... "));
      if (radio.connect_progmem(host, port)) {
        Serial.println(F("Success"));
        return true;
      } else {
        Serial.println(F("Failed"));
        return false;
      }
    }

    void readHttpPacketAndProcessLEDStatus() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println(F("Response Received..."));
          Serial.println(data);
          if(strstr(data, "ON") != NULL) {
            digitalWrite(ledPin, HIGH);
          }else{
            digitalWrite(ledPin, LOW);
          }
          free(data);//Mandatory
        } else {
          Serial.println(error_data_null);
        }
      }
    }

    void httpGetLedStatus() {
      Serial.println(F("Sending GET request... "));
      radio.send_progmem(http_get_request);
      radio.send_progmem(http_useragent);
      radio.send_progmem(http_host);
      radio.send_progmem(http_close_connection);
    }
    void setupGPS(){
      // Start the software serial port at the GPS's default baud
      gpsSerial.begin(GPSBaud);
      Serial.println("GPS Start");//Just show to the monitor that the sketch has started
    }
    void setup() {
      delay(2000);
      pinMode(ledPin, OUTPUT);
      radio.begin(9600,2,3);
      Serial.begin(9600);
      while (!Serial) {};
      //setupStationMode();
      //joinAP();
      setupGPS();
    }
    void displayInfo()
    {
      if (gps.location.isValid())
      {
        Serial.print("Latitude: ");
        Serial.println(gps.location.lat(), 6);
        Serial.print("Longitude: ");
        Serial.println(gps.location.lng(), 6);
        Serial.print("Altitude: ");
        Serial.println(gps.altitude.meters());
        Serial.println("Speed MPH:");
        Serial.println(gps.speed.mph());
      }
      else
      {
        Serial.println("Location: Not Available");
      }

      Serial.print("Date: ");
      if (gps.date.isValid())
      {
        Serial.print(gps.date.month());
        Serial.print("/");
        Serial.print(gps.date.day());
        Serial.print("/");
        Serial.println(gps.date.year());
      }
      else
      {
        Serial.println("Not Available");
      }

      Serial.print("Time: ");
      if (gps.time.isValid())
      {
        if (gps.time.hour() < 10) Serial.print(F("0"));
        Serial.print(gps.time.hour());
        Serial.print(":");
        if (gps.time.minute() < 10) Serial.print(F("0"));
        Serial.print(gps.time.minute());
        Serial.print(":");
        if (gps.time.second() < 10) Serial.print(F("0"));
        Serial.print(gps.time.second());
        Serial.print(".");
        if (gps.time.centisecond() < 10) Serial.print(F("0"));
        Serial.println(gps.time.centisecond());
      }
      else
      {
        Serial.println("Not Available");
      }

      Serial.println();
      Serial.println();
      delay(1000);
    }
    void processGps(){
       // This sketch displays information every time a new sentence is correctly encoded.
      if (gpsSerial.available() > 0)
        if (gps.encode(gpsSerial.read()))
          displayInfo();
    }
    void loop() {
      /*if(establishTcpConnect()){
        httpGetLedStatus();
        readHttpPacketAndProcessLEDStatus();
      }*/
      processGps();
      }

body:
As mentioned by StarCat and romkey, SoftwareSerial only allows one connection at a time.

There are two potential solutions to this in my opinion, but each requires some new hardware.

### Solution 1 - Replace Arduino Uno with an STM32 Blue Pill
STM32 Blue Pill has more than one hardware serial interfaces, so that you don't even need the SoftwareSerial, in fact, the `LiteESP8266Client.h` will auto detect if a STM32 is used or an AVR-based Arduino is used to decide whether to use `HardwareSerial` or `SoftwareSerial`, see [here](https://github.com/e-tinkers/LiteESP8266Client/blob/master/src/LiteESP8266Client.h#L30-L49).

Pros:
- Minimum code change. You be able to use what you have written so far and continue to use ESP-01 as a WiFi-shield;

Cons:
- A little bit extra works to setup STM32duino Core for Arduino and requires either a SWDI programmer or USB-serial programmer.

Read [this](https://www.e-tinkers.com/2020/01/getting-started-with-stm32-and-things-you-need-to-be-aware-of/) for getting started with STM32 and the things need to be aware of.

### Solution 2 - Replace both Arduino Uno and ESP-01 with an ESP8266 Dev Board
Instead of using an ESP-01 as a WiFi shield,  get an ESP12-based development board as an Arduino to replace both the Arduino Uno and ESP-01. In this case, you run Arduino sketch directly on the board and replace the AT firmware with Arduino bootloader.

Pros:
- Integrated Arduino Uno with ESP wireless functionality into one hardware.

Cons:
- Need complete re-write of your application.

[ESP8266 Arduino github](https://github.com/esp8266/Arduino) should have sufficient information for getting started.


message:
Continuous push button detection in for Stepper control

Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards.
but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW,  That means it cannot detect the press of another pushbutton to make it counterclockwise.

I realize that the program isn't detecting the second push button after pressing 1st one.
Tried different options to make it work. but failed.

any suggestions?

Here's my code for reference:-

```

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}
```

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.

it would be a great help pointing out my mistakes.

body:
I implemented your code here on a UNO using 2 pushbuttons (with the stepper motor functions commented out) and it seems to work fine.  When I press button1 I get a lot of "ok" printouts for as long as the button is held down. When I press button2, the same thing happens except with "ok2" instead of "ok".

Here's the code I used:

    /*
        Name:       TwoPushButtonTest.ino
        Created: 9/28/2020 2:36:07 PM
        Author:     FRANKNEWXPS15\Frank
    */

    //#include <AccelStepper.h>

    const int button1Pin = A2;
    const int button2Pin = A1;

    int button1State = 0;
    int button2State = 0;

    boolean flag1 = 0;
    boolean flag2 = 0;

    //AccelStepper stepper = AccelStepper(1, 8, 9);
    void setup()
    {
      pinMode(button1Pin, INPUT);
      pinMode(button2Pin, INPUT);

      Serial.begin(115200);
    }

    void loop()
    {

      //int sensorReading = analogRead(A0);
      //int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

      //stepper.setMaxSpeed(2000);
      //stepper.setSpeed(motorSpeed);

      if (button1State == HIGH)
      {

        Serial.print("ok");
        //stepper.setSpeed(motorSpeed);
        //stepper.runSpeed();

      }

      if (button2State == HIGH)
      {

        Serial.print("ok2");
        //stepper.setSpeed(-motorSpeed);
        //stepper.runSpeed();

      }
    }

and here's the wiring diagram:

[![enter image description here][1]][1]

Note the two 10K pull-down resistors.  If these are not present, then the A2/A3 inputs are indeterminate whenever the buttons are in the 'disconnected' state, and anything can happen.

  [1]: https://i.stack.imgur.com/Re4F8.jpg


message:
Is Arduino Mega Hackable Over The Air

After reviewing similar topics I've decided to ask this question below in the Security Stackexchange forum about 11 days ago.
https://security.stackexchange.com/questions/235423/is-arduino-mega-hackable-over-the-air

*No one gave an answer yet, perhaps I was wrong about the medium that's why I am also posting the question here.*

I am collecting data (by reading input registers) from a machine by RS-485 protocol and Arduino Mega 2560 hardware.

I am also sending this data from Arduino Mega to a NodeMCU which is connected to the internet over WiFi.

I made 100% sure that no physical interference can be performed on the hardware I setup.

But since this machine, I collect data from is controllable (by writing holding registers) over RS-485 (I've tested it) I have to make sure that Arduino's software cannot be changed/re-programmed/flashed over the air by someone.

There is no other device than NodeMCU which is open to the Internet and can be the source of vulnerability. And the only physical connections between Arduino & NodeMCU ar TX3+RX3 pins and power+ground pins.

I do not really care if the data or WiFi password or cloud server credentials are stolen. The only thing I care about is that Arduino is not flashed over the air which can ultimately damage the machine I am taking data from. Do you think this setup is safe regarding the information I present to you?

body:
1. the bootloader doens't listen on RX/TX3.
2. to start the bootloader reset is required
3. to communicate with the bootloader a serial programmer must have STK500 protocol or a telnet bridge for avrdude, which your NodeMCU sketch doesn't have

If your NodeMCU sketch has OTA, then the sketch could be updated to an avrdude telnet bridge. then reset would be needed to activate the bootloader. If your NodeMCU doesn't have a wire to Mega reset pin or you don't have a command in your Mega sketch to activate the reset, some serial overload of your Mega sketch could be a way.

But all this doesn't have an effect because the bootloader only listens at RX0


message:
Is extra hardware and components needed to connect the bare MCU directly to a PCB, without a shield?

As a hobbyist I code in a variety of arduino's and in Digispark's (Attiny 85 and 167).

But I'm doing a project with space contraints, so I'd need to use just the MCU directly over my pcb.

Apart from a voltage regulator (to get the VIn to 5V or 3.3V) do I need extra components to mount the MCU to my PCB?

DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

I'll program the MCU before soldering on to the PCB, so there's no need for USB or programming stuff or leds.

Thanks!

body:
> DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

You don't need a crystal if you use the internal clock of the MCU (which means setting the fuses right and compiling your code to expect the right clock frequency). However if you are using a direct USB interface (such as for the ATMega32U4) then you will need a crystal as the precise timing is required for USB to operate.

You will need capacitors. Decoupling capacitors on all the power pins are not optional and must be included.

You will need a pullup resistor on the RESET pin unless you have set the fuse to disable the RESET pin (not advisable since it will prevent ICSP programming in the future - but can be useful for low pin-count chips).


message:
DS2413 One Wire IC read and store the addresses of individual IC's

Hy,
Here I using 10 DS2413 to control gpios, it works very well with arduino ,I read the 10 ic address and store it in a 2D array, I want to control the individual IC using their address .Here all works well. My problem is the Ic address are not store in arrange wise manner. For ex, I have 10 IC's, Each IC's have unique address, The address of first IC1 is store in arr1, address of ic2 is arr2 and address of ic3 is store in arr3..... what i need is If i Swap the IC1 and IC2 the address of IC2 is store in arr1 and IC1 address is store in arr2.

body:
The OneWire system has no concept of the arrangement of the bus. All it knows is the addresses, and it always searches for those addresses in a pre-defined order.

No matter what arrangement you have on the bus the devices will always be found in the same order.

You can think of it akin to a teacher taking the register in class. They call out the names in alphabetical order and the pupils answer (if they are there). All it tells the teacher is who is there and who isn't. It doesn't give them any information about where in the class the pupil is sat.

You can read more about how the address searching is done [here](https://www.maximintegrated.com/en/design/technical-documents/app-notes/1/187.html).