text:
ESP8266 - Problem with LittleFS after reboot (solved in comments)
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:

}

Without the class header, and preferably some skeleton code that demonstrates how you are using it, it's hard to tell exactly what is happening. For example, are you working from example code that formats the LittleFS file system every time setup() runs? In trying to reverse-engineer the code, I came up with this, and it is working correctly in that there is data after every restart, and it is valid. the cpp is what you gave above, with my own .h and .ino. If you give more info, I'll do a proper answer.  https://gist.github.com/pfeerick/7230ce3b93c35c8b8feb4e97979ac3f7

Will edit my question soon

@PeterFeerick - edited

Thanks for that. Other than a missing #include <LittleFS.h> it worked - i.e. it was appending. I would suggest that if it is not working for you at all, you've not formatted the LittleFS partition first - look at the sketch at the bottom of the gist linked above. There is also an underlying issue in the code, as after several appends, the code causes an exception, but to be expected if you can't get the initial bits to work!
BEGIN!
MOUNTED OK
HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2Append OK
file size: 104

I added this to the loop... do you get anything after the ESP has restarted with this?
void loop() {   delay(2000);   ESP.restart();   delay(100); }

@PeterFeerick -class is implemneted in another.h file - so you don't see that include you've mentioned ( but it is there ). about the format, I'll try again, but doesn't it when I erase all ( third option in Arduino IDE ), doesn't it also format as needed ? how come it shows file size and read properly but "loses" data only after reboot ??

@PeterFeerick - BTW why did you add another #include<LittleFS in .ino file? ( I know it is for format but after it is formatted once, do you still need it ? )

I can't tell you why it shows file size and read properly but "loses" data only after reboot - perhaps it's only buffered in memory, not saved? Have a look at the output here.
https://gist.github.com/pfeerick/33791f2ddbc70f30a89a590eab71d9a0
hm... begin() is supposed to format if a file system isn't detected... i just did an 'erase all' and re-loaded the sketch minus the format routine, and it got to the append after file size: 104 again and then continuous exceptions again. Very strange.
I added the include because I also format when flashLOG b0rks after several appends

Actually, I'm not sure now... because of how the Arduino IDE preprocessor works, it isn't needed in the sketch... as you can see from the second gist... I didn't add it at all, since it will be included via the flashLOG.h. In reality, since I used it in the sketch main, it should be there as well. For your project, it shouldn't need to be included in the main sketch - just in the class that uses it.

I'm UTC+10, so unfortunately it looks like your work is my late evening. Happy to try and work through this more, just need to find a time that works for both of us ;) Then we can also take it over to the chat thingy (only clicked on it before to see what it was about and because SE was being pushy).

@PeterFeerick - As I told, class was placed in another library ( encapsulate my entire IOT class ). Somehow - I had an instance of a file saving JSON, outside to all classes ( I dont know why I did it ), running FS.h - which caused some collision with LittleFS.h which probaby can't be ran together :).
Thank you very much!

Fantastic. Glad you got it working! It's those seemingly little gremlins that are the most annoying - hard to pin down!

@PeterFeerick - sooooooo annoying. I was so troubled about how without calling any class but the one I need, it failed while in a new library it didn't....URRRGGHH. cheers


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

what is what you call 'response time'? there is no such thing. do you mean the time while the AT firmware sends the response after sending the command. that of course can't be instant. there is the communication over Serial and some processing time to handle the command in the firmware

If you're on about the prolific use of delay() after sending a command, is because back in the mists of time someone without a clue wrote a tutorial and did it wrong. People with even less of a clue copped it, and it grew from there. There is no call for any delay of you write your code properly with a send-expect model.

Okay thanks for your valuable suggestions45

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.

source: Stack Exchange

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

sort: votes


text:
how to fix mirrored text on 3.2 inch IPS TFT LCD Display ILI9481 480X320 36 Pins for Arduino Mega2560
i am working on a project on my arduino mega2560. I want to show reading of the sensors on the TFT display, the problem is the text displayed on the screen is mirrored. Since i am very new to arduino i don't know how to fix the problem. I have check a few videos on youtube but nothing helped. I am using the example from the UTFT library arduino (AVR) => UTFT_DEMO_480x320

Can you please provide a link to the library you used (for example to the corresponding github page)? I looked at the UTFT library, that I can find in my library manager, but that does not have any 480x320 demo, so I suspect, that you are using a different library. Also please show your code

http://www.rinkydinkelectronics.com/library.php?id=51

The orientation of the display is controlled by the "Set Address Mode" command (0x36) at line 42 of the ILI9481 driver.
The current value is 0x0A which is 00001010 in binary.  According to the datasheet (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.

i have tried this but still no luck its the same

There should be a change, even if it's a wrong change. So either the IDE caching the compiled code and not realizing that there's a change it needs to recompile for (probably, given the nature of that library), or it's not using the ILI9491 driver.

i have made changes as you suggested, also restarted the IDE i dont know why it isn't detecting any change, is there anything that i am missing?

Are you sure you changed it in the right file? There's lots of files all named the same in that library.

i have modified this file "\Arduino\libraries\UTFT\tft_drivers\ili9481\initlcd"

At times like this I like to add #error foo somewhere in the file in question and see if compilation then fails with a message of error: foo.

i have checked and its gives error while compiling which means it's compiling the latest changes, but the display is still mirrored, maybe there is something else that needs changing. your help will be highly appreciated, and thanks for what you have done until now.

There are other values that you can try. For example 0x4A, which changes the column address order.

0x4A works, now the text is not mirrored Thanks a lot. Can you please update your answer above and change 0x08 to 0x4A so that i can mark it answered.

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.

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'

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


text:
Arduino ESP8266 Wifi Shield GET request with LiteESP8266Client stops after few HTTP request
Below HTTP Get request is working but after few GET request(5-6) the code stops and once I press Arduino reset button then only it start working. Probably looks like something is causing OOM:
// This is a demo example using a public http server for testing both GET and POST requests

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

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

LiteESP8266 radio;

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

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

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

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

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

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

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

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

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

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

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

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

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

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

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

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

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

Probably looks like memory is not getting freed. I am using Arduino UNO + ESP8266 sheild
Update 2
Tried with other REST Server and same issue is observed:
// This is a demo example using a public http server for testing both GET and POST requests

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

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

LiteESP8266 radio;

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

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

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

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

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

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

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

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

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

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

Server side code
package com.test.iot;

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

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

What is your server code? The cause could be on the server side instead of client side. Also do you run the client using a public-facing test server such as httpbin.org as in the example to see if you are facing the same problem?

Yup same issue observed in example . Response attached here

Server side code attached

If you faced the same problem on both servers, then there is something wrong with the client, I will take a look tomorrow as I need to re-flash my esp-01 to do the test.

Could you add a delay in the loop to see if there is any difference?

Will do that to check and will let you know but I doubt this will help. Kindly do flash ESP01 and help with the fix if any required. Thank you

a funny library. it uses malloc with the size of the response. it fragments the heap  5 loops fast. btw: you allow it to allocate 5000 bytes on an MCU with 2kB RAM

Is there anyway to fix, like read line by line and discard not required stuff?? Any code snippet will be helpful to me. Thanks

I can only recommend me WiFiEspAT library. but you would have to flash a newer AT firmware to esp8266 https://github.com/jandrassy/WiFiEspAT/blob/master/README.md

@Juraj, 5000 is the timeout in ms, not the memory allocation.

@hcheung any idea  if it can be fixed soon? Juraj how is this new approach different from old one? Any reason to flash new firmware?

I just want to parse the response, my response size will also be very small like 1-2 word. I have been changing approaches from quite sometime now and to get it working till this step was tough, had to adjust the baud rate to get it working. If you can provide some more information about new firmware and how that is different from the one then that will be helpful.

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.

Awsome I will take latest code from github

BTW, as I mostly use stm32 for my works, I can afford to allocate memory that is equal to one packet MTU (i.e. 1500 bytes), if you are using Arduino, this will leave very little memory for your sketch, although LiteESP8266Client library is designed to utilise very little SRAM, if you found that you need more memory, you can redefine PACKET_MTU to smaller number. It is also better to wrap the string literal with F() macro to keep it in flash.

Many thanks @hcheung. Working like a charm..so far..touch wood


text:
How much power should I supply to L293d shield to run 4 tt gear dc motors and 1 servo sg90?
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.

The motors require the voltage that they require, whatever that is. You have to provide enough current to cover the peak consumption of your whole setup, plus ideally a bit more for "headroom".

What is tt? What's a "tt gear dc motor"?

The 255 only mean 100% duty cycle, so fully on motor. When that is too slow, you need to check, if younare operating the motor at its specified voltage and current. You can only get the max speed and force from a motor, when you are powering it woth the right voltage and provide enough current for it. We cannot know, what motor you exactly have. Look for the maximum current (stall current, as the motor draw max, when it cannot move) and the correct operaring voltage in the datasheet or product site of your motor. You should be able to get it from your vendor, where you bought the motor

Also check, if the motor driver can handle the voltage and current, that you need for the motor

Tt gear motor means BO gear motor yellow coloured

I had supplied power from my laptop so it is enough for motors

Also my motors are not working at initialI have to give some force then it works automatically

So may be problem is in shield


text:
How do powering arduino both barrel jack and lipo battery together?
I have arduino mega and Lipo batterry such this and Lipo battery charger 5V USB Boost. 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

Termal Circuit

Plug the (boosted) battery into the USB socket. Job done.

;) if i try that, boost is heating much more. Is that normal

No, that's not normal. If the barrel jack power is greater than 7V then the USB power should be isolated.

Majenko, you have it backwards. That boost circuit is designed to have 5V OUT at the USB and <5V in at the other end, so you can use a 1S LiPo battery to charge a cell phone. So, the battery goes to the input, while the power can be tapped from the USB connector output to the 5V pin on the Arduino to power the Arduino with 5V. A Schottky diode should probably go from the 5V out on the boost converter to the 5V pin on the Arduino to prevent backflow as well. Charging the LiPo battery from the barrel jack is another issue. That will require a LiPo charge controller IC.

@Majenko I've edited question with your solution but termal problem seen

@GabrielStaples that's why I say the boosted battery. And the usb power circuit deals with the isolation for you. The P-FET is the diode to prevent back powering and there is a handy polyfuse for added protection too.

@mehmet, woah, that's cool! I need a thermal camera. That's super useful. Your images are very low quality/low resolution though. Can you upload higher-resolution images?

Is that a genuine Arduino Mega or a cheap Chinese knock-off? If the latter they probably skimped on the power circuitry.

@GabrielStaples thnks! this is the seek thermal compact pro. Sorry about resulution this is max resulution 320 x 240 Thermal Sensor.

As is described in this post from the arduino forum, 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.

thanks for technic answer. If so I have something on my mind, only powering from barrel jack (9v) should make heating problem has to do it but it doesn't work like that with only powering from barrel dont make any heating problem


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

sounds like the connectors are not providing a solid electrical connection and may even be inadequate for the job ... your post does not really provide any useful info about the actual problem ... you could have asked the same thing in about 10 words ... my NEMA17 stepper motor connector is smoking.  how do i correct this?

too much heat is a problem of too much current and too much resistance; reduce both.

How would I reduce the resistance? Just lower the current? Are you sure that the problem isn't that there's not enough resistance?

Smoking is definitely a bad sign and not OK to run under these conditions. Take a photo of your setup. Maybe your wires are too small? Maybe your code is wrong, or your wiring is wrong and you are periodically shorting the motors, causing really high currents.

How do you attach wires to that shield? Little jumper wires to the pin headers?

Here are some pictures. It's not a complicated setup really. https://imgur.com/a/Ldex9bb
I think all I can do for now is lower the current on my drivers and hope for the best

Please paste images directly into your question. I'll do it for you this time.

I edited your question and inserted your 3 images. It requires review and approval. Perhaps even you can approve the edits? Not sure. Next time, please just drag and drop or copy and paste images right into your question while editing it.

Pin headers have a typical maximum current of 3A - and that is assuming you are connecting a plug with good connections. That is seldom the case.

The pins themselves can only handle 3A of current? Seems like that could definitely be the issue. By the way, how come everyone is commenting instead of writing up answers?

Because none of the comments resolve your question, so aren't really answers... With regard to the OP, smoke is never a good sign... The pins can probably take more than 3A since they are just solid pins, it's the connector/quality of the connection that can't. I suspect the black plastic shrouds are a bit melted if that's whats been getting hot! Plus, the drivers (if they are the A4988 ones) are only 2A rated, so if they are being pushed harder, overcurrent and thermal protection will be hard at work.

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

How can I disable a stepper motor?

On that particular CNC shield pin 8 is the enable pin - LOW=enabled, HIGH=disabled.


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

please provide all available information in your post ... there is no reason why people would have to do internet searches for a datasheet and for any applicable libraries before being able to answer your question

You may be interested in Adafruit's FRAM breakout board: https://www.adafruit.com/product/1895 They have an SPI version too, and both support 256Kbit's of persistent storage. Plus, they're super easy to use.

https://github.com/adafruit/Adafruit_SPIFlash

What is Adafruit's Circuit Playground Express's 2MB storage?

@Majenko, a board by Adafruit a well known and established company with a good web site. Circuit Playground Express is the only one not Arduino board in Arduino SAMD boards package. you could ask what is Neopixels or Feather Huzzah or MKR

@Juraj Yes.... I know who Adafruit are. But what is the "2MB storage"? Is it a physical device? If so what is it? Or is it some online service provided by Adafruit? It's not clear, and I shouldn't need to google these things.

So... it's just a run-of-the-mill 16Mb SPI flash chip. Big whoop. Wanna fight about it? Also Cypress list that model as obsolete now...

@Majenko, as I saw the question I opened the Adafruit site for the board and there it is: "2 MB of SPI Flash storage, used primarily with CircuitPython to store code and libraries.".

In their guided tour 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 (also from Adafruit), that they have also made a library, Adafruit SPI Flash, 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.


text:
connect gy512 is not visible by i2c bus
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.

What is a GY512? I could only find the GY521, which seems to be a breakout board for the MPU6050. And I guess you have used the standard I2C scanner sketch. Have you tried adding pullup resistors to the I2C lines (like 4.7kOhm)?

This question is hard to solve with so much info missing. Could you please add more info and perhaps some pictures.


text:
Temp Sensor not working on ESP32
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);
}

The two things that are different between your working- and non-working trials are the hardware (board and connections to the sensor) and the library code. Your own code and the sensor are already proven. So what is different between the Uno connections and ESP connections to your sensor? Between the Uno-specific and the ESP-specific code sections in the library (if any)?

In my code there is no UNO or ESP specific code. I use the exact same sketch on both microcontrollers. May be when it compiles there are certain things which change but I don't know about that. Other differences that I can think of are the I2C pins which are of course different for UNO and ESP32. I wonder if the library I am using can detect the correct data and clock pins on different mcu's.  But I am able to find the sensor when using the I2C address scanner. It just gives the wrong readings.

Maybe there is some MCU-specific code in the Sodaq_SHT2x library, such that maybe one section might compile for an Uno while another might compile for an ESP. That and connectivity, voltages, etc. seem to be the only differences. I agree that your own code should run on either MCU.

This is my first experience with ESP32 and so far using sensors on I2C bus is giving me a lot of issues. Good sensors (tested on arduino UNO) just stop working on ESP32. What am I missing here? Do I need to modify libraries and my code to make it ESP specific?

"so far using sensors on I2C bus is giving me a lot of issues" sounds like a clue, doesn't it? Especially if other sensors have given you the same problem. If that's the case, your issues sound very likely related to differences in hardware compatibility such as voltages, supply capability, connections, choice of ESP pins - something that is different about the ESP that applies consistently across the various sensors, and less likely to be software related. Has any sensor worked with ESP32 and I2C?

Exactly how is your sensor wired to the ESP32? What pins are connected to what pins? How is it powered? What happens when you run an I2C scanner on the ESP32?

@JRobert I doubt it's due to issues like voltage, supply capabilities etc. Both ESP32 and sensors am I having problem with are 3.3V and I have tried both powering the sensors using ESP32 and through external power supply. Another sensor that wasn't working initially on ESP32 was a BME280. But after sometime it started working. Same code, same circuit. Another sensor that worked right out of the box was an AHT10. So the I2C behaviour is pretty inconsistent.

@romkey It's a very basic setup. I am using 3.3V breakout board with 4 pins(Vin, GND, SCL, SDA). I am using the default I2C pins (D22 for SCL and D21 for SDA). Both the MCU and the breakout board are powered using external 3.3V supply.  The I2C scanner detects the sensor with it's address so ESP32 has no problem seeing the sensor

@Zaffresky that sounds solid - you wouldn't believe the number of people who wire stuff up and don't hook up GND or something like that... :) the only other issue there I can think of is if the wires are really long; that can cause issues with I2C. I'd try a different library that's known to work with the ESP32 - Adafruit and Sparkfun are both very good about this but unfortunately they don't seem to have an SHT21 library. FWIW, I've used BME280s with the ESP32 extensively with no problems.

There's a small chance that adding pull-up resistors to SCL and SDA might help - the ESP32's internal pull-ups are quite weak. A 47K resistor between SCL and 3.3V and SDA and 3.3V might make a difference.

@romkey you were right about the library. I have tried another library for SHT21 that was tested with ESP32 and it works like a charm :)  I was assuming that my tried & tested arduino libraries would work also for ESP32 but its not that simple. Anyways at least I know now where the issue lies

@Zaffresky in my experience many of them do but unfortunately not 100%. glad that resolved it!

The two main issues I encounter with sensors/I2C and different board types are that the needed pullups are different for 5V and 3.3V parts/systems, and if the library is written for AVR (i.e. Uno) it may not work properly on a ESP8266, etc, due to variances in the architecture, etc. So it's always good to try a few libraries, especially if you were able to detect the i2c device using the scanner sketch ;)

@PeterFeerick yeah I have learn't that now. I only had experience with AVR MCUs so far. I have learnt about the library issues now but you make a good point regarding the pull ups. Will keep that in mind as well


text:
HC-12 AT Commands not working
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

HC-12 VCC to Arduino 5V
HC-12 GND to Arduino GND
HC-12 RXD to Arduino D11
HC-12 TXD to Arduino D10
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?

You need to connect Arduino's Rx (pin 11) to HC-12 Tx, and Arduino's Tx(pin 10) to HC-12 Rx.

This worked. Thanks!


text:
Which board to select in PlatformIO for ESP Wroom 32?
I'm quite new in this microcontroller topic and my next step is to make use of a wlan module, which is a ESP WROOM 32.
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 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 ^

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 and find one that matches the amount of flash storage your board has.
You might want to read PlatformIO's ESP32 documentation.

Thanks a lot! I knew it was wrong..  after some hours :) I'm not using a breakout board. How can I figure out the board I have? I can only see what's written on it: fcc id 2ac72 esp wroom 32. Does that reveal something?

Just from the look I'd say it is a Node MCU. In platformio it is given as "NodeMCU-32S" but when I want to use it, it says it is an unknown board. ESP32 is apparently also an unknown board..

it is definitely this one: https://www.reichelt.de/nodemcu-esp32-wifi-und-bluetooth-modul-debo-jt-esp32-p219897.html

Looks like you got it!

Yeah, that was quite an effort just to get started.. :) But it is almost always the same, doesn't matter which electronics or programming..

btw, is there a certain site for all microcontroller related questions? I wonder that there is arduino and raspberry pie, but what about all the electronics around it and other microcontrollers like a stm32 and so on?


text:
Problems Sending Signals to the Arduino-Uno via Keyboard
I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.
I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

int SKEY = 8;

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

  protected:

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

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

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

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

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

}

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

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

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

KbdRptParser Prs;

void setup() {

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

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

  delay( 1 );

  HidKeyboard.SetReportParser(0, &Prs);

}

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

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?
Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!

what LED are you talking about? ... you have no LED control code in your sketch

you can print DN when a key is pressed ...  why can't you turn on an LED when a key is pressed?

sending a pulse to whatever pin when I push a key and stop sending a pulse ... that only applies to a flashing LED ... if you turn on a LED and leave it on, then that is not a pulse

I dont want to leave an led on... I want to be able to push a key to turn on an led and when I let up on that key the led should turn off. Also I made it clear that I have not made the led code yet because if I cant figure out how to make the proper if-statement none of it will work. Every time I try I get an error which was the whole reason I asked this question I know the code to make an led light up but I dont know how to do that while using the keyboard library...

your post says nothing about an error ... why don't you turn on the LED right after you print DN? ... turn off the LED right after you print UP

If I could I would... why else would I be asking this question if I knew how to do it...

i do not understand ... find the line that prints DN ... insert a line that turns on the LED right after it

The only if statement I see is if (Usb.Init() == -1) but that doesn't seem like one you are having trouble with. What is the full exact error message you get from the Arduino IDE when you compile your code?

Did you post the wrong code?  Where is this if statement you are talking about?

In the oneKeyDown routine you get a parameter called key that has the key that was pressed.  Save it to a variable and you can put that variable in an if statement to do whatever you want if it is equal to some value.  Or just light the led when the button is pressed right there in that routine.

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

Very strange because when I press a key there is a specific number or number letter combo attached to it. For example when I look at the serial monitor it knows what key I am pressing and for how long. I dont understand how the Arduino knows via the serial monitor what key is being pressed and is able to print it but wont cant send a pulse to a specific pin based on the duration the key is held down. If the Arduino is aware of the specific key being pressed and its duration there is no reason it cant light an led up.

@CyClone Well, this question and its answer were left alone, because you did not edit your question answering 1) how you tried to control the LED, and 2) which error you got trying.


text:
Why is this looping?
I am trying to do something very simple.  I want the LED to fade from full brightness to off.  This works... However, the LED turns back on to full brightness and fades again, in a loop.  I am not sure why.  I think I am missing something obvious.  Once the legThreeBrightness decrements to 0, nothing should happen...
int legThreeBrightness = 255;

void setup() {

    pinMode(3, OUTPUT);

}

void loop() {

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

legThreeBrightness = 255 doesn't do what you think it does. Turn up your compiler warnings and pay attention to what it says.

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.

sigh...  that was it.  I completely forgot that its a double == for comparison.

@Keltari Rookie mistake, we've all made it. Make sure you keep an eye on your operators whenever you're debugging :-)

https://en.m.wikipedia.org/wiki/Yoda_conditions

There are also some compilers that will warn you about this. If you count up the time you spent debugging this, it might be a better use to figure out if/how your compiler can.

@Keltari if you'd like, you can follow @JonathanZsupportsMonicaC's suggestion to enable compiler warnings. Go to File -> Preferences -> Compiler warnings: and set it to More. If you'd like the compilation to fail instead of just issuing a warning, add #pragma GCC diagnostic error "-Wparentheses" to the top of your program.


text:
Counting to 1000 In Both cores execution time problem in esp32?
I am trying to count to 1000 with single core and dual core with esp32 but the output(run time) dose not make sense, the time which takes a single core should be doubled compared to dual core in theory right?
Here is the code
TaskHandle_t Task1;
TaskHandle_t Task2;
SemaphoreHandle_t baton;

int i = 0;
long l;

void setup() {

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

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

//single core or dual core execution

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

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

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

}

The output I get for runtime
Single core :- 1033 ms
Dual core :- 701 ms

Without delay(1); command the result is even more obvious
Single core :- 39 ms
Dual core :- 40 ms

How can I make my algorithm show that single core takes twice time as dual core execution time I wan't both cores to work parallel not one after the other.

Only one task can be updating i at once. Without delay the act of doing the counting is negligible. It's the semaphore that is giving you any results at all.

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.

Thanks this helped me

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 iit could happen, that it will never has the value 1000for the second task.

But it did not speed up the execution time? Here is the updated code as you asked https://hastebin.com/ajileyiqud.cpp

Right now (without the delay) you couldn't speed up the execution time with a second task. Only one task is allowed to access iat a time and so the other task has to wait and could do nothing.
If you gives the task something to do (the delay) you should se the difference.

I don't understand how to get advantage of the dual cores it has?


text:
Uno WiFi Dev Ed - Example Sketch with UnoWiFiDevEdSerial1.h library by Juraj errors on compile
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

@Juraj ping - sounds like one for you...

you have the Library Manager version of the WiFiLink library. it doesn't allow to specify a Serial interface and has SC converter library included. use the version from the GitHub repo you linked. did you change the firmware?

it is documented here: https://github.com/jandrassy/arduino-library-wifilink#install-this-library


text:
Weird effect of AVR C on USB-serial communication
I recently decided to learn direct port manipulation instead of builtin arduino routines.
First I tried this piece of code
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("on");
delay(500);
digitalWrite(LED_BUILTIN, LOW);
Serial.println("off");
delay(500);
}

This program on running instantly established connection with the serial monitor on my arduino IDE.
But when I try this code
int main(void)
{
Serial.begin(9600);
DDRB = B11111111;
while(1)
{
PORTB = PORTB | 0x20;
Serial.println("off");
_delay_ms(500);
PORTB = PORTB & 0xDF;
Serial.println("on");
_delay_ms(500);
}
}

But this program is taking some time, about 5-10 seconds to establish serial connection. Also delay() is not working too. When I use delay() instead of _delay_ms(), the entire arduino board freezes like a computer and stops blinking the LED instead LED is fully ON.
I tried is on several programs, while "setup-loop" program connects instantly, AVR C programs does not.
why does it happen?

Because normally main() initializes all the appropriate hardware and timers. You're circumventing that with your own main() so nothing Ardunioy works.

I should be most grateful if you could elaborate that in an answer.

please indent your code correctly .... beginners that might be browsing the quetions should be exposed to correctly formatted code no matter how simple the code listing is

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.

Could you explain the significance of "serialEventRun"?

If you haven't defined a serialEvent() function then it has no significance at all. If you have defined one then it runs it.

What is the purpose of initVariant()?

That is the bit where I say then board-specific ones (normally nothing)

I just rewrote my code to include just init() and nothing else, the serial communication, both read and write, is now working. So my question, is     USBDevice.attach()
necessary?

Only if you're on an ATMega32U4 or similar chip where the USB is a real USB connection, not a UART connection through a USB bridge chip.

Let us continue this discussion in chat.


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

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

void setup() {

    Serial.begin(9600);

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

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

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

}

void loop() {

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

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

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

}

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

and

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

you can remove 2/3 of the code if you use arrays

@jsotola that is probably true, but doesnt change the error I am having,

first do loop counts to -1 ... the second do loop prints the -1 and counts to 256 ... second do loop keeps counting from 256  because do-while always runs at least once ... use if (legThreeBrightness > 255){

Seems to be the question title should changed slightly, such as "Why are the do while loops stopping later than I expect?"

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).

Honestly, I think I actually tried this last night, but I will try it again.  It also doesnt explain why in only happens sometimes.  I will report back.

It's definitely this - you can see in the output it go out of bounds, and just keeps going. e.g. from one part of a run: 252 253 254 255 256 256 257 256 258 257 257 259 258 259 258 260 259 260 260 261 262 263 261 262 263 264 265 261 264 265 266 267 262 263
Another way to prevent the value going out of bounds is to not use a do while loop, which runs the loop BEFORE it tests the value. But you will still need to use < or > for the comparison as you don't want the value decremented/incremented past when you have reached the boundary of your range.

this fixed the issue

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;

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


text:
More effecient datalogging code
Background:
I am using a Teensy 3.6 to data log over a dozen sensors. I am printing to Serial1 for local Serial access, Serial3 for remote access (via xbee, same data is on Serial1 as on Serail3, just different physical connection) as well as datalog to SDCard (CSV format). My code is expanding and is incredibly repetitive, and I am looking for a more efficient way of writing the following. I am trying to move a lot of the rest of my code to classes using this and this 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.

put the two serial prints and the datalog into one function ... call the function for each parameter to be logged ... use an array for the text ... pass parameter value and index to text to the function ... log(1, eOilTempF); ... 1 points to Engine Oil Temp:\t

IIRC there's a library around that lets you use << with Serial. I can't recall what it's called though and my google-fu isn't strong enough.

simplify code by using an array to hold values ... e[ OilTempF ] instead of eOilTempF ... that way you can loop through values

@Majenko Streaming might be what you're talking about: https://github.com/janelia-arduino/Streaming. This would help a lot with taking out all of the Serial.print and extra lines, but it would still be duplicated code between Serial, Serial3, and Logfile

@TheAutomator Yeah, that's the one. It would certainly make each block smaller, and you may be able to use it with a wrapper class that mirrors the output to two serial devices.

You can combine the 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;

You don't need to use pointers, eg. DualSerial(Print & s1, Print & s2) : _dev1(s1), _dev2(s2) {} and change the member variables to Print & _dev1; Print & _dev2;. In the write function change -> to .. You can initialise a reference in a constructor.

@NickGammon I know. But I like using pointers.


text:
digitalwrite with function parameter as parameter
Firstly, excuse my poor English, this is not my native langage.
I'm trying to use an Arduino Uno to drive an 8 relay board from an MQTT Subscription. I ask for help because i'm some kind of beginner in arduino, i'm just a Linux addict.
The idea is to get a payload from PubSubclient and use it to manage relays.
For example, the payload '71' ask the relay 7 to turn on and '42' make the relay 4 to turn off.
All works fine until I wanted to write a function with two parameters : 'relay_number' and 'Action'
All parameters are received but the relay never goes up or down.
My code :
void callback(char* topic, byte* payload, unsigned int length) {

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

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

  RelayControl(Relay_Nb, Action);
}

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

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

I'm sure an old maker have the solution i'm searching for hours now.
Please help and don't hesitate to show me others ways.
Thanks.

What is the serial output?

Relay_Nb is the character 1 or 0, not the value 1 or 0?

The serial output is for debugging purpose.
Character or value is probably the problem, but what have i to do to change this?

your callback function makes an assumption about the data ... there is no check for unexpected data

You're right.I'll write it after the relay issue.

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:

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

It works fine, you're my hero.
I just don't understand how. Where can I find some explaination ?
I can now start the security checks.

@Pwol: man ascii, and look for the code points of the digits.

@EdgarBonet You're assuming he's using a real operating system, not some toy like Windows.

@Majenko: He wrote “i'm just a Linux addict”.

@EdgarBonet True. I tuned out at "I ask for help because..."

Any reason ot use '0' subtraction in preference to the atoi() function? i.e. int Relay_Nb = atoi(payload[0]);

@PeterFeerick atoi() expects a string, not a character.

Or Relay_Nb = payload[0] & byte(0x0f); That's why ASCII for 0 to 9 was encoded as 0x30 to 0x39, i.e. easy conversion between bytes and characters.


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

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.


text:
Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board?
I have just started my first project on Arduino. I have an Arduino Uno and an L293D motor shield.
I have installed the motor shield on the Arduino Uno board and the motor shield covers all pins of the Arduino Uno board. The motor shield is connected with four gear motors and one servo motor.
Can I use digital pins 2-13 to make some LED flashing circuit?
Which digital pins are used by the Motor shield and which pins are not used?

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

Link to the shield? Is it really a L29D, or is it actually a L293D? What pins are used in the code?

@MatsK, I notice in your edit you removed tt from gear motor description. It looks like this is a brand/model. See here: https://www.adafruit.com/product/3777. I didn't know what it meant at first either so I had left it in.

If this is the same board as seen on Banggood Which may also be seen at Adafruit
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.


text:
wdt reset cause:4, boot mode:(3,6)
I'm working on Python and nodeMCU with websocket connection.
So, I send a string from Python to nodeMCU and nodeMCU collects the string and decodes to set values to a stepper motor. Initial code worked fine before updating with stepper motor code. Now it triggers watchdog resets.
Here's my full code:-
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AccelStepper.h>

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

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

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

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

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

  WiFi.begin(ssid, password);

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

  Serial.println(WiFi.localIP());

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

  server.begin();

}

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

  if(type == WS_EVT_CONNECT){

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

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

  } else if(type == WS_EVT_DATA){

    Serial.println("Data received: ");

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

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

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

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

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

    }

//    Serial.println();
  }
}

void loop(){

  }

It would be a great help pointing out my mistakes.

Does stepper.runToPosition(); block the code from continuing until the stepper has moved into position? wdt reset cause:4 is a hardware watchdog crash type, and occurs because your ESP8266 has been busy for too long without giving control back to the underlying RTOS. IIRC, it fires for perceived 'lockups' of approx 8 seconds. You can try scattering a few yield(); in your onWsEvent function and see if that helps.

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

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

When you call delay() or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.
The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in loop().
For instance,
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){

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

  if(type == WS_EVT_CONNECT){

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

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

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

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

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

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

}

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


text:
Port manipulation: Coding for two chips
I am using Arduino Nano to test a code that will be ported on an ATTiny chip, which will need to perform operations at a frequency near clock maximum, calling for a very succinct coding.
My goal: to streamline coding for two different chips in one file with the least repetitions and operations possible.
Specifically, I have a pin
#ifdef TIMSK0 //Nano vs atTiny
const byte  wavePin  = 5,
            waveBit  = B100000;
      byte *wavePort = &PORTD;
#define NANO
#else
const byte  wavePin  = 0,
            waveBit  = PB1;
      byte *wavePort = &PORTB;
#endif

Notice the pointer? It works, but I have the impression this may not be the most efficient option, as it adds an operation (by looking up the reference). I have also planned to do constantly check which chip we are loading it in this fashion
#ifdef NANO
  PORTD
#else
  PORTB
#endif
  |=   waveBit *  waveOn);
#ifdef NANO
  PORTD
#else
  PORTB
#endif
  &= ~(waveBit * !waveOn));

But again, while this may be perfectly fine in operations, it hurts the eyes and is rather repetitive.
Is there a way to create a direct access to a port?

Are you familiar with C++ Macros?

Not yet? Tell me more :D

Do you mean to do something like #define WAVEPORT PORTD?

StarCat you opened me a can of worms and I love it :D Thanks it actually works!

Great! That is actually more or less what I meant.