text:
How to add a pedestrian button code to a traffic light with ultrasonic sensor?
So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.
I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:
// Variables for Station 1 Traffic Light Components
const int Red1LED = 9;
const int Yellow1LED = 2;
const int Green1LED = 3;
const int GreenArrow = 4;
#define trigPin 12
#define echoPin 13
// Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 5;
const int Yellow2LED = 6;
const int Green2LED = 7;
const int GreenArrow2 = 8;

void setup() {

  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(GreenArrow, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(GreenArrow2, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
 Serial.begin(9600);
  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  //delayMicroseconds(10); // Added this line
  //digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.println(distance);
  if (distance < 20) {  // This is where the LED On/Off happens
     delay(1000);  //  1 Seconds of Red
  digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Yellow1LED, HIGH);
  delay(1000);  // 1 Seconds of Green
  digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Red1LED, HIGH);
  delay(1000);  // 1 Seconds of Yellow
   // Station 2 Timing
  delay(1000);  //  1 Second of Red
  digitalWrite(Red2LED, LOW);
  digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
  delay(1000);  // 1 Second of Green
  digitalWrite(GreenArrow2, LOW);
  digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
  delay(1000);  // 1 Second of Yellow
  digitalWrite(Green2LED, LOW);
  digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
  delay(1000);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Red2LED, HIGH);

   digitalWrite(Red1LED, LOW);
  digitalWrite(GreenArrow, HIGH);
  delay(1000);
  digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite( Green1LED, HIGH);
}
  else {
   digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
  digitalWrite(Red2LED, HIGH);
  digitalWrite(GreenArrow, LOW);
  digitalWrite(Green1LED, HIGH);
  digitalWrite(Yellow1LED, LOW);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Green2LED, LOW);
  digitalWrite(GreenArrow2, LOW);

  }
}

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.

Thank you for making it clear that this is course work.
You are asking for help to do the extension, but by your own words you don't understand how the core code works.  I have to be honest I can't be bothered to read the code, it looks horrible.  If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding.  "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty!  (If you teacher can't be bothered to read it, you aren't going to get 100%!)

Comments - commenting out code is not the best use for // explaining why you are doing what you are doing is.
Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures.  (These might be more advanced than where you are at the moment, sorry if that's the case).
Breaking you code down into bite sized pieces make it more readable.  That start of your loop contains some code that could be in a function called getDistance()
Turning the lights on and off in the way you are doing it is open to errors.  You could turn the red light on and the green light on.  If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted.  You wouldn't need to store the state.

Example code (not tested or compiled)
class Lights
{
  public:
    enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
    Lights(int[] pins)
    {
      for (int l = 0; l < eMaxLight; ++l)
        pinMode (pins[l], OUTPUT);
    }
    ~Lights()
    {}
    void setLight (eLight newLight)
    {
       for (int l = 0; l < eMaxLight; ++l)
         digitalWrite(m_Light[l], LOW);
       digitalWrite(m_Light[newLight], HIGH);
    }
}

You probably want to look at a state machine.  List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed.  This should give you a working system with a pedestrian button that hopefully you understand.

Thanks for answering but the code you have given me includes pedestrian lights. I would rather just press the button and have all the lights turn off. How does the code work and what does each line do because I'm very confused. And what is a enum? My code was rather simple because it is all we know. We just started learning arduino and our teacher has been away for quite awhile now. And compared to other students in my class this was the shortest code so I guess you can't expect better for beginners. I just have to learn coding all together to be honest.

An enum is a way of representing a discrete set of values with words in your code.  (A better description is here https://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx).  So a pedestrian presses the button on pin 'x' and the traffic lights go off?  or do you mean the lights go red.  That should be "easy" to achieve.  Delete the pedestrian values from the enum.  Attach a button and get it to trigger an interrupt (see Arduino website).  The interrupt handler will set the value of a volatile bool to true.  Your main code will have to check this value regularly, and change the lights.


text:
this code is not printing anything on the serial moniter. the code is in setup()
Serial.println("CLEARDATA"); //clears up any data left from previous projects
Serial.println("LABEL,time,load reading(gm),microwave output,CO sensor,sound data,magnetic sensor "); //always write LABEL, so excel knows the next things will be the names of the columns (instead of Acolumn you could write Time for instance)
Serial.println("RESETTIMER"); //resets timer to 0

//pinMode(AOUTpin, INPUT);//sets the pin as an input to the arduino
// pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
Serial.println("HX711 calibration sketch");
Serial.println("Remove all weight from scale");
Serial.println("After readings begin, place known weight on scale");
Serial.println("Press + or a to increase calibration factor");
Serial.println("Press - or z to decrease calibration factor");

Please include the entire setup() function.

Serial.begin(9600); is missing

There can be different reasons, among:

The speed of the serial port does not match with the serial 'monitor'
The speed of the serial port is not set at all (can cause first problem)

I don't see this before the print statements:
Serial.begin(9600); // or some other speed
That will prevent anything from printing.

source: Stack Exchange

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

sort: votes


text:
Problems lighting LEDs on receiving Arduino given a char array from sending Arduino in Tinkercad
The gist of the problem is that I'm trying to have an Arduino with a breadboard that has 5 buttons and 4 LEDs each led is linked with a button and the fifth button "sends" the lights that were switched on with a char array to the receiving Arduino, in this Arduino, this Arduino algo has a breadboard with 4 LEDs of the same color and with the char array I try to switch the same LEDs that were switched on in the first Arduino, my problem is when I send the char array and receive it in the second Arduino and try to run a function that runs through the array and find which points in the char array are different than 0 and turn on a led it never turns any LEDs, I know the logic is right but I don't understand why it doesn't work.

This is the design I am working with in tinkercad and will also link the project if you wish to run it on there, I assume that the problem is from tinkercad and not the code though I may be horribly wrong.
This is the sender sketch
#include <SoftwareSerial.h>

#define rxPin 9
#define txPin 8

// Iniciamos los pins de los 4 leds de sender y reciver
const int ledRed = 13;
const int ledBlue = 12;
const int ledGreen = 11;
const int ledWhite = 10;

// iniciamos los pins de los 5 botones
const int pushbuttonRed = 7;
const int pushbuttonBlue = 6;
const int pushbuttonGreen = 5;
const int pushbuttonWhite = 4;
const int pushbuttonEnviar = 3;

// Declaramos el estado de los 4 leds de sender y reciver
int ledStateRed = 0;
int ledStateBlue = 0;
int ledStateGreen = 0;
int ledStateWhite = 0;

char c;
char leds[7] = {'H','0','0','0','0','F','\0'};

//String cadena_final = "";
SoftwareSerial receiver =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  Serial.begin(9600);
  receiver.begin(9600);
  pinMode(ledRed, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledWhite, OUTPUT);
  pinMode(pushbuttonRed, INPUT);
  pinMode(pushbuttonBlue, INPUT);
  pinMode(pushbuttonGreen, INPUT);
  pinMode(pushbuttonWhite, INPUT);
  pinMode(pushbuttonEnviar, INPUT);
}

void loop() {

    // Boton Rojo
    if(digitalRead(pushbuttonRed) == 1) {
      digitalWrite(ledRed, HIGH);
      ledStateRed += 1;
      leds[1] = '1';
      if(ledStateRed % 2 == 0){
        digitalWrite(ledRed, LOW);
        leds[1] = '0';
        ledStateRed = 0;
      }
      delay(100);
    }

    // Boton Azul
    if(digitalRead(pushbuttonBlue) == 1) {
      digitalWrite(ledBlue, HIGH);
      ledStateBlue += 1;
      leds[2] = '1';
      if(ledStateBlue % 2 == 0){
        digitalWrite(ledBlue, LOW);
        ledStateBlue = 0;
        leds[2] = '0';
      }
      delay(100);
    }

    // Boton Verde
    if(digitalRead(pushbuttonGreen) == 1) {
      digitalWrite(ledGreen, HIGH);
      ledStateGreen += 1;
      leds[3] = '1';
      if(ledStateGreen % 2 == 0){
        digitalWrite(ledGreen, LOW);
        ledStateGreen = 0;
        leds[3] = '0';
      }
      delay(100);
    }

    // Boton Blanco
    if(digitalRead(pushbuttonWhite) == 1) {
      digitalWrite(ledWhite, HIGH);
      ledStateWhite += 1;
      leds[4] = '1';
      if(ledStateWhite % 2 == 0){
        digitalWrite(ledWhite, LOW);
        ledStateWhite = 0;
        leds[4] = '0';
      }
      delay(100);
    }

    // Boton Enviar
    if(digitalRead(pushbuttonEnviar) == 1) {
      // Reinicio los leds de sender para enviar otro mensaje
      ledStateWhite = 0;
      ledStateGreen = 0;
      ledStateBlue = 0;
      ledStateRed  = 0;
      digitalWrite(ledWhite, LOW);
      digitalWrite(ledRed, LOW);
      digitalWrite(ledBlue, LOW);
      digitalWrite(ledGreen, LOW);
      delay(100);
      Serial.write(leds,7);
      leds[1] = '0';
      leds[2] = '0';
      leds[3] = '0';
      leds[4] = '0';
    }
}

void printArray(char A[]){
    int i = 0;
    for(i=0;i<6;i++){
        Serial.print(A[i]);
    }
}

This is the receiver sketch
#include <SoftwareSerial.h>

#define rxPin 9
#define txPin 8

char leds2[7] = {'\0'};

// Iniciamos los pins de los 4 leds
const int Red = 4;
const int Blue = 5;
const int Green = 6;
const int White = 7;

// Creamos el boton que limpia pantalla
const int buttonClear = 10;

char c;
String recData;

SoftwareSerial receiver =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  receiver.begin(9600);
  pinMode(Red, OUTPUT);
  pinMode(Blue, OUTPUT);
  pinMode(Green, OUTPUT);
  pinMode(White, OUTPUT);

  Serial.begin(9600);
}

void loop() {
    int i=0;

    if (receiver.available()) {

      delay(100); //allows all serial sent to be received together
      while(receiver.available() && i<6) {
        leds2[i] = receiver.read();   // starts with i=0
        delay(100);
        i++;
      }
      leds2[i]='\0';
      //digitalWrite(Red,HIGH);
    }
    if(i>0) {
      lightLeds(leds2);
    }
}

void lightLeds(char A[]){
    int i;

    for(i=0;i<6;i++){
        if(A[1]=='1' || A[1]==1) digitalWrite(Red, HIGH);
        if(A[2]=='1' || A[2]==1) digitalWrite(Blue, HIGH);
        if(A[3]=='1' || A[3]==1) digitalWrite(Green, HIGH);
        if(A[4]=='1' || A[4]==1) digitalWrite(White, HIGH);
    }
}

void printArray(char A[]){
    int i = 0;
    for(i;i<6;i++){
        Serial.print(A[i]);
    }
}

Your "working logic" is quite unlogic:
In sender you define a char array:
char leds[6] = {'H','0','0','0','0','F'};
which should be
 char leds[7] = {'H','0','0','0','0','F','\0'}; // terminate the array

Here each '0' represents a led as can be seen in subroutine Boton Enviar
Instead of assigning a state to each position 0/1 so leds[2]='1' would be e.g. led blue ON you write a number to it (example walk through for blue):
if(digitalRead(pushbuttonBlue) == 1) {
      digitalWrite(ledBlue, HIGH);
      ledStateBlue += 1;
      leds[2] = '5';  // Here should be leds[2] = '1';
      if(ledStateBlue % 2 == 0){
        digitalWrite(ledBlue, LOW);
        ledStateBlue = 0;
        leds[2] = '0';

so if blue and and you send (if using the terminator)
 leds[] = {'H','5','0','0','0','F'.'\0'};

On the receiver side the following happens:
   while(receiver.available() && i<6) {
        leds2[i++] = receiver.read();   // starts with i=1
        delay(100);
      }
      leds2[i++]='\0';
      digitalWrite(Red,HIGH);
    }
    if(i>0) {
      lightLeds(leds2);

so your led2 looks like
 {XX,'H','5','0','0','0','F'} //XX is undefined garbage might be '\0' so the array ends here

Solution define array as follows:
char leds2[7] ={'\0'};
.....
   while(receiver.available() && i<6) {
        leds2[i] = receiver.read();   // starts with i=0
        delay(100);
        i++;
      }
      leds2[i]='\0';
      // digitalWrite(Red,HIGH); // USE builtin led not one of the used as "end marker"
    }
    if(i>0) {
      lightLeds(leds2)

The light logic should go for the space a value is and not the value:
void lightLeds(char A[]){
    int i;

    for(i=0;i<6;i++){
        if(A[2]=='1' || A[2]==1) digitalWrite(Blue, HIGH);
        if(A[2]=='0' || A[2]==0) digitalWrite(Blue, LOW);
       ....
    }
}

To get the mix of different logics apart place both progs in an editor (eg. notepad++) side by side and look for differences in the logic. There is more than one error in the programs, fix them as proposed and it wll work (Read the comments in my code for further details).
EDIT
The OP had still problems with his code. I tookthe example and let it run hardware based on two UNOs, it worked but SoftwareSerial is very bad. No problem on the hardware with AltSoftSerial.h. In TinkerCAD no chance, the moment I switched to HW-Serial it worked like a charm, so here is the refined code for SENDER:
// Time variables
unsigned long startTime = 0;
unsigned long intervalTime = 1000; // send once a second

// Iniciamos los pins de los 4 leds de sender y reciver
const int ledRed = 13;
const int ledBlue = 12;
const int ledGreen = 11;
const int ledWhite = 10;

// iniciamos los pins de los 5 botones
const int pushbuttonRed = 7;
const int pushbuttonBlue = 6;
const int pushbuttonGreen = 5;
const int pushbuttonWhite = 4;
const int pushbuttonEnviar = 3;

// Declaramos el estado de los 4 leds de sender y reciver
int ledStateRed = 0;
int ledStateBlue = 0;
int ledStateGreen = 0;
int ledStateWhite = 0;

char c;
char leds[7] = {'H', '0', '0', '0', '0', 'F', '\0'};

//String cadena_final = "";
SoftwareSerial sender =  SoftwareSerial(rxPin, txPin);

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledWhite, OUTPUT);
  pinMode(pushbuttonRed, INPUT);
  pinMode(pushbuttonBlue, INPUT);
  pinMode(pushbuttonGreen, INPUT);
  pinMode(pushbuttonWhite, INPUT);
  pinMode(pushbuttonEnviar, INPUT);
  sender.begin(19200);
  DEBUG_INTERFACE.begin(9600);
  DEBUG_INTERFACE.println("DEBUG ON");
}

void loop() {

  // Boton Rojo
  if (digitalRead(pushbuttonRed) == 1) {
    digitalWrite(ledRed, HIGH);
    ledStateRed += 1;
    leds[1] = '1';
    if (ledStateRed % 2 == 0) {
      digitalWrite(ledRed, LOW);
      leds[1] = '0';
      ledStateRed = 0;
    }
  }

  // Boton Azul
  if (digitalRead(pushbuttonBlue) == 1) {
    digitalWrite(ledBlue, HIGH);
    ledStateBlue += 1;
    leds[2] = '1';
    if (ledStateBlue % 2 == 0) {
      digitalWrite(ledBlue, LOW);
      ledStateBlue = 0;
      leds[2] = '0';
    }
  }

  // Boton Verde
  if (digitalRead(pushbuttonGreen) == 1) {
    digitalWrite(ledGreen, HIGH);
    ledStateGreen += 1;
    leds[3] = '1';
    if (ledStateGreen % 2 == 0) {
      digitalWrite(ledGreen, LOW);
      ledStateGreen = 0;
      leds[3] = '0';
    }
  }

  // Boton Blanco
  if (digitalRead(pushbuttonWhite) == 1) {
    digitalWrite(ledWhite, HIGH);
    ledStateWhite += 1;
    leds[4] = '1';
    if (ledStateWhite % 2 == 0) {
      digitalWrite(ledWhite, LOW);
      ledStateWhite = 0;
      leds[4] = '0';
    }
  }

  // Boton Enviar
  if (digitalRead(pushbuttonEnviar) == 1) switchAll();

    if (millis() - startTime > intervalTime) {
    DEBUG_INTERFACE.println(leds);
    sender.println(leds);
    startTime = millis();
  }
}

void switchAll() {
  // Reinicio los leds de sender para enviar otro mensaje
  ledStateWhite = 0;
  ledStateGreen = 0;
  ledStateBlue = 0;
  ledStateRed  = 0;
  digitalWrite(ledWhite, LOW);
  digitalWrite(ledRed, LOW);
  digitalWrite(ledBlue, LOW);
  digitalWrite(ledGreen, LOW);
  DEBUG_INTERFACE.println(leds);
  leds[1] = '0';
  leds[2] = '0';
  leds[3] = '0';
  leds[4] = '0';
}

and the code for RECEIVER:
// Iniciamos los pins de los 4 leds
const int Red = 4;
const int Blue = 5;
const int Green = 6;
const int White = 7;

// Creamos el boton que limpia pantalla
const int buttonClear = 10;

char rc;
const int maxChar = 6;
static byte charCount = 0;
char leds2[7] = {'\0'};
bool newData = false;

#define DEBUG_INTERFACE Serial
#define receiver Serial

void setup() {
  receiver.begin(9600);
  pinMode(Red, OUTPUT);
  pinMode(Blue, OUTPUT);
  pinMode(Green, OUTPUT);
  pinMode(White, OUTPUT);

  DEBUG_INTERFACE.begin(9600);
  DEBUG_INTERFACE.println("DEBUG ON");
}

void loop() {
  receiveStartEndMarkers();
  if (newData) {
    DEBUG_INTERFACE.print(" LED Array received: ");
    DEBUG_INTERFACE.println(leds2);
    lightLeds(leds2);
    newData = false;
  }
}

void lightLeds(char A[]) {
  for (int i = 0; i < 6; i++) {
    if (A[1] == '1' || A[1] == 1) digitalWrite(Red, HIGH);
    if (A[2] == '1' || A[2] == 1) digitalWrite(Blue, HIGH);
    if (A[3] == '1' || A[3] == 1) digitalWrite(Green, HIGH);
    if (A[4] == '1' || A[4] == 1) digitalWrite(White, HIGH);
    if (A[1] == '0' || A[1] == 0) digitalWrite(Red, LOW);
    if (A[2] == '0' || A[2] == 0) digitalWrite(Blue, LOW);
    if (A[3] == '0' || A[3] == 0) digitalWrite(Green, LOW);
    if (A[4] == '0' || A[4] == 0) digitalWrite(White, LOW);
  }
  DEBUG_INTERFACE.print(A); DEBUG_INTERFACE.println(" Leds switched");
}

void receiveStartEndMarkers() {
  static boolean recvInProgress = false;
  char startMarker = 'H';
  char endMarker = 'F';

  if (receiver.available() > 0) {
    rc = receiver.read();
    //DEBUG_INTERFACE.print(rc);
    if (recvInProgress) {
      if (rc != endMarker) {
        leds2[charCount] = rc;
        charCount++;
        if (charCount > maxChar) {
          charCount = maxChar;
        }
      }
      else {
        leds2[charCount] = rc;
        charCount++;
        leds2[charCount] = '\0'; // terminate the string
        recvInProgress = false;
        charCount = 0;
        newData = true;
      }
    }
    else if (rc == startMarker) {
      recvInProgress = true;
      leds2[charCount] = rc;
      charCount++;
    }
  }
}

Working code looks like this - change to HW-Serial 0(RX), 1(TX) to 1(TX), 0(RX):

So as a result DO NOT USE SoftwareSerial.h in TinkerCAD - its not working at the moment, use HW serial for communication examples or you will get crazy if working code suddenly outputs garbagge. When using real hardware use AltSoftSerial (full duplex mode). If you plan to use your design with real hardware use resistors for the LEDs (search for resistor calculator LED) as different colored leds need different resistor values.

I've added all of the suggested changes, still the problem persists, the lights from the second arduino will not light up. Also i cannot find a continuation in the comments as you suggest in the end of your post.

There, the code has been edited

Sure, here is the tinkercad link: https://www.tinkercad.com/things/37CXjQkn6Bi-copy-of-4-buttons-4-leds/editel?sharecode=dSsvqDLMEfnYp7htfceDF2-BnIh1-h0FegRC5zt1KdQ

Riddle solved see my edit above example under your link is fully working now-have fun and if ok mark as solved Thanks

I'm sorry, it seems that both receiver and sender are the same code.

Codebreaker, it's not working for me. The LEDs on the second Arduino are not lighting up and the second Arduino is never receiving the LED array or atleast the message is never displaying.

Code fixed (c&p error). You have of course to use HW Serial so connect 0(RX), 1(TX) from one Uno to 1(TX), 0(RX) to the other and delete the sw serial cables I tested for an hour it works 100%

Yes, it works. Thank you so much.

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


text:
Potential difference across the same wire
This issue may be weird, and I'm not sure if this is because of my wiring, but it would seem that I do not have the same voltage (or approximately the same voltage) between the VCC(3.3V) and the VCC power rail of my breadboard.
When measuring the voltage, there is ~0.300 mV difference. And indeed measuring VCC and GND gives me 2.9 V, instead of 3.3 V

I measured the flat jumper, it doesn't have any resistance (~~0)

The ESP is consuming below 100mA, so no voltage drop

Could anyone explain me that ?
See attached pictures

It's not "same" wire. There are at least contacts between board pin and bread board and bread board to wire... But if those rails are unloaded, it'll be quite unexpected to have any voltage drop

You are not measuring the wire. Try putting one probe on the actual wire where it goes into the breadboard, not the Arduino 3.3V point, and the other probe on the other end of that wire.

This question seem to belong in electrical engineering community rather than here.

The only reasonable explanation is that the path between the 3.3V pin and the wire you are measuring does indeed have non-zero resistance. The wires look dirty to me from the photo, plus there would be internal resistance in the breadboard connectors.
You are measuring from the 3.3V pin and not the other end of the wire. I suggest using a different wire, or cleaning that one with sandpaper or by filing it down until you see shiny copper. Also try a different pin on the breadboard.
This is really a hardware or measurement issue. There is no way that a wire with zero resistance from one end to the other is going to have a 0.242V drop across it.

I struggled a few days to get it work, but it would seem that I don't have any more voltage drop :) (or below 10mv), thank you for your answer !

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


text:
1MHZ Attiny85 RF with MANCHESTER library
I'm trying to set up a transmitter made by the following components :

Attiny85 (I need 1MHZ speed)
Cheap 433mhz transmitter (FS1000A)

The library I am using is the Manchester library GitHub.
The attiny85 and the transmitter are powered with regulated 5V.
I set up 1MHZ when burning the bootloader for the tiny.
I am successful at transmitting with 8 AND 16MHZ with my Attiny85, however, 1MHZ seems to malfunction.
For 1MHZ on the tiny, this line need to be added in order to adjust timings :
man.workAround1MhzTinyCore();

Here is the complete code :
#include <Manchester.h>
/*
  Manchester Transmitter example
  In this example transmitter will send one 16 bit number
  per transmission.
  Try different speeds using these constants, your maximum
  possible speed will depend on various factors like transmitter
  type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
#define TX 2 //pin where your transmitter is connected

uint8_t transmit_data = 11;
void setup() {
  man.workAround1MhzTinyCore();
  //pinMode(RX, OUTPUT);
  man.setupTransmit(TX, MAN_300);
  pinMode(1, OUTPUT);
}
void loop() {
  digitalWrite(1, HIGH);
  man.transmit(transmit_data);
  delay(100);
  digitalWrite(1, LOW);

  delay(200);
}

Someone else has/had this issue Can't transmit on @1MHZ attiny85, and i don't know if it has been fixed or not. I am unsure if the library is still updated, and if this issue isn't with the library itself.
Does anyone have any leads or fix for that issue ?
That would greatly help, Thanks

The comments in the library code suggest, that this is a problem with the core. You can search in the issues of the core on github or open your own issue for it to find out if it is fixed. Though - as you report it not working without the workaround - I don't think it is fixed.  Does the workaround not work for you?

Hi, thanks for answering quickly, no, the workaround does not work for me. Do you mean the core of the tiny library or the core of the Manchester library ?

A core in the Arduino world is the support package for specific groups of boards/microcontroller (as installed from the board manager). So it is the Tiny core and the Manchester library, not vice versa. So yes, with core I mean the Tiny core (or whatever core you have installed for the Attiny)

The linked issue of the Manchester library also states, that calls to delay() does not work correctly (a value of 5000ms giving only 1s delay). Does this also happen for you? Please also test delayMicroseconds() since that is the function used in the Manchester library

Ok thanks for the tip, I managed to test it and it would seem to be working correctly, I get approximately 5 seconds every time, with delay() and delayMicroseconds()

I see this was 9 months ago, are you still working with this project? If so, did you locate any further information on the Manchester library. The link “Full details available on the Arduino Manchester Encoding site” is no longer working. Thanks,
Rc

Ok funny story, I think I found a solution, not sure why, but :
My setup (the same) :

Attiny85 (1MHZ (set on bootloader))
Cheap 433mhz transmitter (FS1000A)
Attiny microcontrollers library

When burning the bootloader with 1MHZ, and uploading sketch, it would seem that removing the line man.workAround1MhzTinyCore(); makes it work.
Without the line it's working, and with the work around it is NOT
Voila !


text:
A4988 Jitter on stepper motor, some of the time
Hardware:

Arduino Uno Rev3
A4988 Driver
Nema 8 Stepper

Setup:
I've adjusted the VRef of the driver based on the formula VRef = Imot * 8 * Rsen. With the values of Imot = .5 (max = .6), Rsen = .068.
A 12-Volt power supply is being used to supply power to the breadboard hat for the Arduino.
The Arduino code is being activated by a Python GUI, that is sending commands to the Arduino to make adjustments to the code in order to manipulate delay between steps, step size, and enable/disable. here is a simplified version of the Arduino code.
#include "src/Laser_Welder_8124.h"

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

    pinMode(STEPPER_DIR, OUTPUT);
    pinMode(STEPPER_STEP, OUTPUT);

    pinMode(STEPPER_ENABLE, OUTPUT);
    pinMode(STEPPER_MS1, OUTPUT);
    pinMode(STEPPER_MS2, OUTPUT);
    pinMode(STEPPER_MS3, OUTPUT);

    digitalWrite(STEPPER_MS1, HIGH);
    digitalWrite(STEPPER_MS2, HIGH);
    digitalWrite(STEPPER_MS3, HIGH);

    digitalWrite(STEPPER_DIR, HIGH);
    digitalWrite(STEPPER_ENABLE, HIGH);
}

void loop() {

    curMillis = millis();
    commsCheck();
    singleStep();
}

void commsCheck(){

    if(Serial.available() > 0){

        int rlen = Serial.readBytes(incomingMsg, MSGSIZE);
        byte cmd = incomingMsg[CMD_POS];

        int val = incomingMsg[VAL_POS];

        switch(cmd){
            case 0xC0:{
                enableStepperMotor(val);
                break;
            }
            case 0xC1:{

                toggleStepperDirection(cmdLookup[2].pin, val);
                break;
            }
            case 0xC2:{

                cmdLookup[0].state = val;
                millisBetweenSteps = val;

                break;
            }
            case 0xC7:{

                setStepSize(val);
                break;
            }
        }
    }
}

void setStepSize(int val){

    switch(val){
        case 0xD0:{
            stepSize(HIGH, HIGH, HIGH);
            break;
        }
        case 0xD1:{
            stepSize(HIGH, HIGH, LOW);
            break;
        }
        case 0xD2:{
            stepSize(LOW, HIGH, LOW);
            break;
        }
        case 0xD3:{
            stepSize(HIGH, LOW, LOW);
            break;
        }
        case 0xD4:{
            stepSize(LOW, LOW, LOW);
            break;
        }
    }
}

void stepSize(int MS1, int MS2, int MS3){
    digitalWrite(STEPPER_MS1, MS1);
    digitalWrite(STEPPER_MS2, MS2);
    digitalWrite(STEPPER_MS3, MS3);
}

void toggleStepperDirection(int pin, int val)
{

    if (val == 0){
        cmdLookup[1].state = CW;
        digitalWrite(STEPPER_DIR, LOW);
    }
    else{
        cmdLookup[1].state = CCW;
        digitalWrite(STEPPER_DIR, HIGH);
    }
}

void singleStep() {

    if (curMillis - prevStepMillis >= millisBetweenSteps) {

        prevStepMillis = curMillis;
        digitalWrite(STEPPER_STEP, HIGH);
        digitalWrite(STEPPER_STEP, LOW);
    }
}

This works, for the most part.
I'm using the GUI to pass a value from 1-255 to represent a delay between steps in milliseconds.
If I set the time between steps to 1 ms, then it runs smoothly on all step sizes. However, when I start to play with the time delay, I get all sorts of jitter, at different time delays with different step sizes. How do I go about smoothing out the motor so I can use a range of delays across different step sizes?
I've attached a video link to show you what I'm seeing.
Video Link of motor behavior


text:
Arduino 3.3v pro mini, most efficient use of AA batteries for power
I want to use a 3.3V pro mini that uses a BME 280 to take temp/pressure/humidity, and nRF24L01 module to transmit the data, at ?10 minute intervals. I want to use 1, 2,3 or 4  AA batteries to power it. I've read all about the techniques to reduce power consumption, by removing the power LED and using sleep functions.
But I would like to know the most efficient combination of batteries to use. If I can get a year out of 1 battery and a step-up converter, I would be happiest with that. But perhaps 3 duracell or 4 (rechargeable) batteries  connected directly to the Vcc pin (ie no regulator) might be better. Does anyone have first-hand experience to know what works best?

You can definitely do better with another regulator that the on-board ones, which are not energy efficient because they drop the supply voltage through a resistance, wasting the excess current as heat. An external boost regulator would waste much less current (charge, really, since we're trying to make maximum use of the battery capacity, or equivalently, trying to minimize the capacity & space needed to run your system for a year).
So you need two things:

The most space-efficient way (I assume...) to store a year's energy needs; and
A pretty good idea of what the energy requirement will be.

For (2.), you'll need an energy budget for your system:

How much current your system draws when it is awake;
How much current your system draws when it is asleep;
It's duty cycle (e.g.: 3% awake time, 97% sleep time), and use that to calculate the total charge in milliAmp-hours the system draws during the 1 year.

Don't forget to account for the batteries' inefficiency when they're cold, if that will be an issue, and add in a safety factor so it won't die before you arrive a year hence to change the batteries.
You'll need to consider powering down the sensor(s) and radio(s) during CPU sleep; their idle draw would make sleeping the CPU ineffective (as far as saving battery is concerned).
Once you have an energy budget, you can look at the available ways to store and deliver a year's worth - regulator type, size and efficiency; battery size and count) to see what combination will meet your needs for cost, simplicity, and space limitations.


text:
Stepper motor not working with A4988 driver
I have been trying to run stepper motor via Arduino Uno and A4988 motor driver via this tutorial: https://howtomechatronics.com/tutorials/arduino/how-to-control-stepper-motor-with-a4988-driver-and-arduino/
The schematic for my wiring:
So far I have checked the connections multiple times, tried different Arduino boards and A4988 drivers, even tried using a DRV8825 driver, manually declaring HIGH for SLEEP and RESET pins and LOW for ENABLE via arduino. Checked with several batteries which show no problem, even had a friend check the motors via other different driver(YS-DIV268n) he had and the motors worked fine.
I even tried increasing the current from driver via the potentiometer on it but none of these worked.
All this time I observed that the driver got hot quite a lot and that's it.
The arduino code is as follows:
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */

// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
void loop() {
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000); // One second delay

  digitalWrite(dirPin,LOW); //Changes the rotations direction
  // Makes 400 pulses for making two full cycle rotation
  for(int x = 0; x < 400; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000);
}```

In your for loops you have 2 delays each 500us, so 1ms per step. You are doing this for 200 steps, so each for loop would take 200ms, so only 1/5 of a second (ignoring the execution time of digitalwrite). Have you tried changing the numbers a bit? Using higher delays and doing more steps?

test the driver standalone ... remove the arduino ... use switches to control STEP and DIR


text:
6 ST7735 screens not working at same time with Pico
Hello i have a question for you. I have 6 St7735s screen 0.96 ınch. I connect them to my Raspberry pi pico. I want to show them some text but they are showing at the same time. First screen start working and shows "Screen 1 Test" and then its close. After that second screen start working and show "Screen 2 Test" and its close again and it goes to last screen and it show "Screen 6 test" and not closing. But the rest of it stay close. I use same connection for GND - VCC - SCL - SDA - RES - DC pins. Only Cs pin is diffrent. Any advice for me?
The code that i used :
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>

#define TFT_CS1 2
#define TFT_CS2 3
#define TFT_CS3 4
#define TFT_CS4 5
#define TFT_CS5 14
#define TFT_CS6 15
#define TFT_DC 9
#define TFT_RST 7

Adafruit_ST7735 tfts[] = {
  Adafruit_ST7735(TFT_CS1, TFT_DC, TFT_RST),
  Adafruit_ST7735(TFT_CS2, TFT_DC, TFT_RST),
  Adafruit_ST7735(TFT_CS3, TFT_DC, TFT_RST),
  Adafruit_ST7735(TFT_CS4, TFT_DC, TFT_RST),
  Adafruit_ST7735(TFT_CS5, TFT_DC, TFT_RST),
  Adafruit_ST7735(TFT_CS6, TFT_DC, TFT_RST)
};

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

  for(int i = 0; i < 6; i++){
    tfts[i].initR(INITR_MINI160x80);
    tfts[i].setRotation(3);
    tfts[i].fillScreen(ST7735_BLACK);
    tfts[i].setTextColor(ST7735_WHITE);
    tfts[i].setTextSize(2);
  }
}

void loop() {
  for(int i = 0; i < 6; i++){
    tfts[i].setCursor(0, 0);
    tfts[i].println("Screen " + String(i+1) + " test");
    delay(1000);
  }
}

what happens if you iterate through the screens in a descending order?

I didnt understand but if i lower delay time it still working same

go through the screens in the 6, 5, 4 order

You might want to have separate reset pin for each, it probably resets all displays and initialize one of them.

Or you can try if it's possible to configure only first object with TFT_RST and the rest with -1 instead. But it might be checked somewhere.


text:
Communication with scale via rs232
I need help with an Arduino project. I want to read values from a TCS150 scale using the serial port. The hardware I have is an UNO R3 board and a MAX3232 level converter.
I have connected:
MAX3232 power supply - 5V from UNO R3
TX -> D10
When checking the voltage on the TX cable connected to UNO, it varies between 3.5V and 4.2V, so there shouldn't be any connection problem. I tried to upload a simple program as shown in the picture, but I can't receive any values So far, I haven't found a solution. The incoming data when I plugged in scale to computer via Putty is correct. Do you know where I might have made a mistake in connecting or programming the Arduino?
Program:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,-1);  // -1 if not using TX to save a pin

void setup()
{
   Serial.begin(9600);
   Serial.println("<Arduino is ready>");
   mySerial.begin(9600);
}

void loop()
{
  if(Serial.available()) {
    Serial.println("serial available");
  } else {
    Serial.println("serial not available");
  }

  if(mySerial.available()) {
    Serial.println("myserial available");
  } else {
    Serial.println("myserial not available");
  }
  string x = mySerial.readString();
  Serial.println(x);
  delay(1000);
}

The output is:
-> serial not available
-> myserial not available
-> ? (question mark in rhombus)

Quick comment:  It looks like you are trying  to open a hardware serial port and a software serial port.  Two serial ports!  Is that what you really wanted to do?

@st2000 I think Konrad wants to read from a scale TCS150 and forward the reading to the Arduino Terminal. So both channel are required. The Serial.available if statement is not needed, there is no writing from the terminal to the Arduino. I would do it like if (myserial.available()){ Serial.write(myserial.read()); }.  And delete the rest of the code in the loop() routine.


text:
MPU 6050 Pitch and Roll values bouncing back to zero
I wired an MPU 6050 to an Arduino Pro Micro:

...and installed the MPU 6050 library by Electronic Cats in the Arduino IDE.
I used the IMU_Zero sketch to capture the acceleration and gyro offsets. I then punched the offset numbers into the MPU6050_DMP6 sketch and uploaded to the board.
So far this is the same procedure explained in this video:
https://www.youtube.com/watch?v=7879Oe71-dY
In the serial monitor I am getting the values for yaw, pitch and roll. Yaw drifts over time, but pitch and roll remain close to zero.
When I move the device to test roll and pitch, the output changes accordingly, but as soon as I stop moving the device, values for pitch and roll change decrease of increase rapidly until they return to zero. It is as if there is a bouncing effect.
I see the same behaviour using the GetAngle sketch from the MPU6050_light library.
This is not the behaviour I see in the video above and several others and I am trying to understand why this is happening and how to fix it. Does anyone have a clue?

There has been 1 open issue (for years now) at the github repository you have chosen for the 6050 driver software regarding a FIFO running out of data and returning zero.  Perhaps you might find an answer there.

When you stop moving the device, do you lay it flat? If so, this may be intended behavior.

No, I move the device to a different position and it remains in that position. Yaw value reflects the movement and holds the new position. Pitch and roll do not.

Your results are unexpected.  Normally Yaw is not something derived from only an accelerometer and gyroscope unless the user is accepting of accumulated errors.  Normally, dependable and steady Yaw requires the user to add a magnetometer. Please check your project's hardware, wiring, power supply, software against working example projects.

Are you aware that gyroscopes measure angular velocity, not orientation? A gyro reads zero if it's lying around. The video doesn't tell much as you don't see the actual movement of the sensor... Though, I'd certainly expect the same behaviour for all three axes...

You are correct. It is supposed to go back to zero. Actual angles need to be calculated using values from the accelerometer. After doing some more research and testing, I realized my accelerometer is outputting fixed values: 1G for the Z axis, and 0G for the X and Y axes. The values do not change when I tip the board. I used the method described in the video below to test:
https://www.youtube.com/watch?v=7VW_XVbtu9k
I have found posts from other people complaining about the high rates of defects on these boards and right now I'm 99% convinced I have a bad board.

Sketch used for my test: https://github.com/CarbonAeronautics/Part-XIV-MeasureAngles


text:
What's Memory Allocation technique in Arduino
I am currently working on an assignment for my embedded systems course, and my professor has asked us to determine the memory allocation technique employed in Arduino. Specifically, I need to identify whether it utilizes best fit, quick fit, worst fit, next fit, or first fit memory allocation methods.
Despite conducting online research and seeking input from my colleagues, We have been unable to find an answer to this question.
I would greatly appreciate any insights or information on the memory allocation technique used in Arduino.
Thank you.

https://www.nongnu.org/avr-libc/user-manual/malloc.html

Use the source, Luke!
The AVR-based Arduinos rely on the avr-libc library, which provides
malloc() and friends. You can read the source code online.
It is generously commented, and you can understand pretty well the
allocation strategy by reading the comments alone.

Long answer short, it used both first-fit and best-fit.
The malloc function in the avr-libc makes use of a so-called free list to track the free spaces in the memory.
When there is a memory request, it starts by looping over this list searching for the first exact match [First Fit].
While looping over the list, it keeps track of the piece of memory that will leave the least amount of space(best-fit). If it didn't find the exact match, it uses this piece of memory [Best Fit].
Furthermore, it doesn't use this piece of memory directly, it checks for its size first, if it is big enough, it takes the amount of memory needed and adds the leftover to the free list, else, it allocates the whole piece of memory.
N.B. it allocates new memory space to the heap if it doesn't find the first-fit or best-fit.

Example Scenarios:

First Fit:

Free list: [64, 128, 128, 256, 512, 128]
Request: 128
Action: Take the first 128.

Best Fit:

Free list: [64, 256, 512]
Request: 128
Action: Take the 256, use 128, and add the other 128 to the free list.

Best Fit:

Free list: [64, 256, 512, 130]
Request: 128
Action: Take the 130 and use it all.

Hope things are clear now!


text:
Atmega 328pu on breadboard. What to choose in order to upload code with ftdi converter
When I program atmega328 PU on breadboard,vwhat programmer do I have to use and what arduino board type I have to choose? I am trying this with ftdi converter I have already done the connections and it's okay but there's an error when I'm trying to upload the code either with instant upload either with the programmer. Everything can help is acceptable and thanks in advance for your support.

Does your ATmega have the Arduino bootloader?

I have a number of atmega328-PU-on-breadboards. I build them with a 16MHz crystal and load the Uno Optiboot loader if they don't already have a bootloader installed. I program them with an FTDI USB to TTL Serial 5V Adapter Cable 6 Pin 0.1 inch Pitch Female Socket Header UART IC FT232RL Chip (or the 3.3v version of the same cable, if I built for 3.3v). By using a 16 MHz crystal and a standard bootloader, I can select 'Uno' as the board type in the IDE and everything works. On the board, I build a 6-pin header to accept the cable's 6-pin female header I use connect it for for uploading and/or viewing debug output on the board's serial port, but otherwise remove it and power the board through a more compact micro-USB connector. You could always make a more permanent connection between your board and the USB-FTDI cable if you find that more suitable.
Update:

what programmer do you choose ? Also can you share your pinout ?

My programmer is avrdude, run by the IDE. My boards program exactly like an Uno.
Pinout:
.
The CTS output (brown wire) is unused; the RTS output is wired connected to the reset pin through a 0.1uF capacitor, if you want the auto-reset feature. If you are using a different FTDI device, you will, of course, have to use it's particular pinout but it should provide the same signals and behavior.
This is the reset circuit I use on my board (crudely drawn but gets the point across):

Its ok ,but what programmer do you choose ? Also can you share your pinout ? Thanks in advance

There are quite a few questions here about breadboard computers. Try searching this site for "breadboard". I also have a page about making a breadboard Arduino which might help.
Normally I would set the Arduino type to Uno if the breadboard computer has a 16 MHz oscillator or crystal on it. If you are running at 8 MHz (possibly with the internal oscillator) I would set it to Lilypad.
If the chip doesn't have a bootloader on it then you need to install that first. I have a page about installing a bootloader which might help.
To install the bootloader you need to use an SPI interface as described on the above page. That requires running 6 wires from an existing (working) Arduino to your breadboard.

it's okay but there's an error when I'm trying to upload the code

It's OK? But there's an error? What error message?

I will try this next days. Although we have a different ftdi converter. I have a red one with the ft232rl chip. Thanks for help. If I can't achieve it after this i will come back again. Thank you


text:
if statement does not work with fraction, but works with decimal equivalent
I'm trying to trouble shoot a problem with my code and narrowed it down to my if statement not working with a fraction.
The below code does not work and returns 0
for(float i=0; i <= 1; i += .0001){
 t += .0001;
 if(t >= 1/440){ //Fraction
   t = 0;
 }
 Serial.println(t*100);
 delay(100);
}

But when I replace the 1/440 with its decimal equivalent (.0022727) it works fine and counts from 0 to 2.2
for(float i=0; i <= 1; i += .0001){
 t += .0001;
 if(t >= 0.0022727){ //Decimal
   t = 0;
 }
 Serial.println(t*100);
 delay(100);
}

If there is a simple way to use a fractional value instead of a decimal value it would make my application much similar.
Thanks.

Always present float calculations like this 1.0/440.0 and not 1/440 to prevent  these being treated as integer calculations. Avoid using floats in comparisons especially '==' comparisons.

@6v6gt  Please read When shouldn't I comment?. If you aren't requesting clarification from the author (or the other couple of reasons to comment on the question) then you should be posting an answer instead.

@6v6gt You may want to look at this. I don't know if it will matter being as old as it is, but you could weigh in on it if you have the interest; I don't. But I would them to make up their minds about it.

@NickGammon One problem with giving a formal answer in such a borderline off topic case (this one could fail if the often applied test "non-Arduino specific" is applied and it does anyway have a general C/C++ look to it) is that the answerer risks losing a couple of Brownie points if someone decides to assert that it is off topic and starts down-voting both the question and the answer.  Some answers which I have put considerable effort into, and the OP could not have known that the solution to the problem was "Non-Arduino specific", have ended up with a -1 score.

@6v6gt Yeah, I agree. I try to ignore the occasional down-vote as there are people who like to nitpick that sort of stuff. It's true it's really a programming question, but we do have a programming tag after all, so I think programming questions are OK. Especially if beginners to Arduino maybe think that the Arduino has different rules to C++.

"The process of designing and writing source code as part of a program (or sketch) for Arduino." It is not clear that this applies to the question asked nor the answer given. Nor that it isn't in conflict with "If the solution would be the same with or without Arduino, then it's usually a general coding question". I don't disagree with your desire to answer it here. But your thinking is not evidently supported by the rules where it isn't evidently not supported by the rules.

1/440 will be treated as an integer expression, returning zero.
To make it work, make one or both operands a floating-point type. In your case:
 if(t >= (float)1 / 440){ //Fraction
   t = 0;
 }

Or:
 if(t >= 1.0/440){ //Fraction
   t = 0;
 }


text:
FreeRTOS is not solving my problem to run tasks parallelly
I'm pretty new to esp32 and I'm trying to combine two codes in one, they are simple codes from projects that I found online, the first one uses PIR sensor to send message to telegram each time motion is detected, second code uses RFID to open door lock. When I tried directly merging the two codes together the esp32 went crazy on serial monitor and nothing worked even the WIFI failed to connect.
Then I tried creating task for each one using freeRTOS and I did it like this:
task1: for Wifi connection running on CORE 0 //wifi function is taken from sketch 1
task2: for RFID and door lock running on CORE 1 //taken from sketch 2
task3: for motion detection and sending telegram message running on CORE 0 //taken from sketch 1
Again esp32 went crazy when I opened serial monitor and it gave me this error:" Guru Meditation Error: Core  1 panic'ed (IllegalInstruction). Exception was unhandled. "
I have no clue why is this happening, does it really require RTOS to combine the two sketches and run them at the same time, or a simple delays and if statements would solve the problem? I need some help please.
Sketch 1: Motion detection from enter link description here
/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/telegram-esp32-motion-detection-arduino/

  Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "XXXXXXXXXX"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

const int motionSensor = 27; // PIR Motion Sensor
bool motionDetected = false;

// Indicates when motion is detected
void IRAM_ATTR detectsMovement() {
  //Serial.println("MOTION DETECTED!!!");
  motionDetected = true;
}

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

  // PIR Motion Sensor mode INPUT_PULLUP
  pinMode(motionSensor, INPUT_PULLUP);
  // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  bot.sendMessage(CHAT_ID, "Bot started up", "");
}

void loop() {
  if(motionDetected){
    bot.sendMessage(CHAT_ID, "Motion detected!!", "");
    Serial.println("Motion Detected");
    motionDetected = false;
  }
}

Sketch 2: RFID door lock from enter link description here
/*
 * This ESP32 code is created by esp32io.com
 *
 * This ESP32 code is released in the public domain
 *
 * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-rfid-nfc-door-lock-system
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN    5  // ESP32 pin GIOP5
#define RST_PIN   27 // ESP32 pin GIOP27
#define RELAY_PIN 22 // ESP32 pin GIOP22 connects to relay

MFRC522 rfid(SS_PIN, RST_PIN);

byte keyTagUID[4] = {0xFF, 0xFF, 0xFF, 0xFF};

void setup() {
  Serial.begin(9600);
  SPI.begin(); // init SPI bus
  rfid.PCD_Init(); // init MFRC522
  pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output.
  digitalWrite(RELAY_PIN, HIGH); // lock the door

  Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");
}

void loop() {
  if (rfid.PICC_IsNewCardPresent()) { // new tag is available
    if (rfid.PICC_ReadCardSerial()) { // NUID has been readed
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

      if (rfid.uid.uidByte[0] == keyTagUID[0] &&
          rfid.uid.uidByte[1] == keyTagUID[1] &&
          rfid.uid.uidByte[2] == keyTagUID[2] &&
          rfid.uid.uidByte[3] == keyTagUID[3] ) {
        Serial.println("Access is granted");
        digitalWrite(RELAY_PIN, LOW);  // unlock the door for 2 seconds
        delay(2000);
        digitalWrite(RELAY_PIN, HIGH); // lock the door
      }
      else
      {
        Serial.print("Access denied, UID:");
        for (int i = 0; i < rfid.uid.size; i++) {
          Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
          Serial.print(rfid.uid.uidByte[i], HEX);
        }
        Serial.println();
      }

      rfid.PICC_HaltA(); // halt PICC
      rfid.PCD_StopCrypto1(); // stop encryption on PCD
    }
  }
}

No, you don't need an RTOS to do something simple like:
if (motionDetected)
    open_the_door ();

You basically have two loops:
void loop ()
  {
  if (motionDetected)
      send_a_message_to_open_the_door ();
  }

And:
void loop ()
  {
  if (message_received_to_open_the_door)
     open_the_door();
  }

So, you combine them into a single loop:
void loop ()
  {
  if (motionDetected)
     open_the_door();
  }

I'll leave you to make the actual code changes.


text:
Why Did I Have To Program Duemilanove Bootloader?
As a volunteer for Public Invention, I have developed an Atmega328 based design in which I thought I was largely duplicating the Arduino UNO.
Unlike the UNO, I did choose a CH340 USB to UART chip as that was a part on some UNO clones I have purchased.
Our project, the General Alarm Device, is at:
https://github.com/PubInv/general-alarm-device
In the summer of 2022 We built up 15 Verion 1 assemblies.
When we went to put boot loader into them we found we could put the Duemilanove bootloader but not the UNO.  We do not know why.
Even with the Duemilanove bootloader we from time to time have problems uploading code. Some times the IDE reports a problem but the code uploaded.  And perhaps some times we had to try to load more than once.
Here is an issue written up after one user had some difficulty with firmware upload:
https://github.com/PubInv/general-alarm-device/issues/127
Related questions,
Is their a way to check which boot loader is in a board?
Could our root problem have been due to which boot loader was on the UNO we were using as the ICP?

the difference is the upload baud rate. Duemilanove bootloader uses much slower baud rate. you have some problem with the USB to TTL Serial circuit

Hello Juraj,  Can you point me to documentation for these baud rates. For what should I google?

see the boards.txt file for the AVR platform. (or read in the IDE console the  parameters of the upload command)

Related questions, Is their a way to check which boot loader is in a board?

I wrote some code to detect chip signatures a while ago which also reports on known bootloaders: http://www.gammon.com.au/forum/?id=11633
It really is too long to post here. The code however is at https://github.com/nickgammon/arduino_sketches in particular in the Atmega_Board_Detector folder.
It's the same processor chip, you shouldn't have problems uploading, provided you use the appropriate clock speed and baud rate.
See my answers here:

Have I bricked my Arduino Uno? Problems with uploading to board

What happens when code is uploaded using the bootloader?

Where do I learn what is appropriate?

Well, the bootloaders have hard-coded into them the speed at which they expect the serial data to arrive. In the case of Optiboot it is 115200 baud, some other bootloaders may use 9600, 57600 or other speeds.
Now this baud rate is also dependent on the clock rate of the processor, because the baud rate is derived from the system clock.
So for example, on a Uno, Optiboot "expects" (in the sense that a computer can expect anything) that it will be running on a board at 16 MHz, and that the communication will be at 115200 baud.
So, if you are running at 8 MHz (half that speed) then the baud rate will naturally be 57600. However you can compensate for that by editing the file boards.txt in your Arduino installation and changing the baud rate, eg.
uno.name=Arduino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

Change the line "uno.upload.speed" to read 57600 in this case. That way the program (avrdude) which uploads to the board will upload slower, and since you are running at a slower speed, all will be well.

So, to make it all work:

Find which bootloader you have (by comparing signatures) or simply upload a new bootloader of a known type. I have a page about uploading bootloaders which might help you there.

Look up (eg. in that file) what the baud rate this particular bootloader uses (eg. 115200 for Optiboot).

Set your processor to run at that clock speed with a crystal or resonator. (see the line "uno.build.f_cpu" which is 16000000 in this case).

If you choose to run the processor at a different speed (eg. using the internal clock, at 8 MHz) then either use a bootloader designed for 8 MHz, or change the upload speed baud rate line in the file as mentioned above. I suggest copy/pasting an existing entry, changing for example "uno" at the start of each line to "myboard" or something like that, and the "name" line as well, so it will appear in the drop-down menu of available boards).

Hello Nick,  Thanks for the link to the code I hope to try it soon.   Regarding "provided you use the appropriate clock speed and baud rate."  Where do I learn what is approprate. That is what I am asking about here. I am not afraid to read docuementation but have no idea the key words for which to search.

@ForrestErickson See amended answer.


text:
Working with pulseIn() and millis()
I'm trying to use pulseIn with elapsed time using millis(), I don't want to use interrupts instead of pulseIn (I need pulseIn because I need accurate pulse time), the elapsed time doesn't need to be very accurate, so to calculate the elapsed time I've added to the elapsed time the time the arduino is blocked, The problem is the calculated elapsed is very inaccurate, I suspect it sometimes never enters if(elapsed > 1000*60*2), Why is that? How can I fix that?
Thanks.
Code
unsigned long startTime = 0;
unsigned long elapsed = 0;
unsigned int val = 0;
uint32_t time_wait_pulse = 0;

void setup(){
  startTime = millis();
}

void f(){
  uint32_t time = 0;
  time += pulseIn(pin, LOW);
  if(time > 0) {
   ...
   time_wait_pulse += time;
  } else {
   time_wait_pulse += 1000000; //default pulseIn timeout (micros)
  }
}

void loop(){
    elapsed = millis() - startTime + (unsigned long)(time_wait_pulse/1000);
    if(elapsed > 1000*60*2){
      val++;
      startTime = millis();
      time_wait_pulse = 0;
    }

     noInterrupts();
     f();
     interrupts();
}

millis() is using interrupts to work. When deactivating interrupts for your function f(), you prevent that the value returned by millis() can actually change in that time.
So if the interrupt associated with millis() occurs during the execution of f(), you will lose time in your measurement and it will be inaccurate. It will get worse the more time the code spends with interrupts off vs on. micros() will still be updated without interrupts on (since it directly reads the register of Timer0), but it will still lose time after about 500ms, since then it cannot compensate for multiple overflows in that time period.
The way to go forward depends on your requirements. Is it really needed, that you disable interrupts for the pulseIn() measurement? What accuracy do you get in both cases (interrupts on vs off) and what accuracy do you need? If you absolutely need to turn off interrupts, only do it for the shortest time (only around pulseIn()). You can built your own time keeping analog to millis() using a 16bit Timer (you didn't specify what Arduino you are using), which would give you way more time, that the microcontroller can spend without interrupts on before loosing time in the measurement.You can also use a different prescaler to further increase this time, though sacrificing precision for it.

You can time reasonably long intervals using Timer 2 (on the Atmega328) as described in my page about timers.
The example there is this:
void startTimer1 ()
  {
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  // zero it
  TCNT1 = 0;
  TIFR1 |= bit (TOV1);  // clear overflow flag
  // start Timer 1
  TCCR1B =  bit (CS10) | bit (CS12);  //  prescaler of 1024
  }  // end of startTimer1

unsigned long getTimer1Reading ()
  {
  unsigned long elapsed = TCNT1;
  if (TIFR1 &  bit (TOV1))
     elapsed += 65536;
  return elapsed;
  }  // end of getTimer1Reading

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

  }  // end of setup

void loop ()
  {
  Serial.println ("Starting ...");
  Serial.flush ();

  startTimer1 ();

  delay (7560);
  float secs = (1.0 / F_CPU * 1024) * getTimer1Reading ();

  Serial.print ("Time taken = ");
  Serial.print (secs);
  Serial.println (" seconds.");

  } // end of loop

The code above uses Timer 1 to time an interval up to 8.388 seconds. It users a prescaler of 1024, which means each "count" of timer 1 is 1/16e6 * 1024 of a second (0.000064 seconds, or 64 µs). Since it can count up to 65536 we can time 0.000064 * 65536 = 4.194304 seconds. Then the timer overflows, but we can test the "overflow flag" and know the overflow occurred. That lets us time up to 8.388608 seconds before we miss the fact that there was a second overflow.
This code works even if interrupts are off, because the timing is done by the hardware timer.
Output on my Uno:
Starting ...
Time taken = 7.56 seconds.


text:
Using 2 VL53L4CD ToF sensors and getting error after getting first reading
pretty new to arduino stuff and was hoping to get some help with my code.
I'm trying to use 2 ToF sensors and get continuous readings from them. I understand that I have to use the xshut feature and switch them on and off to alternate them but I'm stuck in an error loop and I'm not quite sure where to go from here. Does anyone know what's going on and how to solve this?
Here's my code:
/* Includes ------------------------------------------------------------------*/
#include <Arduino.h>
#include <Wire.h>
#include <vl53l4cd_class.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <WiFi.h>
//#include <ESPAsyncWebServer.h>
#define DEV_I2C Wire
#define SerialPort Serial
char report[64];
//address we will assign if dual sensor is present
uint8_t sensor1add = 0x30;
uint8_t sensor2add = 0x31;
// set the pins to shutdown
#define xshut1 A0
#define xshut2 A1
#define GFX_BL DF_GFX_BL
//this holds the measurement
VL53L4CD_Result_t results1;
VL53L4CD_Result_t results2;
float sensor1, sensor2;
//Components.
VL53L4CD sensor1_vl53l4cd_sat(&DEV_I2C, A0);
VL53L4CD sensor2_vl53l4cd_sat(&DEV_I2C, A1);
//init Wifi
/*void initWifi(){
    Serial.print("Setting AP (Access Point)...");
  // No password
  WiFi.softAP (ssid);
  // Start WiFi Access Point
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.print(IP);
    // Print ESP8266 Local IP Adress
  Serial.println(WiFi.localIP());
}*/
//init sensors
void initSensor(VL53L4CD sensorX, uint8_t sensoradd)
{
  // Init sensor1
  //Set sensor address.
  sensorX.VL53L4CD_SetI2CAddress(sensoradd);
  // Configure VL53L4CD satellite component.
  sensorX.begin();
  // Switch off VL53L4CD satellite component.
  sensorX.VL53L4CD_Off();
  //Initialize VL53L4CD satellite component.
  sensorX.InitSensor();
  // Program the highest possible TimingBudget, without enabling the
  // low power mode. This should give the best accuracy
  sensorX.VL53L4CD_SetRangeTiming(200, 0);
  sensorX.VL53L4CD_SetOffset(-10);
  // Start Measurements
  sensorX.VL53L4CD_StartRanging();
}
//getSensor1Reading
void getSensor1Reading(uint8_t status, uint8_t NewDataReady)
{
  sensor1_vl53l4cd_sat.VL53L4CD_On();
  Serial.println("Sensor 1 is on");
  if ((!status) && (NewDataReady != 0)) {
    // (Mandatory) Clear HW interrupt to restart measurements
    sensor1_vl53l4cd_sat.VL53L4CD_ClearInterrupt();
    // Read measured distance. RangeStatus = 0 means valid data
    sensor1_vl53l4cd_sat.VL53L4CD_GetResult(&results1);
    snprintf(report, sizeof(report), "Status = %3u, Distance = %5u mm, Signal = %6u kcps/spad\r\n",
             results1.range_status,
             results1.distance_mm,
             results1.signal_per_spad_kcps);
    sensor1 = results1.distance_mm;
    Serial.println((String)"This is Sensor1 " + (float)sensor1 + (String)"mm");
  }
  sensor1_vl53l4cd_sat.VL53L4CD_Off();
}
//getSensor2Reading
void getSensor2Reading(uint8_t status, uint8_t NewDataReady)
{
  sensor2_vl53l4cd_sat.VL53L4CD_On();
  Serial.println("Sensor 2 is on");
  if ((!status) && (NewDataReady != 0)) {
    // (Mandatory) Clear HW interrupt to restart measurements
    sensor2_vl53l4cd_sat.VL53L4CD_ClearInterrupt();
    // Read measured distance. RangeStatus = 0 means valid data
    sensor2_vl53l4cd_sat.VL53L4CD_GetResult(&results2);
    snprintf(report, sizeof(report), "Status = %3u, Distance = %5u mm, Signal = %6u kcps/spad\r\n",
             results2.range_status,
             results2.distance_mm,
             results2.signal_per_spad_kcps);
    sensor2 = results2.distance_mm;
    Serial.println((String)"This is Sensor2 " + (float)sensor2 + (String)"mm");
  }
  sensor2_vl53l4cd_sat.VL53L4CD_Off();
}
/*void offset()
{
}*/
/* Setup ---------------------------------------------------------------------*/
void setup()
{
  // Initialize serial for output.
  SerialPort.begin(115200);
  SerialPort.println("Starting...");
  // Initialize I2C bus.
  DEV_I2C.begin();

  initSensor(sensor1_vl53l4cd_sat, sensor1add);
  initSensor(sensor2_vl53l4cd_sat, sensor2add);
}
void loop()
{
  uint8_t NewDataReady1 = 0;
  uint8_t NewDataReady2 = 0;
  uint8_t status1;
  uint8_t status2;
  do {
    status1 = sensor1_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady1);
    status2 = sensor2_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady2);
  } while (!NewDataReady1 || !NewDataReady2);
  getSensor1Reading(status1, NewDataReady1);
  getSensor2Reading(status2, NewDataReady2);
  if (!sensor1_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady1))
  {
    Serial.println((String)"NewDataReady1 is not ready");
  }
  else if (!sensor2_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady2))
  {
    Serial.println((String)"NewDataReady2 is not ready");
  }
  else{Serial.println("New data unable to be parsed");}
}

But I keep getting this error:
--- forcing DTR inactive
--- forcing RTS inactive
--- Terminal on COM9 | 115200 8-N-1
--- Available filters and text transformations: colorize, debug, default, direct, esp32_exception_decoder, hexlify, log2file, nocontrol, printable, send_on_enter, time
--- More details at https://bit.ly/pio-monitor-filters
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H
This is Sensor1 0.00mm
This is Sensor2 30.00mm
[  2883][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3884][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error 263
[  3884][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3886][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3893][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3900][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3907][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3914][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
[  3921][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1


text:
try to send AT commands from Arduino nano to ESP01
I encountered an issue when I try to send AT commands from Arduino nano to ESP01 I tried to find any tutorial for more helps, but I find nothing. please someone can help me.
I tried the tutorial from this link.
https://electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html
But nothing happens when I type AT in serial monitor. I didn't see any response from the ESP module.

maybe the two modules are not connected together

Show your code. There are some errors in the code in the text of the linked article. For example,  here if(a != ‘r’ && a != ‘n’ && (a < 32)) the 'n' should be '\n'  (new line character). Did you notice that the wiring diagram shows the top view of the ESP-01 module, not the underside which nomally you'd make the connections to.

I really connect them together as shown in the diagram on the site and I also already fixed the error in the code then I upload the code in the Arduino but always nothing.

I notice all you say 6v6gt but it's impossible communicate both microcontrollers.

this is my code.
`#include <SoftwareSerial.h>
SoftwareSerial softSerial(3, 2); // RX, TX
void setup()
{
uint32_t baud = 9600;
Serial.begin(baud);
softSerial.begin(baud);
Serial.print("SETUP!! @");
Serial.println(baud);
}
void loop()
{
while(softSerial.available() > 0)
{
char a = softSerial.read();
if(a == '\0')
continue;
if(a != '\r' && a != '\n' && (a < 32))
continue;
Serial.print(a);
}`

the other part of the code here
while(Serial.available() > 0)     {       char a = Serial.read();       Serial.write(a);       softSerial.write(a);     } }

Please put the code in your original question as comments are unsuitable for long pieces of code and it is very difficult to read.
The code does not anyway appear to match the diagram in your linked article. RX of one device should be connected to TX of the other device. Try: SoftwareSerial softSerial(2, 3); // RX, TX note 2&3 intercahnged .


text:
Pass typedef to a function
I'm working with a ESP32S3 that will manage 2 I2S ports, so for the cleanness of my code and also because i'll work multiple I2S installations - deinstallations, i want to move all the functions to and ".cpp .h" file.
something like this

I2S_functions.h
#ifndef I2S_FUNCTIONS_H
#define I2S_FUNCTIONS_H
#include <Arduino.h>
#include <driver/i2s.h>

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,int buf_count, int buf_len, bool apll);

#endif

I2S_functions.cpp

#include "I2S_functions.h"

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,
int buf_count, int buf_len, bool apll)
{
  const i2s_config_t i2s_config =
  {

    .mode = I2S_MODE,
    //.mode = (i2s_mode_t)(I2S_MODE),
    .sample_rate = I2S_SAMPLE_RATE,

    .bits_per_sample = I2S_SAMPLE_BITS,
    .channel_format = I2S_CHANNEL,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),

    .intr_alloc_flags = 0, // default interrupt priority
    .dma_buf_count = buf_count,//cambiado de 8 a 64
    .dma_buf_len = buf_len,
    .use_apll = apll
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}

main.ino

#include "I2S_functions.h"

// I2S config //////
#include <driver/i2s.h>

#define I2S_PORT I2S_NUM_0
//#define I2S_SAMPLE_RATE  (44100)
float I2S_SAMPLE_RATE=44100;
int I2S_SAMPLE_BITS=32;
//#define I2S_SAMPLE_BITS  (32)
#define bufferLen 1024
#define I2S_READ_LEN (16*1024)

void setup ()
{
  i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
I2S_BITS_PER_SAMPLE_32BIT,I2S_CHANNEL_FMT_ONLY_LEFT,I2S_COMM_FORMAT_STAND_I2S,8,bufferLen,false);

}

But when i compile this, i got errors passing the second argument which is "I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE"
a copy from the error:
C:\Users\.ino: In function 'void setup()':
test_10seg_V2:52:39: error: invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]
   i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
                        ~~~~~~~~~~~~~~~^~~~~~~~~~~~
In file included from C:\Users\.ino:2:
C:\Users\I2S_functions.h:6:50: note:   initializing argument 2 of 'void i2s_install(i2s_port_t, i2s_mode_t, float, i2s_bits_per_sample_t, i2s_channel_fmt_t, i2s_comm_format_t, int, int, bool)'
 void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,

exit status 1
invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]

Essentially i have 2 questions. While i looked in the github from the esp32 i found off that there is some typedef of the I2S config (https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/esp32/include/hal/include/hal/i2s_types.h). I've never worked with this type of structs before so i am guessing how should i use it and specially how should i pass this type of variables to a function.
typedef enum {
    I2S_BITS_PER_SAMPLE_8BIT    = 8,            /*!< data bit-width: 8 */
    I2S_BITS_PER_SAMPLE_16BIT   = 16,           /*!< data bit-width: 16 */
    I2S_BITS_PER_SAMPLE_24BIT   = 24,           /*!< data bit-width: 24 */
    I2S_BITS_PER_SAMPLE_32BIT   = 32,           /*!< data bit-width: 32 */
} i2s_bits_per_sample_t;

/**
 * @brief I2S bit width per chan.
 *
 */
typedef enum {
    I2S_BITS_PER_CHAN_DEFAULT        = (0),      /*!< channel bit-width equals to data bit-width */
    I2S_BITS_PER_CHAN_8BIT           = (8),      /*!< channel bit-width: 8 */
    I2S_BITS_PER_CHAN_16BIT          = (16),     /*!< channel bit-width: 16 */
    I2S_BITS_PER_CHAN_24BIT          = (24),     /*!< channel bit-width: 24 */
    I2S_BITS_PER_CHAN_32BIT          = (32),     /*!< channel bit-width: 32 */
} i2s_bits_per_chan_t;

my questions are
1.- I would like to understand how this structs works. I want to clean my code the most that i could, and that mean passing a lot of functions out of the main file. So any resource is well welcome to improve my coding skill.
2.- Why the code fails passing this 2 variables "I2S_MODE_MASTER|I2S_MODE_RX" ?. Is there any special way of passing this variables when are 2 options at once?.
Thanks for your replies!

this is more a general C++ programming question, than it is an Arduino question

https://en.wikipedia.org/wiki/Enumerated_type

Answer to Question 1: The typedef code you posted is enum and not struct. Look up C++ Enumeration and you will find lots of good tutorials. Here is one video.
Answer to Question 2:  You need to typecast the argument for your function to accept it as i2s_mode_t.
i2s_install(I2S_PORT, (i2s_mode_t)(I2S_MODE_MASTER|I2S_MODE_RX), ... ... ...);

i2s_mode_t it is an example of a very bad API design. it should never be an enum.


text:
Using HTTPClient with ESP not working
I have a program running on an esp8266 that attempts to fetch json data from an HTTPS endpoint that is hosted on aws amplify (data comes from a next.js app).
I can retrieve the data correctly when I use WifiClient alone, but when I want to use HttpClient, I get this error:
[HTTP] GET... failed, error: connection failed

This is my code:
void Network::get_data()
{
    if (consumption_data)
        return;

    const char *endpoint = "https://.....";

    wifi_client.setInsecure();
    http_client.setTimeout(10000);

    if (!http_client.begin(wifi_client, endpoint))
    {
        Serial.println("Connection failed");
    }

    // Make the HTTP request
    String payload;
    int http_code = http_client.GET();

    if (http_code == HTTP_CODE_OK)
    {
        payload = http_client.getString();
    }

    else
    {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http_client.errorToString(http_code).c_str());
        return;
    }

    Serial.print("Payload: ");
    Serial.println(payload);

    // Parse JSON response
 }

My class contains these:
    WiFiClientSecure wifi_client;
    HTTPClient http_client;

The endpoint is accessible from postman and doesn't require any auth headers. Any idea what the problem may be?
Thank you

what is the value of http_code?

It starts off as 400. And then -1 for the subsequent requests. The 400 error is the output text I provided above.

Its always best to add more information to the question itself.


text:
Problem compiling sketches for the arduino wavgat uno R33
I am configuring the arduino IDE to be able to compile and upload sketches for the arduino wavgat uno R3. I have installed the Arduino IDE, as well as the required drivers for the board. I also have downloaded the zip containing the "hardware" and "librairies" folder that i copied into the "Arduino" folder.
In the IDE, I can select the wavgat uno R3 as a board and the board is detected by the IDE.
However, when I try to compile any sketch, I get the following error message :
avr-gcc: error: C:\Users\henry\AppData\Local\Temp\arduino\sketches\F2EF7F804783EB75A0A6457CF6D8C244/core\core.a: No such file or directory

exit status 1

Compilation error: exit status 1

I seems to be a problem related to the compilation. Is there something related to the compilation for the wavgat uno R3 that I forgot ?
Thank you in advance

did you try to restart the IDE?

Yes, I even tried to restart the computer altogether.

The problem was solved by using a specific version of the arduino IDE, the 1.8.15. You have to install the drivers and copy the correct driver files in the Arduino folder. The program then compile correctly and can be uploaded to the wavgat.
Also, when working on the wavgat nano, you have to select "WAVGAT UNO R3" as the board type, and not "WAVGAT NANO 3.0" as you might first think.


text:
Uploading code to ESP32 using Arduino OTA
im trying to upload my code to my esp32 through OTA iam able to discover the network port but my code is always failing to upload i donno the reason behind it
#include <WiFi.h>
#include <ArduinoOTA.h>

const char* ssid = "Redmi";
const char* password = "12345678s";
const char* OTA_password = "1234"; // set your own OTA password

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

  // Connect to Wi-Fi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print IP address
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Start OTA update server with authentication
  ArduinoOTA.setHostname("my-esp32");
  ArduinoOTA.setPassword(OTA_password); // set OTA password
  ArduinoOTA.onStart([]() {
    // Disable other tasks that may interfere with OTA update
    Serial.println("OTA update started");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nOTA update finished");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("OTA update progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("OTA update error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("OTA authentication failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("OTA begin failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("OTA connect failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("OTA receive failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("OTA end failed");
    }
  });
  ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();
  // Your other code here
}

above is the code i uploaded to create OTA server
#include <WiFi.h>
#include <ArduinoOTA.h>

const char* ssid = "Redmi";
const char* password = "12345678s";

#define LEDPIN 4

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

  // Connect to Wi-Fi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");

  // Start OTA update server
  ArduinoOTA.begin();
  Serial.println("OTA server started");

  // Initialize LED pin as output
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  ArduinoOTA.handle();

  // Blink LED every second
  digitalWrite(LEDPIN, HIGH);
  delay(1000);
  digitalWrite(LEDPIN, LOW);
  delay(1000);
}

and im trying to upload above blink program through OTA

and above is the error im getting it getting stucked and i have to restart the software everytime to test it. I appreciate if anybody care to explain and help me


text:
Wireless Sensor communication with 100Hz rate
I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

Note, please edit your question in reply

Usually protocols that package up data and test for errors are too slow for real time purposes.  This is why gamers, for example, like using a corded mouse over a wireless mouse.  Unfortunately when you go this route you are usually left with out all the abstractions that make using a common protocol like TCP/IP almost easy.  It is up to you to research this more.  But it sounds like you are entering into the world of serial port radios using simple but very specific proprietary protocols.  And, for all I know, you only need to communicate in one direction.  Which would simplify your hardware.

[edit of my earlier comment, with bps correction] Have you also tried UDP/IP? Lower overhead might make a difference. Although if you aren't getting 5600 bps thruput (ie, 56*100 payload bits) with TCP/IP, probably something's wrong in your setup, which you haven't detailed enough for comment upon. You could provide a Minimal, Complete, and Verifiable example code and part numbers plus name of host computer; could be most of the delay is in the host.

With TCP/IP most of the delay is the act of opening the socket. If you open a socket, send a couple of bytes, then close the socket, yes it is going to take a long time. However, if you open the socket and keep it open then TCP/IP can be quite fast. Over a local network it's as good as a serial connection.

Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.

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


text:
Fan dropping voltage?
I have students using an arduino to control a fan.  We have multiple types of fans. We want to turn the fan off/on with digital HIGH.  When the 5V fan is plugged into 5V and ground, it runs.  When I ground it and attached the power side to a pin set to HIGH the voltage drops down to 2.2V??? When the fan is not plugged into the pin there is 5V.  Why would the power drop when the fan is plugged in?

Most digital pins on Arduinos are qualified to handle up to 25 mA typically and 40 mA at most.  If more current than that is drawn or sunk, the pin voltage will drop or rise, out of specification.  This is due to resistance in the pin drivers, and by Ohm's law, voltage equal to current times resistance will develop.  That “lost” power (voltage times current) is converted to heat within the microcontroller, and can damage it.
The fan motors probably draw rather more than 25 mA; they probably require a few hundred mA.  You can add transistors or motor controllers between the Arduinos and the fans to deal with such current loads.

Absolute Maximum Current per Pin is 40mA (in Arduino Uno) so when you connect the fan with the I/O pins at that time the fan may draw more current from the pin and because of this the voltage level of the pin may drop down. Because Fan or Motor want more current then the capacity of Arduino pins capacity so if you want to On/Start the Fan/Motor then you have to connect Fan/Motor Driver between the Arduino Pin and Fan/Motor. And you have to provide external power source to the motor driver circuit.
For your reference:


text:
32x32 RGB-LED Matrix displaying Arabic Font with Font Forge more easily
At the moment I am using a separate function to display byte arrays like these:
const PROGMEM unsigned char arab4[] = {
  0x00, 0x00, 0x00, 0x00,
  0xf0, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x00, 0x0e, 0x00, 0x00,
  0x80, 0x03, 0x00, 0x00,
  0xc0, 0x01, 0x00, 0x00,
  0x60, 0x00, 0x00, 0x00,
  0x20, 0x00, 0x00, 0x00,
  0x10, 0x00, 0x00, 0x00,
  0x18, 0x00, 0x00, 0x00,
  0x08, 0x10, 0x06, 0x00,
  0x0c, 0x70, 0x0f, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x04, 0x78, 0x06, 0x00,
  0x06, 0x20, 0x00, 0x00,
  0x06, 0x80, 0x00, 0x00,
  0x06, 0xc0, 0x01, 0x00,
  0x06, 0xc0, 0x03, 0x00,
  0x0e, 0xe0, 0x01, 0x00,
  0x1c, 0x80, 0x01, 0x00,
  0x1c, 0x00, 0x00, 0x00,
  0x7c, 0x00, 0x00, 0x00,
  0xf8, 0x00, 0x00, 0x00,
  0xf0, 0x07, 0x00, 0x00,
  0xe0, 0x7f, 0x00, 0x3c,
  0xc0, 0xff, 0xff, 0x0f,
  0x00, 0xff, 0xff, 0x01,
  0x00, 0xf0, 0x1f, 0x00,
  0x00, 0x00, 0x00, 0x00};

My function for displaying uses Adafruit libraries
#include <RGBmatrixPanel.h>
#include <Adafruit_GFX.h>

Finally my Function:
void xbm32_n (const PROGMEM unsigned char bild[32],word cchsv) {

int i = 0;
while(i<32){

    for(int k=4*i;k<(4+4*i);k++)
    {

    for(int ii = 0; ii<8; ii++){

       int bit = ((pgm_read_byte(&(bild[k]))) >> ii) & 1;
       if(bit == 1) { matrix.drawPixel(ii+8*k-4*8*i, i, cchsv);}}}

   i++   ;
    }
   }

The inner workings are as follows:
The function draws each 32 bit row with the color chosen on the Panel depending on the 4 bytes in each "row" of the hex array.
Essentially 2 loops (to draw the row in byte increments) with outer while loop (to move to next row).
The calculation of the pixel positions can be seen inside the matrix.drawPixel(x-pos,y-pos,color-value) Adafruit-function, and were made up by experimenting long hours.
See for the whole .ino File here
Notes on the file

It also features among others

(like a displaying shifting 8x8 symbol-array saved in const PROGMEM byte IMAGES2[][8] used in the function bildlauf(1,...)

an updated function void xbm32_4c(char bild[32],word* cchsvar[4], int duration,int cseq[4])) where:

word* cchsvar[4] points to four color data values
cseq[4] is the sequence for displaying the colors in each panel
quadrant

The subdivision of the panel is realized via if() and else if() commands checking the conditions for positions:
x = (ii+8*k-4*8*i) </> some value  && y = i </> some value

Function input:

bild[32] is used for the hex array as in my case arab4[]
cchsv is a color data value . I am using sparkfun 32 LED Matrix and
found the following function for hsv color space to work well:
  word hsvcolor(int h, int s, int b ) { //Try HSV colors http://colorizer.org/
  int hue1, sat1, bright1;
  word result;

  hue1=map(h, 0, 360, 0, 1535);
  sat1=map(s, 0, 100, 0, 255);
  bright1=map(b, 0, 100, 0, 255);
  result = matrix.ColorHSV(hue1,sat1,bright1,true);

  return result;
}

Current Issues to solve:
I am using Font Forge to create XBM Files in helping me create the hex letter array, but found it very clumsy to export, as the width size must be a multiple of eight to adjust height by deleting 0x00 rows.
At the moment I am searching for easier ways to "correct" the exported XBM arrays (like using 8x8 Editor 8x8 Editor, only for 32x32 Matrices).
Is there a possibility for this?
Alternatively it would also help to create a function to truncate hex arrays to fit 32x32 dimensions somehow.
Additionally, in Arabic there is the issue of variant glyphs for the different letter positions (isolated, medial, initial, final). It seems possible to create byte arrays for all variants but "correcting" each bitmap so that a scrolling effect (I plan to upgrade to 64x32 LED Matrix) "adds up" visually seems daunting. I am happy for suggestion on realizing this challenge as well.
I am aware that there is a Adafruit function for bitmaps:
void Adafruit_GFX::drawBitmap()
I couldn't get it to work with my hex array, also the possibility on how to change quadrant colors or other subdivisions lead me to write my own version I modified from 8x8 Panel case. I am not sure whether there are inefficiencies in the code I have written, I therefore am happy for suggestions.

The solution to creating Arabic characters with typographic ligature and scrolling them, is:
Using the application RTB RichText to Bitmap :

Set width-size of bitmap in increments of 32*n while using a height
    initially bigger than 32  (saving the bmp will allow for cropping of rows so that bigger letters can be produced, a bit offset to fit height 32)
Saving the bmp and editing it (take care that bitmap rows are saved in rows, if not switch scanning line mode)
Also the byte    endian for output must be rightly chosen: ("Lsb" for pc-editing, uploading to    arduino for use in the function provided here, it is in
    "Msb")
 The cropped characters bitmap must be then reloaded into RTB Pixel Editor on a fitting canvas (generate an empty one) and set to a different scanning mode (rows now in columns) with byte endian Msb

Group the array of hex elements in pairs of four (you can use
notepad++ and  regex find:
(((0[xX][0-9a-fA-F,]{2})[,]){3}((0[xX][0-9a-fA-F,]{2})))
replace: {/1}

Using a suiting arduino scrolling function (on top of adafruit    libraries)

Insert 32x(4_hex) chunks of your bitmap data in the file provided
above as array element in:  const PROGMEM unsigned char
I[][32][4]= {{here},{here},...,{here}}
Adjust main loop code for scrolling direction (here r to l) via increment or
decrement and number of scrolls (panel-size is here chosen 32):
int es=64; while (es>0) {   scroller01(I,32,dpink,es,go);   --es; }
Verify if you need to load a chunk of your bitmap group to const
PROGMEM unsigned char I[][32][4] , so that scrolling is fluid and
does not jump when the arduino re-cycles

The Question got solved in detour via another question  in this exchange (see  here ). I am answering it to resolve parts of it.
The scrolling is slow when extended fully onto 64x32 Panels with arduino Mega 2560.
For a clip see:

  www.dropbox.com/s/qth8iuygra1wx9b/VID-20170210-WA0000.mp4?dl=0

 If somebody comes up with a more efficient,faster way, please do share!

Seems to get downvoted without explanation after two years. At least share your opinion when doing so.


text:
How can one reset Arduino Nano from NodeMCU?
If one connects the RESET pin on an Arduino Nano to a digital pin on a NodeMCU, will the NodeMCU be able to reset the Nano by setting said pin to LOW?

Yes, you can reset a 5 V Arduino with esp8266. I did it many times. The esp8266 doesn't have a problem with pull-up level current at 5 V.
On my picture io 0 of the esp-12F is wired to reset pin of Nano. The esp-12F runs WiFiLink firmware which can OTA upload sketch to ATmega328p and of course before flashing it must reset the ATmega.

Yes - grounding the reset pin over-rides the pullup resistor on the Atmega 328's reset pin. You may not be able to prevent the NodeMCU from resetting the Nano when it (NodeMCU) is reset, if that matters.

esp8266 doesn't set pins LOW at startup

Good to know - thanks.

that matters.  tks for the headsup, UPVOTED.

yes it can.
and to make this answer a little longer...

you don't need a level shifter as the pins are 5v tolerant. pullups aren't a problem
you may use an optocoupler for isolation :)

interesting, UPVOTED


text:
Endless loop on boot after reflashing ESP-12E with AT firmware
I flashed the ESP-12E from AT firmware 2.0 (running ok) to NodeMCU (running ok). When I reflashed it back to the AT 2.0 it is stuck in endless loop on boot:
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2408, room 16
tail 8
chksum 0xe5
load 0x3ffe8000, len 776, room 0
tail 8
chksum 0x84
load 0x3ffe8310, len 632, room 0
tail 8
chksum 0xd8
csum 0xd8

2nd boot version : 1.6
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
no GPIO select!
jump to run user1 @ 1000

rf_cal[0] !=0x05,is 0xFF

I am sure I flashed it correctly, it was not my first flashing of AT firmware. Just to be sure:
esp_init_data_default.bin -> 0x3fc000
blank.bin -> 0x3fe000
boot_v1.6.bin -> 0x0000
user1.1024.new.2.bin -> 0x1000
blank.bin -> 0x7e000

I can even reflash it to the NodeMCU firmware and it works, but reflashing to the AT firmware ends in the same endless loop again.
I suspect the problem is in initialization data, but I'm at my wit's end with it.

Maximilian, thanks for you reply. I did erasing of the flash in past. I made some new tests, read the whole 4M flash and compared it with one in a functional module and finally got it working. The critical is your last sentence.
The solution: I had to flash esp_init_data_default.bin to the address 0xfc000. I found nothing about it in the documentation but this is the way I got the ESP12 to work again.
Thanks!

Full answer and writeup to the comments:
The error message is due to the bootloader trying to read the contents of its radio-frontend calibration data (hence the name rf_cal). It compares it with a magic number, 0x05, but fails because it reads 0xFF at that point. 0xff is an indication that you read data from flash which was erased. After erasing a flash-sector, the data in it becomes 0xff 0xff 0xff... Hence it seems as if the bootloader is trying to access the data from the wrong address, thus only reading erased flash data. The RF-calibration data is stored in the file esp_init_data_default.bin and must be flashed to the correct address in order for the bootloader to be able to read it.
The NodeMCU documentation  tells us the needed address for esp_init_data_default.bin given the size of the flash of our ESP module:

The bootloader messages
2nd boot version : 1.6
SPI Speed      : 40MHz
SPI Mode       : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)

indicate that the flashed firmware (or that what is overriden by esptool.py) uses the 8 MBit flash size. There should be two ways to fix this:

Put esp_init_data_default.bin to the address the 8Mbit (1 MByte) bootloader expects, which is 0xfc000
Force the usage of the 32 MBit (4 MByte) Flash map by giving esptool.py the parameter --flash_size 32m. This makes esptool.py overwrite a few bytes in the firmware (at 0x000000) to adapt the firmware.

By your comments, method one worked. If there are problems however with the flash or the firmware, consider also trying method 2.

authors: Роман Кушнір