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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

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

Answers: 1

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


body:
So I want to have one persistent SSL connection to a cloud server (Azure IoT Hub) to upload telemetry and another SSL connection to a server to perform a simple GET request every 30 minutes.

I've setup my first connection and telemetry is successfully sent, then I connect to the second server, I get a response, close the connection, but my first connection to Azure IoT Hub crashes.

I haven't found any information online on how many simultaneous SSL connections the Arduino Uno WiFi Rev. 2 supports nor any guidance on how to use more than 1 SSL connections. Any help would be greatly appreciated.

title: Two SSL connections at the same time on Uno WiFi rev 2

Answers: 0


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

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

Answers: 1

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


body:
i have one ESP32-POE and ESP32-POE and i'm using the Olimex RS485 module to read a power meter that is placed near the ESP32 (5 meters of CAT5 cable - 9600 8N1).

My device has this workflow (it's powered via PoE using a Cisco 2960x switch):

 - Boot and acquire a DHCP address
 - Connect to the server and check if there is a new ota package to download
 - Read via modbus (Using ModbusMaster library) the power meter
 - Prepare the data in JSON format using ArduinoJson library and send it to the broker using PubSubClient
 - Wait for five minutes using Millis and start over with the loop

This is the main logic that "blocks" the loop and wait for some minutes:

    void loop() {
      wdt_reset();
      MQTT_connect();

      client_subscriber_loop(); // loop subscriber mqtt

      unsigned long currentMillis = millis();
      if (currentMillis - previousMillisTaskDataPublisher > MQTT_PUBLISH_EVERY) {
        if (DEBUG == 1)
          Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());
        //  OTA Check
        trueverit_ota_check_update();
        wdt_reset();

        publish_data();
        if (DEBUG == 1)
          Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());

        previousMillisTaskDataPublisher = currentMillis;
      }
    }

As you can see, i've also have Watchdog timer enabled and it is feeded in the loop or function that have to feed it (Modbus read, etc...)

Now, here comes the issues, this works exactly for 10 days and after that the MCU goes in loop, the LAN green led will flash indefinitely and nothing work, leaving the ESP32 in a undefined state.

This is the debug message that i see on arduino console:

[![Arduino console][1]][1]

***There is no way to make it work a part of power off and power on the device.***

This is extremely uncomfortable...in my case i have 25 of those devices placed far away from my office (600km) and i can't go every time to reboot them every ten days.

Maybe is hardware related issue? a software issue on ModbusMaster library?

Any toughts?

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

title: ESP32-POE/ISO unstable after 10 days of power up

Answers: 0


body:
My Question is How to easily invoke Simple REST Service trigerred using **Arduino UNO + ESP8266 WIFI Shield** programmed with AT command? I am new to this Subject and gone through many tutorial over internet but so far I could not making this working as per my requirement

**My Requirement:** Invoke a simple Get request originated from Arduino Uno and via ESP8266 WIFI Shield to submit to server and process the response.

**What all I have done so far:**
1. Used below Blynk example to Submit Up time to the Server and View in Mobile**This is Working which means hardware setup at my side should be ok**, but I dont want to Submit request to Blynk Server and I want to Submit request to my REST server and first of all I want to do a simple GET request may be to any already working API for ex: http://jsonplaceholder.typicode.com/posts/1

       #define BLYNK_PRINT Serial
        #include <ESP8266_Lib.h>
        #include <BlynkSimpleShieldEsp8266.h>

        // You should get Auth Token in the Blynk App.
        // Go to the Project Settings (nut icon).
        char auth[] = "xyz";

        // Your WiFi credentials.
        // Set password to "" for open networks.
        char ssid[] = "xyz";
        char pass[] = "xyz";

        // Hardware Serial on Mega, Leonardo, Micro...
        //#define EspSerial Serial1

        // or Software Serial on Uno, Nano...
        #include <SoftwareSerial.h>
        SoftwareSerial EspSerial(2, 3); // RX, TX

        // Your ESP8266 baud rate:
        #define ESP8266_BAUD 115200

        ESP8266 wifi(&EspSerial);

        BlynkTimer timer;

        void myTimerEvent()
        {
          // You can send any value at any time.
          // Please don't send more that 10 values per second.
          Blynk.virtualWrite(V5, millis() / 1000);
        }

        void setup()
        {
          // Debug console
          Serial.begin(115200);

          // Set ESP8266 baud rate
          EspSerial.begin(ESP8266_BAUD);
          delay(10);

          Blynk.begin(auth, wifi, ssid, pass);
          // You can also specify server:
          //Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 80);
          //Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8080);

          // Setup a function to be called every second
          timer.setInterval(1000L, myTimerEvent);
        }

        void loop()
        {
          Blynk.run();
          timer.run(); // Initiates BlynkTimer
        }

 Output :

      ___  __          __
       / _ )/ /_ _____  / /__
      / _  / / // / _ \/  '_/
     /____/_/\_, /_//_/_/\_\
            /___/ v0.6.1 on Arduino Uno

    [517] Connecting to xyz
    [13550] AT version:1.1.0.0(May 11 2016 18:09:56)
    SDK version:1.5.4(baaea 1
    [23591] Failed to connect WiFi
    [31752] Ready (ping: 11ms).
    [70474] Ready (ping: 12ms).
    [86528] Ready (ping: 13ms).
Though I get Failed to connect to wifi but probably it retries and works there after as I can see timer in Mobile APP which is progressing.

2. Invoke HTTP request using AT Command, but I am getting output as ">" which I am not able to get as why the output is like this:

    ````//
    #include <SoftwareSerial.h>

    SoftwareSerial ESP8266(2, 3);

    String Network = "xyz";
    String Password = "xyz";

    void setup()
    {

      Serial.begin(9600);

      ESP8266.begin(115200);
      ESP8266.println("AT+CIOBAUD=9600");
      readESP8266(4000);

      ESP8266.begin(9600);
      InitESP8266();
      ConnectToWebsite();
    }

    void loop()
    {
       while(ESP8266.available())
       {
         Serial.println(ESP8266.readString());
       }

    }

    /* Function to initialise ESP8266 */
    void InitESP8266()
    {

      ESP8266.println("AT");
      readESP8266(2000);

      ESP8266.println("AT+CWMODE=3"); //Wifi mode
      readESP8266(5000);

      ESP8266.println("AT+CWJAP=\""+ Network + "\",\"" + Password +"\""); //connect wifi
      readESP8266(10000);

      ESP8266.println("AT+CIFSR"); // IP adress
      readESP8266(1000);

      ESP8266.println("AT+CIPMUX=1");  // multiple connections
      readESP8266(1000);

    }

    /* Function to connect to the server */
    void ConnectToWebsite()
    {

      ESP8266.println("AT+CIPSTART=1,\"TCP\",\"jsonplaceholder.typicode.com\",80"); //connect to website
      readESP8266(10000);

      ESP8266.println("AT+CIPSEND=1,114");
      readESP8266(2000);

      String httpreq = "GET /posts/1 HTTP/1.1";
      // Make a HTTP request:
      ESP8266.println(httpreq);
      readESP8266(10000);

      readESP8266(5000);

      //Serial.println("\r\n");
    }

    //read and display message
    void readESP8266(const int timeout)
    {
      String reponse = "";
      long int time = millis();
      while( (time+timeout) > millis())
      {
        while(ESP8266.available())
        {
          char c = ESP8266.read();
          reponse+=c;
        }
      }
      Serial.print(reponse);
    }````

Output:

    OK

    OK
    WIFI DISCONNECT
    WIFI CONNECTED
    WIFI GOT IP

    OK
    +CIFSR:APIP,"192.168.4.1"
    +CIFSR:APMAC,"abcd"
    +CIFSR:STAIP,"192.168.0.169"
    +CIFSR:STAMAC,"abcd"

    OK

    OK
    1,CONNECT

    OK

    OK
    > 1,CLOSED

3. If I use WIFI ESP then I am getting following error

    ````#include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2, 3); // RX, TX
    #endif

    char ssid[] = "xyz";            // your network SSID (name)
    char pass[] = "xyz";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "arduino.cc";

    // Initialize the Ethernet client object
    WiFiEspClient client;

    void setup()
    {
      // initialize serial for debugging
      Serial.begin(115200);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        //while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      // you're connected now, so print out the data
      Serial.println("You're connected to the network");

      printWifiStatus();

      Serial.println();
      Serial.println("Starting connection to server...");
      // if you get a connection, report back via serial
      if (client.connect(server, 80)) {
        Serial.println("Connected to server");
        // Make a HTTP request
        client.println("GET /asciilogo.txt HTTP/1.1");
        client.println("Host: arduino.cc");
        client.println("Connection: close");
        client.println();
      }
    }

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if the server's disconnected, stop the client
      if (!client.connected()) {
        Serial.println();
        Serial.println("Disconnecting from server...");
        client.stop();

        // do nothing forevermore
        while (true);
      }
    }

    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength
      long rssi = WiFi.RSSI();
      Serial.print("Signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }````

Output:

    ````[WiFiEsp] I >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] Initializing ESP module
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] Cannot initialize ESP module
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] No tag found
    WiFi shield not present
    Attempting to connect to WPA SSID: xyz
    [WiFiEsp] >>> TIMEOUT >>>
````
Please let me know in case you figure out the issue.

title: How to easily invoke Simple REST Service trigerred using Arduino UNO + ESP8266 WIFI Shield programmed with AT command?

Answers: 0


body:
    static const int dry = 570;
    static const int wet = 225;
    static const int RELAY = 2;
    static const unsigned long DELAY_1_S      = 1000;
    static const unsigned long DELAY_1_MINUTE = DELAY_1_S * 60;
    static const unsigned long DELAY_1_HOUR   = DELAY_1_MINUTE * 60;
    static boolean watering = false;

    void setup() {
      Serial.begin(9600);
      pinMode(RELAY, OUTPUT);
    }

    void loop() {
      int sensorVal = analogRead(A0);
      int percentageHumidity = map(sensorVal, wet, dry, 100, 0);
      Serial.print(percentageHumidity);
      Serial.println("%");
      if (!watering && percentageHumidity < 60){
        watering = true;
        Serial.println("Watering!!!");
        digitalWrite(RELAY, HIGH);
        delay(3*DELAY_1_S);
        digitalWrite(RELAY, LOW);
        watering = false;
      }
      Serial.println(DELAY_1_S * 10);
      delay(10*DELAY_1_S);
    }

I have an analog reading at A0 from a capacitance water sensor. If the sensors read a value of 60% or less humidity it will activate a water pump. The water pump is connected through a 5v relay and the water pump has its independent power supply. For some reason, the code works when connected to the USB as intended, but when I power it with the battery it connects always the water pump.

title: Code is not looping correctly when running on battery

Answers: 0


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

title: Unable to read Arduino+ESP8266 full get Response

Answers: 1

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.


body:
So recently, I purchased an Arduino Mega 2560 Kit from Amazon, which was customized from this company called Adeept. But when I tried to plug it into my computer, it didn't recognize it. This means my device manager didn't change in any way, shape, or form. The Arduino IDE that I fully downloaded couldn't upload code, and I also tried using different USB cords, and I tried using another computer as well, but it still didn't work.

**Is there a driver that I need to upload or something else that I'm missing?**

Thank you for your time :)

title: Adeept Arduino Mega 2560 isn't recognized

Answers: 0


body:
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);
    }

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

Answers: 3

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);
    }
  }
```


body:
I'm trying to create an even log saved on flash.
I try to make it a class, called `flashLOG` as shown. Code behaves as expceted, reads, writes and  posts it size and entries.

The problem is that after reboot - it seems that the file "disappears".

Code is written based on the Arduino IDE example. First I thought it is a flash problem, but after flashing Arduino's example and tried to run my code on an other MCU - it seems there no physical problem with flash.

I tried to reduce most of my code only to write "events" in order to see what survives reboot - so please ignore commented out lines and some logic in reading text, in code attached.

The only thing came in mind-  perhaps it  has something to do with being in a class or inside a library.

Appreciate any help finding this bug
 **EDIT 1: ** Update .h file and .ino fil

`.h` file

    class flashLOG {
    private:
        char *_logfilename = "/logfile.txt";
        const static int _logsize = 5;     // entries
        const static int _log_length = 20; // chars in each entry
        char _log_array[_logsize][_log_length];
    public:
        flashLOG(char *filename = "/logfile.txt");
        void start();
        void read();
        void write(const char *message);
        void append(const char *message);
        void postlog(int x);
        int sizelog();
    };

`.cpp` file:

    flashLOG::flashLOG(char *filename)
    {
        _logfilename = filename;
    }
    void flashLOG::start() {
        if (!LittleFS.begin())
        {
            Serial.println("LittleFS mount failed");
        }
        else {
            Serial.println("MOUNTED OK");
        }
    }
    void flashLOG::read() {
        int r = 0;
        int c = 0;

        File file = LittleFS.open(_logfilename, "r");
        if (!file)
        {
            Serial.println("Failed to open file for reading");
        }
        else {
            while (file.available())
            {
                char tt = file.read();
                //     if (tt != '\n')
                //     {
                //         _log_array[r][c] = tt;
                //         c++;
                //     }
                //     else
                //     {
                //         _log_array[r][c] = '\n';
                //         r++;
                //         c = 0;
                //         // Serial.println(_log_array[r-1]);
                //     }
                Serial.write(tt);
            }
        }
        file.close();
        //     return r;

    }
    void flashLOG::write(const char *message)
    {
        char a[_log_length];
        //     sprintf(a, "%s\n", message);

        File file = LittleFS.open(_logfilename, "a");
        if (!file)
        {
            Serial.println("Failed to open file for appending");
        }
        else {
            if (file.print(message)) {
                Serial.println("Append OK");
            }
            else {
                Serial.println("Append fail");
            }
        }
        Serial.printf("file size: %d\n", file.size());
        delay(2000);
        file.close();
    }
    void flashLOG::append(const char *message)
    {
        char a[_log_length];
        //     sprintf(a, "%s\n", message);

        File file = LittleFS.open(_logfilename, "a");
        if (!file)
        {
            Serial.println("Failed to open file for appending");
        }
        else {
            if (file.print(message)) {
                Serial.println("Append OK");
            }
            else {
                Serial.println("Append fail");
            }
        }
        Serial.printf("file size: %d\n", file.size());
        //     delay(2000);
        file.close();
    }
    void flashLOG::postlog(int x)
    {
        int num_lines = 0;//read();
        int y = min(x, num_lines);
        for (int a = 0; a < y; a++)
        {
            if (y > 1)
            {
                char t[_log_length];
                sprintf(t, "[#%d] %s", a, _log_array[a]);
                Serial.println(t);
            }
            else
            {
                Serial.println(_log_array[a]);
            }
        }
    }
    int flashLOG::sizelog()
    {
        File file = LittleFS.open(_logfilename, "r");
        int f=file.size();
        file.close();
        return f;
    }

`.ino` file

    #include <myIOT.h>
    #include <Arduino.h>

    flashLOG flog;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("\nBEGIN!");
      flog.start();
    //  flog.write("HITHERE");
      flog.read();
      flog.append("HITHERE2");
    //  flog.read();

    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

title: ESP8266 - Problem with LittleFS after reboot (solved in comments)

Answers: 0


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

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

Answers: 1

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.


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

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

Answers: 3

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'


body:
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);
        }
    }

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

Answers: 1

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.


body:
I'm new to Arduino. I am trying to making an obstacle avoiding car using Arduino Uno and L293d motor driver shield.

Four tt gear dc motors and 1 servo motor were connected. How much power should I supply or which batteries and how much should I use? Also, how do I increase the speed of the motor? It's max is 255 in shield but that it is slow.

title: How much power should I supply to L293d shield to run 4 tt gear dc motors and 1 servo sg90?

Answers: 0


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

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

Answers: 1

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


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

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

Answers: 1

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


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

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

Answers: 1

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


body:
I am a newbie. Please help to make gy512 visible on i2c interface.

i did

sda - a4
scl - a5
vcc - 5v
gnd - gnd

I have used i2c sticker scatch and use PC monitor.

title: connect gy512 is not visible by i2c bus

Answers: 0


body:
I am using SHT21 temp sensor with ESP32 using I2C. The sensor only reports temp of -273 and 0 for RH. The sensor is not faulty as I have tried this on an Arduino UNO with the same sketch and it works fine. I am using the default data and clk pins on ESP 32. Also I tried it on a different ESP32 board as well as powering the sensor from the ESP32 and externally but still get incorrect readings. I suspect it is more of a software issue than a hardware one. Could you please help me find the cause?

Here is my sketch:

    #include <Wire.h>
    #include <Sodaq_SHT2x.h>

    void setup()
    {
      Wire.begin();
      Serial.begin(9600);
    }

    void loop()
    {
      Serial.print("Humidity(%RH): ");
      Serial.print(SHT2x.GetHumidity());
      Serial.print("     Temperature(C): ");
      Serial.println(SHT2x.GetTemperature());
      Serial.print("     Dewpoint(C): ");
      Serial.println(SHT2x.GetDewPoint());

      delay(1000);
    }

title: Temp Sensor not working on ESP32

Answers: 0


body:
I'm currently working on HC-12 transceivers. Normal operations are fine and I was able to successfully transmit basic strings between an Arduino UNO and and Arduino Nano, both of which use HC-12s.

However, when I'm trying to configure the HC-12s using AT commands, the commands that I send through the serial monitor, like the basic "AT" or "AT+VERSION" return no response.

Here's my wiring setup [![enter image description here][1]][1]

 1. HC-12 VCC to Arduino 5V
 2. HC-12 GND to Arduino GND
 3. HC-12 RXD to Arduino D11
 4. HC-12 TXD to Arduino D10
 5. HC-12 SET to Arduino GND

And here's my arduino code fore sending AT commands

    #include <SoftwareSerial.h>

    #define RX 11 //Connect to the TX pin of the HC-12
    #define TX 10 //Connect to the RX pin of the HC-12

    SoftwareSerial mySerial(RX, TX);

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

      while(!Serial);

      Serial.println("Input AT commands");
    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }

Things I've already tried include switching to different baud rates from 300 to 9600. I've also tried the HC-12 GUI configuration tool, but that one returns an error "Serial I/O error: CreateFile failed"

Is there any way to find out if this is a problem of the HC-12 itself, or just a configuration issue?

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

title: HC-12 AT Commands not working

Answers: 0


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

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

Answers: 1

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


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

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

Answers: 1

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


body:
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);
        }
    }

title: Why is this looping?

Answers: 1

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.


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

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

Answers: 2

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.


body:
Example sketch does not compile, error message
'static void WiFiClass::init()' is private within this context
IDE 1.8.13
Board Uno WiFi Dev Ed.
I have been using this board for several years uploading to Thingspeak using UnoWiFiDevEd.h using Ciao.
Now I am trying to use the UnoWiFiDevEdSerial1.h library but I can't even compile the example code below. Any suggestions?

/*
 WiFiLink example: WebClient
 https://github.com/jandrassy/arduino-library-wifilink
 */

#include <UnoWiFiDevEdSerial1.h>
#include <WiFiLink.h>

char server[] = "arduino.cc";
boolean sendRequest = true;

WiFiClient client;

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

  Serial1.begin(115200);
  Serial1.resetESP();
  delay(3000); //wait while WiFiLink firmware connects to WiFi with Web Panel settings

  WiFi.init(&Serial1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(10);
  }
  Serial.println("You're connected to the network");
  printWifiStatus();
  Serial.println();
}

void loop() {
  if (sendRequest) {

/Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino: In function 'void setup()':
UnoWiFiLink_DevEd:21:8: error: 'static void WiFiClass::init()' is private within this context
   WiFi.init(&Serial1);
        ^~~~
In file included from /Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino:7:0:
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note: declared private here
     static void init();
                 ^~~~
UnoWiFiLink_DevEd:21:21: error: no matching function for call to 'WiFiClass::init(UnoWiFiDevEdSerial1*)'
   WiFi.init(&Serial1);
                     ^
In file included from /Users/mack/Documents/Arduino/UnoWiFiLink_DevEd/UnoWiFiLink_DevEd.ino:7:0:
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note: candidate: static void WiFiClass::init()
     static void init();
                 ^~~~
/Users/mack/Documents/Arduino/libraries/WiFi_Link/src/WiFiLink.h:44:17: note:   candidate expects 0 arguments, 1 provided
Using library Uno_WiFi_Developer_Edition_Serial1 at version 1.0.4 in folder: /Users/mack/Documents/Arduino/libraries/Uno_WiFi_Developer_Edition_Serial1
Using library WiFi_Link at version 1.0.1 in folder: /Users/mack/Documents/Arduino/libraries/WiFi_Link
Using library Wire at version 1.0 in folder: /private/var/folders/5v/dc3kh_4136g2j560dgjg3vww0000gn/T/AppTranslocation/E151A1AA-2F37-45B4-9B3C-A69070247D9C/d/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
exit status 1
'static void WiFiClass::init()' is private within this context

title: Uno WiFi Dev Ed - Example Sketch with UnoWiFiDevEdSerial1.h library by Juraj errors on compile

Answers: 0


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

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

Answers: 1

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.


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

title: Why are the Do While loops not stopping?

Answers: 3

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.


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

title: More effecient datalogging code

Answers: 1

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;
```


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

title: digitalwrite with function parameter as parameter

Answers: 1

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


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

title: ESPTool 3-run stub fail error

Answers: 1

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.


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

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

Answers: 1

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