text:
How can I adapt this code for the ATTiny85?
So I set up an Arduino circuit that while a button was pressed, a sound effect would play and an LED would activate until I stopped pressing the button. Since I didn't use a micro sd card module, I had to use wav2c to convert the audio to numeric values that I then used the code here to implement the audio. The numeric values for the audio were placed in a header file that was referenced in the code. The code and my circuit work but I want to see if I can use one of my new ATTiny85's to run the code and perform the same operations as the Arduino did. I have set up my Arduino Mega 2560 to program the ATTiny85. I have tested it with Blink and it works. However, after I had moved the pins of the speaker, LED, and button to those of the ATTin85 and edited the appropriate code, it will not upload to the ATTiny85. It gives error messages that certain variables have not been declared in this scope. One such is "TCCR1B" and when I comment it out, it claims another variable has not been declared in this scope. Any idea how I can overcome this and if it's even possible to use the ATTiny in this capacity?
The Code I tried uploading to the ATTiny85

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 20000
#include "Test.h"

int ledPin = 0;
int speakerPin = 1; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 2;
volatile uint16_t sample;
byte lastSample;
int buttonState = 0;
const byte interruptPin = 2;
volatile byte state = LOW;

void stopPlayback()
{
    digitalWrite(ledPin, LOW);
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    digitalWrite(ledPin, HIGH);
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();
        //digitalWrite(ledPin, HIGH);
        //delay(1000);
        //digitalWrite(ledPin, LOW);
}

void setup()
{
    pinMode( pinSwitch1, INPUT );
    pinMode(ledPin, OUTPUT);
    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), stopPlayback, CHANGE);

}

void loop()
{
//startPlayback();
//delay(5000);
//stopPlayback();
buttonState = digitalRead(pinSwitch1);

stopPlayback();

if (buttonState == LOW) {
    startPlayback();
    delay(1150);

}

}

The header file with the audio
#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

//There are a lot more numbers in here to generate the audio but I cut most out to save space

};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

The ATTINY85 doesn't have the same set of timers as the board this was written for.    That looks like code for an UNO (ATMEGA328) or a Mega (ATMEGA2560).  The ATTINY85 doesn't have a corresponding timer to the 16 bit Timer1 on those chips.  You really can't use this on an 85.

As @delta_G pointed out, this code is written specifically to access the timer hardware on the chip, and the ATTINY85 has different timer hardware.
It would not be hard to change this code to work with your just need to output the next step in the list of audio values 8000 timer per second.
There are two ways you could do this...

You could figure out the corresponding settings for the ATTINY85 timer hardware and use those instead. The timer registers are documented in the ATTINY85 datasheets and you can google lots of info on how to set those registers, but it is complicated.
You can bit-bang the audio data out though a digital pin. Bing banging means you write code that manually sets the pin high or low at the appropriate times.

Since it does not look like you need to do anything else while the sound is playing, I think bit banging is the simpler approach here.
Do do bit banging, you get rid of the start and end playback functions and instal have a playSound() function that looks something like this...
void playSound() {
    pinMode(speakerPin, OUTPUT);  // This really belongs in setup()
    for(unsigned sample=0; sample<sounddata_length; sample++) {      // step though the audio samples
        sample_value=pgm_read_byte(&sounddata_data[sample])/2;    // grab next value from array in flash

        // Note that we divide the value by 2. This is because our target rate is
        // 8000 samples per second, which is 125us per sample. Each sample value is 0-255, so /2 gives us
        // a value 0-127. If we spend about 127us on each sample then we are in the right ballpark
        // for playback speed (ok, a bit slow).

        digitalWrite( speakerPin , 1);     // poor man's single cycle bitbang PWM
        _delay_us( sample_value );
        digitalWrite( speakerPin , 0);
        _delay_us( 127-sample_value );

     }

    }
}

This is just pseudo code and I have not checked to see if this even compiles, but you should get the idea.
This is also a hack, so it does not take into account how long the digitalWrite() takes
or the overhead of the loop. It also explicitly stretches the sample time from 125us to 127us for math simplicity and speed (dividing the 0-255 by 2 is very fast). All these will likely make the playback sound slow and low, but i'm not sure how much.
I also do not take into account that the playback can get interrupted which would cause audio glitches. You can fix this by putting cli()/sei() around the playSound() code.
Finally, each sample only gets a single PWM cycle so I don't expect audio to be CD quality, but maybe good enough. If you need more PWM cycles then there are ways to do this, but then probably better to use the hardware timer.
LMK if you can get this working (post a video!) or have any questions!


text:
How to fix when i shorted 5v to gnd accidentally (Arduino Nano)
I connected 5V to GND accidentally (connect directly, no LED, no motor). Now the LED on the board doesn't light up and power LED lights up but it is not bright. The 5V output pin is only around 1.98V. I'm using clone version from Alibaba. I ordered two, one is still working but the shorted one doesn't work. May I know how to fix them?

You very likely fried components on the board, and would have to troubleshoot and repair those components. If they are surface-mount components that is a highly skilled repai. As Systembolaget says, it's not likely worth it.

I would say that to repair an Arduino Nano clone yourself, if ICs/SMD parts are damaged, is not worth the effort, if you could do it at all (first having to find out which parts need to be replaced, carefully de-soldering the delicate SMD parts, then putting new parts in place, etc.).

First of all  thanks for answer my question, for my case MBR0520 diode is damaged, Voltage regulator is still working, i did a bypass from MBR0520 diode to voltage regulator and it's work perfectly.

source: Stack Exchange

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

sort: votes


text:
Why does this take more byte?
I am only replacing a portion of my code where I want to use the first method but as you can see it is making my sketch size little bigger
//if(iBPM >= 40 || iBPM <= 170 )
      {
      char iBPMwav[50];
      String thisString = String(iBPM);
      String stringThree =  "n" + thisString;
      stringThree =  stringThree + ".wav";
      stringThree.toCharArray(iBPMwav, 50);
      tmrpcm.play(iBPMwav);
      }

Sketch uses 29678 bytes (100%)
This is simple but at the end, I want to go from the number 40 up to 170, and this is why I want to use the first method.
//if(iBPM >= 40 || iBPM <= 170 )
  {
      if(iBPM == 71)
tmrpcm.play("n71.wav");
  else if(iBPM == 72)
tmrpcm.play("n72.wav");
  else if(iBPM == 73)
tmrpcm.play("n73.wav");
  else if(iBPM == 74)
tmrpcm.play("n74.wav");
  else if(iBPM == 75)
tmrpcm.play("n75.wav");
  else if(iBPM == 76)
tmrpcm.play("n76.wav");
  else if(iBPM == 77)
tmrpcm.play("n77.wav");
  else if(iBPM == 78)
tmrpcm.play("n78.wav");
  else if(iBPM == 79)
tmrpcm.play("n79.wav");
  else if(iBPM == 80)
tmrpcm.play("n80.wav");
  else if(iBPM == 81)
tmrpcm.play("n81.wav");
  else if(iBPM == 82)
tmrpcm.play("n82.wav");
  else if(iBPM == 83)
tmrpcm.play("n83.wav");
  else if(iBPM == 84)
tmrpcm.play("n84.wav");
  else if(iBPM == 85)
tmrpcm.play("n85.wav");
  else if(iBPM == 86)
tmrpcm.play("n86.wav");
  else if(iBPM == 87)
tmrpcm.play("n87.wav");
  else if(iBPM == 89)
tmrpcm.play("n89.wav");
  else if(iBPM == 90)
tmrpcm.play("n90.wav");
  else if(iBPM == 91)
tmrpcm.play("n91.wav");
  else if(iBPM == 92)
tmrpcm.play("n92.wav");
  else if(iBPM == 93)
tmrpcm.play("n93.wav");
  else if(iBPM == 94)
tmrpcm.play("n94.wav");
  else if(iBPM == 95)
tmrpcm.play("n95.wav");
  else if(iBPM == 96)
tmrpcm.play("n96.wav");
  else if(iBPM == 97)
tmrpcm.play("n97.wav");
  else if(iBPM == 98)
tmrpcm.play("n98.wav");
  else if(iBPM == 99)
tmrpcm.play("n99.wav");
  else if(iBPM == 100)
tmrpcm.play("n100.wav");
  else if(iBPM == 101)
tmrpcm.play("n101.wav");
  else if(iBPM == 102)
tmrpcm.play("n102.wav");
else
 tmrpcm.play("n170.wav");
}

Sketch uses 29024 bytes (101%)

You are using the String class which is pretty mighty and not light weight. It is always a good idea NOT to use the String class on MCUs.

Are you aware that iBPM >= 40 || iBPM <= 170 is always true?

@EdgarBonet No, I didn't know

Then you should learn what the operators >=, <= and || mean.

@EdgarBonet Yes I did look that up that after you mentioned and learned from somewhere else. Tell me about it what a huge mistake boy ha ha

I suggest having simpler file names (same size, always 3 digit numbers)
/// Return a text "n000.wav" ... "n255.wav"
/// depending on the parameter
char* makeFileName(byte i) {
  static char name[9] = "nxxx.wav";
  byte digit = i/100;
  name[1] = '0' + digit;
  i -= digit*100;
  digit = i/10;
  name[2] = '0' + digit;
  i -= digit*10;
  name[3] = '0' + i;

  return name;
}

Looks smart to me. I will try it today.

Alright, I like your idea.. changing the name of the files will be like loosen flywheel for me. Instead, I made your code into two versions the first for "nxx.wav" and one for "nxxx.wav"

While the Strings class makes a C/C++ program easy to understand and maintain, as stated in the comments, using the Strings class is a memory intensive option which should be should be avoided when memory is in short supply.  Such as on the embedded processors used in most Arduino platforms.
Here are 2 examples where Stings is used and not used.  Note the reduction from 2326 bytes to 734 bytes of program memory necessary to store the sketch in the embedded processor.
void setup()
{
}

void loop()
{
  uint8_t iBPM;
  uint8_t pointer;
  for(iBPM = 40; iBPM <= 170; iBPM++)
  {
    char iBPMwav[50];
    String thisString = String(iBPM);
    String stringThree =  "n" + thisString;
    stringThree =  stringThree + ".wav";
    stringThree.toCharArray(iBPMwav, 50);
//  tmrpcm.play(iBPMwav);
  }
}

Sketch uses 2326 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 27 bytes (1%) of dynamic memory...
void setup()
{
}

void loop()
{
  uint8_t iBPM;
  uint8_t pointer;
  for(iBPM = 40; iBPM <= 170; iBPM++)
  {
    char iBPMwav[50];
    pointer = 0;
    char temp_str[10];
//  String thisString = String(iBPM);
//  String stringThree =  "n" + thisString;
//  stringThree =  stringThree + ".wav";
//  stringThree.toCharArray(iBPMwav, 50);
    itoa(iBPM, temp_str, 10);
    if(iBPM < 100)
    {
      strncpy(&iBPMwav[pointer],"n0",2);
      pointer += 2;
      strncpy(&iBPMwav[pointer],temp_str,2);
      pointer += 2;
    }
    else
    {
      strncpy(&iBPMwav[pointer],"n",1);
      pointer += 1;
      strncpy(&iBPMwav[pointer],temp_str,3);
      pointer += 3;
    }
    strncpy(&iBPMwav[pointer],".wav",4);
//  tmrpcm.play(iBPMwav);
  }
}

Sketch uses 734 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 15 bytes (0%) of dynamic memory...

BTW: String use even more RAM than compiler can see. And String+String is awfully complicated, creating a lot of garbage  :)

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


text:
light detection system: Response different from power bank and computer system
Hello friends
I'm working on a light detection system for the higher secondary summer term project, for which I'm using a simple Arduino board, Adafruit 16-Bit ADC, an LDR with some resisters, a 5V USB power source either the computer USB 2.0 port or a mobile power bank 5V-500mA/1A/2.1A, a USB mobile charging cable (not the data cable) and a Bluetooth module to communicate with Arduino system, an android or a computer (different from Arduino power source) to record the data.
The difference in maximum and minimum response is very poor when replacing the power source from the computer USB to power bank USB. With the same environmental and experimental conditions, the response goes from 50000 to 45000 counts (the changes in response are 5000 counts) with the power bank. For the same situations, the response goes from 50000 to 5000 counts (the changes are 45000) with the computer power source which is more suitable but it's better to use a small power supply.
How can I get the better and stable response? Kindly help me to solve out this issue. Thank you.

Could you please provide a link to the ADC product page or datasheet?

You could use the on-board ADC on the Arduino. See the Analog Read Serial and Read Analog Voltage built in examples.

Thanks for your valuable comments. ADC must be at least 16 bits for my project while on arduino board it has 10 bit only.That's why I'm using ADS115 here. For datasheet: www.ti.com/lit/gpn/ADS1115.

Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons.  More may exist.

The USB 2.0 definition stats such a port provide 0.5A of current.  Some devices limit the current as a precaution.  Therefor the battery may provide more current then the USB source.  The type of USB source was not specified and no voltage measurement data was provided.
How fast does the device need to react to a change in light level?  A light-dependent resistor or LDR can have a latency of as much as a second with respect to light level changes.
With regards to the 16 bit ADC.  What precautions have been made with regards to precisely controlling the ADC's voltage reference?  Any fluctuation can cause large errors.  What precautions have been made with regards to filtering out the ADC's random noise?  For example, many ADCs only have a fraction of their resolution if averaging is not used.

Source info.: 1) USB 2.0 5V 0.5A        2) MI  and Intex original power bank has 3 port for 5V 0.5A/1A/2A supply.
All 3 ports of each power bank are providing the same response. All data is being received only through the Bluetooth communication with all other things remain same. In my case the output should be at least first, so 5000 is minimum with a computer USB2.0.

In my case the output should be at least first, so the computer is 5000 minimum with USB2.0. But for similar situations, when the source is replaced with the above power bank, the output response for all the same conditions for the minimum response varies from 5000 to 45000. Again, with the computer's USB 2.0 / 3.0 port, it goes from 45,000 to 5000 for similar conditions.

Get a volt meter and measure the actual voltage across the USB power pins.  Do this under the most current demanding situations.  Likely when communicating with the Bluetooth device.  If you can not do this, start simplifying the project.  Start by removing the Bluetooth device and communicating with the Arduino over the serial port.  Keep simplifying until you stop getting unexpected results.

Hello dear st2000
Thanks for your precious time and response.
It is working perfectly with serial or Bluetooth when
connected to the computer USB 2.0 port via cable or charging cable.
But with above mentioned power bank or mobile charger, it is not showing the same response with Bluetooth and I can't go for the serial in case of power bank.
Computer USB 2.0 port voltage = 4.91 V.
Power bank USB port voltage = 5.17 V.

@AsTJ, this is not much of a voltage difference.  Also, I looked up your ADC.  Is this one the ADC you are using?  If so the ADC chip contains an internal voltage reference.  So the small voltage difference you measured between your computer and power brick should not make the difference you are seeing.  I am at a loss.  Perhaps try a different power brick or ordinary battery.

@AsTJ, which Arduino board are you using?  I see that the ADC chip needs a serial port.  I assume the Bluetooth does too.  Are you using a software defined port by any chance?  Software defined ports are fine for slower speeds and simple projects.  But if the processor is tasked with too much to do, the software defined ports usually act unexpectedly.

Dear st2000, thanks for kind response. It's the same as available on the link send by you. The system has been checked with MI and Intex 10000mAh power bank have 3 seperate ports 5V - 0.5A, 1A, 2A and one Micromax 5V-0.5A power adaptor and one MI 5V-2A power adaptor. Also checked with 3 different Dell computers and one HP laptop.
Generally I'm using arduino uno but due to this issue, the system has been checked with a duplicate arduino nano also. The software defined serial ports are used to communicate in between but no other issue has found except amplitude or response counts.


text:
MKR1010 disconnects and reconnects normally until it reaches a point where it never reconnects again
The board does reconnect from time to time, but there are times where it just disconnects and never reconnects again and I can't replicate the error because while I run it with Serial open and turn ON and OFF my WiFis it always reconnects as it should.
#include <ArduinoHttpClient.h>
#include <WiFiNINA.h>
#include <EmonLib.h>

EnergyMonitor emon1;
EnergyMonitor emon2;
EnergyMonitor emon3;
int INTERVAL = 60;
int last_code = 0;

char ssid[] = "MySSID";
char pass[] = "MyPW";

String ID = "Garden_Pump_Sensor";

int sequence = 0;
double kWh = 0.0;

char serverAddress[] = "192.168.1.108";  // server address
int port = 5005;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);

int status = WL_IDLE_STATUS;

void setup() {
  Serial.begin(9600);
  analogReadResolution(9);
  emon1.current(0, 100);
  emon2.current(5, 100);
  emon3.current(6, 100);
  Connecting();
}

void Connecting() {
  int tries = 4;
  while ( (WiFi.status() != WL_CONNECTED && tries > 0) || last_code != 200) {
    Serial.print("Status #1: ");
    Serial.println(WiFi.status());
    WiFi.begin(ssid, pass);
    Serial.print("Status #2: ");
    Serial.println(WiFi.status());
    tries--;
    last_code = 200;
  }

  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void reconnecting() {
  if (WiFi.status() != 3  || (WiFi.RSSI() <= -90) || (WiFi.RSSI() == 0) || last_code != 200) {
    WiFi.end();
    Connecting();
  }
}

void loop() {
  unsigned long delayTime = INTERVAL * 1000;
  unsigned long time_start = millis();

  DataMonitorAndSend();

  unsigned long time_final = millis() - time_start;
  unsigned long delay_value = delayTime - time_final;
  Serial.println(delay_value);
  if (delay_value < 1  || delay_value > delayTime) {
    return;
  } else {
    delay(delay_value);
  }

}

void DataMonitorAndSend() {
  reconnecting();

  Serial.println("making POST request");
  String contentType = "application/json";
  kWh = kWh + getKWH();
  String postData = "{\"ID\": \""+ID+"\",\"seq\": " + String(sequence) + ",\"kWh\": " + String(kWh, 6) + "}";
  Serial.print("data: ");
  Serial.println(postData);

  client.setHttpResponseTimeout(5 * 1000);
  client.post("/receivedata/", contentType, postData);

  // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  if (statusCode == 200) {
    kWh = 0;
    sequence++;
  }
  last_code = statusCode;
  Serial.print("Response: ");
  Serial.println(response);

}

double getKWH() {
  int LOOPS = 15;
  double kWh_Total = 0.0;
  unsigned long delayTime_kwh = 2 * 1000;
  for (int i = 0; i < LOOPS; i++) {
    unsigned long time_start_kwh = millis();

    double Irms1 = emon1.calcIrms(600);
    if (Irms1 < 0.3) Irms1 = 0;
    double Watt1 = (Irms1 * 230) / 1000;

    double Irms2 = emon2.calcIrms(600);
    if (Irms2 < 0.3) Irms2 = 0;
    double Watt2 = (Irms2 * 230) / 1000;

    double Irms3 = emon3.calcIrms(600);
    if (Irms3 < 0.3) Irms3 = 0;
    double Watt3 = (Irms3 * 230) / 1000;

    kWh_Total = kWh_Total + ((Watt1 + Watt2 + Watt3) / 60);

    unsigned long time_final_kwh = millis() - time_start_kwh;
    unsigned long delay_value_kwh = delayTime_kwh - time_final_kwh;
    if (delay_value_kwh < 0  || delay_value_kwh > delayTime_kwh) {
      delay(0);
    } else {
      delay(delay_value_kwh);
    }

  }

  return kWh_Total / LOOPS;
}

Feel free to ignore the getkWH(), it's code related to power consumption. Also the firmware is up to date and the server is using a static IP.

A quick answer (so take it for what it is worth): If using Windows, I have had different versions of Windows decide on their own a particular network was bad, stop communicating over it and not say a word about it.  Switching to Linux the network problems all became clear and, finally, problems could be easily solved.

Thank you, but for the server, I'm using a raspberry pi / raspbian OS running a simple Flask Server. I have actually this server for other projects and had no issues, I think the issue is that the mkr is not sending /hangs somewhere and not a case of the server not receiving since I sent requests from other sources into it and it works fine.

Since you only send a data every 60s, it is better to only establish a WiFi when you need it, AND only create an instance of HttpClient after that. That's means that it only creating the wifi and client instances when you need it instead of using a global instances. Here is a way I usually do for such an application that I modified based on your sketch, you could give it a try. Please noted that only the  changes that I made are highlighted in my code snippet, please fill-in the rest of your code:
unsigned long INTERVAL = 60000;  // in milliseconds
unsigned long time_start = millis() + INTERVAL;    // noted that I changed this to a global variable and to unsigned long

// WiFiClient wifi;
// HttpClient client = HttpClient(wifi, serverAddress, port);

void Connecting() {
  WiFi.disconnect();
  WiFi.begin(ssid, pass);
  Serial.print("Connecting to ");
  Serial.print(ssid);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" Connected");

  // your code for printing localIP
}

void loop() {

  if (WiFi.status() != WL_CONNECTED)
    connecting();

  // send data when INTERVAL is reached
  if (millis() - time_start > INTERVAL) {
    DataMonitorAndSend();
    time_start = millis();
  }

  yield();

}

void DataMonitorAndSend() {
  // reconnecting();

  WiFiClient wifi;
  HttpClient client = HttpClient(wifi, serverAddress, port);

  // rest of your DataMinitorAndSend() code

  client.end();

}

I found that before using WiFi.begin() to re-connect, one needs to use WiFi.disconnect() first. At least that keeps my set-up reliably re-connecting, when its battery is empty or my router is out for a moment. Also, testing for WL_CONNECTED or 3 only means that one's set-up is connected to the router, but the router not necessarily yet to the internet; in case of a restart of the router after a power outage. On one of my routers, one has to wait 10 seconds, on another 18 seconds.
void connectToWLAN()
{
  // Check if the AirLift FeatherWing's WLAN module works
  if (WiFi.status() == WL_NO_MODULE)
  {
    Serial.println("Connection to AirLift FeatherWing WLAN module failed");

    // If not, indicate there is a WLAN module malfunction
    WiFi.setLEDs(0, 255, 0); // Red

    // And stop forever
    while (true);
  }

  // Return to loop() if already connected to the WLAN router
  if (WiFi.status() == WL_CONNECTED)
  {
    return;
  }

  Serial.println("Trying to connect to WLAN router");

  // Indicate there is no WLAN router connection just yet
  WiFi.setLEDs(192, 255, 0); // Yellow

  do
  {
    // Start connection to WLAN router and print a status value
    WiFi.disconnect();
    delay(1000);

    status = WiFi.begin(WLAN_SSID, WLAN_PASS);
    // WL_IDLE_STATUS     = 0
    // WL_NO_SSID_AVAIL   = 1
    // WL_SCAN_COMPLETED  = 2
    // WL_CONNECTED       = 3
    // WL_CONNECT_FAILED  = 4
    // WL_CONNECTION_LOST = 5
    // WL_DISCONNECTED    = 6
    Serial.println(WiFi.status());
    delay(10000);
  }
  while (status != WL_CONNECTED);

  Serial.println("Connection to WLAN router successful");

  // Indicate that the WLAN router connection was established
  WiFi.setLEDs(255, 0, 0); // Green

  // To better see the status indicating RGB LED's state
  delay(2000);
}


text:
Which of the ESP8266 alternatives allows for full packet capture/injection in promiscuous mode?
I am part of a product group that is developing a low cost wireless intrusion detection system, for home usage.
We have already produced and delivered to market ESP8266 based product however for the new thing, we need the chipset to be able to enter promiscuous mode and receive/inject 802.11 packets on the fly without any limits.
ESP8266 is limited to 112bytes max, which is not enough to even parse the Beacon frame properly.
What are the alternatives for ESP8266 currently - that allow:

to capture the 802.11 frames
have no packet length limits
allow packet injection

Ps. doesn't have to be ARDUINO - but needs to be C/C++ programmable.
Thanks in advance.

Are you using encryption on your WiFi network?

Obviously, people do use encryption WEP(rarely)/WPA/2. Why do you ask ?

Because if you have encryption there is no such thing as promiscuous mode. You can't see anyone elses frames, they are encrypted. You want raw radio data access, and that then means manually decrypting packets to make any sense of anything.

Well you can still have promisc enabled and receive DATA packets that are encrypted. You can decrypt them later on if you know the key, not sure what's your point. Simply put, ESP does the job, but is limited with 112bytes which is not enough to perform full packet analysis.

That sounds more like direct radio data access than promiscuous mode.  If the ESP8266 can do it (kind of) then the ESP32 can most likely do it far better.

Unfortunately both 32 and 8266 have a limit set by ESPRESSIF for max length of a packet to 112 bytes. What does it mean? You get a MGMT Beacon frame length 239 bytes. All you can read is first 112 bytes, while in the rest of it you get trash...

Maybe something like the CC3100MOD would do the job. Not sure about programming it, but it has an ARM CPU embedded in it, so you can certainly use GCC. There's probably some toolkit available from TI from it. I've never used one, so I can't comment.


text:
How to keep the regulator cool while battery powering the arduino and accessories?
I'm trying to build a battery operated hand lantern. It has the Arduino, an MPU6050 accelerometer, and 4 APA106 (WS2812B-like) LEDs.
If everything's powered through the Arduino's 5V pins, that's 80mA for the Arduino, 240mA for the 4 LEDs, and let's round up to 5 mA for the MPU6050.
If I'm using 5x AA batteries for 7.5V (at full charge) that should be 2.5V * 325mA of power wasted or just under a watt that'll be heating up the regulator? I'm not sure if that's huge or tiny or in between or what.
What's the most sane way to power this device for an absolute newbie?

Use en external voltage regulator (go switch-mode if you care about battery life) that is adequately cooled.

"Switch mode"? What would I be regulating the voltage down to, since it still has to be fed through the Arduino's linear regulator?

@Different55 Switchmode voltage regulators rapidly switch on and off the current. Together with a capacitor they can provide a stable voltage with a lot less power lost. Regulate to 5V or slightly above that. The arduino can handle a slight undervolt.

@Different55 I dare to assume that the answer suggest feeding 5V from the regulator directly to the 5V pin of Arduino, skipping its weak and inefficient regulator altogether.

Let me know if this is completely stupid, but as I was thinking about regulators and batteries I remembered I have a portable USB power bank. Doesn't the Arduino's USB input also skip the regulator?

1W is near the limit of what a small LDO can handle. It will get considerably hot.
I would use 4 batteries instead of 5, and a 3.3V Arduino clone instead of the UNO, and power the LEDs directly from the batteries. You could also use your original UNO, feeding it with 6V on a 5V pin through a simple diode, which would drop it to something like 5.4..5.3V.

How would powering the LEDs from the battery work? They seem pretty demanding of a steady 5v of power, and at least at a full charge 4 of them would be 6V.

@Different55 instead of the positive coming from VCC it comes straight from the + of the battery. The negative of the battery and LED both get connected to arduino ground.

@Different55 APA106 have a working range of 4.5 to 6V.

I suggest using a DC-DC buck/boost voltage regulator. Those can take a wide range of input voltages and put out an adjustable output voltage
This one on Amazon, for example, can take an input of 3-40V and provide an output of 1.5-35V(Adjustable). It is a switching power supply, so it should not produce much waste heat. That one is rated at 2A, or 3A if you add a heat-sink.
You could feed the regulated 5V into the USB connector on your Arduino, and to your other components as well. (Just take a USB cable, cut it, and tie the red and black wires to ground and +5V, respectively.
You might need a filtering capacitor to protect the Arduino from voltage variations as the load on the power supply changes.

Is that a special type of capacitor or just a normal one used for that purpose? Will any capacitor work? Does it just store energy and spit it out to smooth out tiny dips?

You want a decent sized electrolytic, between 5V and ground physically near the input to the Arduino. I'm not an EE - I'd have to do some digging to figure out what rating of capacitor is appropriate. Yes, it acts as a filter, and resists changes in voltage.


text:
Arduino HID keyboard does not work
I'm using a ItsyBitsy 32u4, Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the Keyboard docs say are supported.
I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.
Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?
EDIT: the keyboard works on a different computer.
#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}

you shoukd read the reference and study the examples

@Juraj I have, what do you think I missed?

it seemed you missed what is in the Answer. do you have a text editor open in foreground?

Yeah, I have a window focused that accepts and displays keyboard input. Typing on my actual keyboard displays the keys.

next I would try removing Serial from the sketch

removing serial didn't make a difference.

check the Device Manager if it has the HID device

There was some issue with my laptop, not controller or the sketch.
I tried the my board with another computer and it worked. I tried a commercial keyboard on my first computer it also didn't work.
Both keyboards work after a reboot.

Keyboard.press() expects a character, but you are passing a character array. Also Keyboard.press() only presses but does not release the key. Keyboard.releaseAll() can be used to release all keys.
I would try:
Keyboard.press('A') ;  //note the ' instead of "
Keyboard.releaseAll();

or preferably:
Keyboard.write('A');   //handles press and release of basic keys

I made an error when I created my simple repo sketch, but I have tried Keyboard.press('A') and Keyboard.write('A'). Neither work.

I also tried Keyboard.write('a') after reading keyboard.cpp and realizing that writing 'A' sends keypesses for a and the shift modifier.


text:
Phase and frequency correct PWM mode Arduino Mega 2560
I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?

unsigned int b=7999;
void setup() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TCCR4B=(1<<WGM43)|(0<<WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1<<CS10);
TIMSK4 |=(1<<OCIE4A);
}

void loop() {
  }

ISR(TIMER_COMPA_vect){

  }

The output of the code for different duty cycles are as below
Duty cycle:0.2 (OCR4A=b/5)

Duty cycle:0.2 (OCR4A=b/2)

see the diagrams for pwm timing  in the datasheet

Can you please explain what is wrong

in phase correct pwm the counter counts up and then down and so it matches the compare register twice in one period. first while counting up a second match while counting down. the pin changes state on both matches

That's what I need. But it's clear from the wave form that the pin trigger while down counting and resets immediately as a glitch

You wrote:

TIMSK4 |= (1<<OCIE4A);

and then never defined ISR(TIMER4_COMPA_vect). As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.

When I added interrupt service routine (ISR(TIMER4_COMPA_vect)) the output waveform acts exactly like fast PWM. It does not provide phase correct wave

@VivekVijayan: Do you get the expected frequency? If so, how do you tell it is not phase correct?

@Edger Bonet: I am getting the expected frequency. But when I observe the waveform all the waves with different duty cycle starts from the same point. I believe in phase correct pwm mode the OCnA or OCnB pins are set during upcounting. So I could expect different starting points(in time) for waves with different duty cycles

@VivekVijayan: You would not get 1 kHz in fast PWM mode. Re “different starting points (in time)”: What is your time reference for defining the starting points? Are you using an oscilloscope? If so, how did you configure its trigger?

I don't know much about CRO. I am using an electronic module called Expeyes which basically acts as a DSO. I used the time reference axis to determine the triggering points. Expeyes doesnt have any option to control triggering. I generated Fast PWM using different code and compared it with the output from the above mentioned code.

@VivekVijayan: Your phase correct waveform is fine. It looks wrong to you only because you don't understand how your DSO sets its time axis.

Thanks for your time. I am proceeding with it. Will try some RC filters to identify the output waveform.


text:
RDTSC alternative for Arduino
To calculate an operation execution time, I was saving the millis() result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?

yes, on Uno the alternative is millis()

There are several alternatives. The best choice for you depends on the
time resolution you need and the maximum duration you may want to
measure:

millis() is good for slow things. It has a resolution of 2 ms
(it increments by steps of 1 ms most of the time, but 2 ms
occasionally) and can measure durations as long as 49.7 days.
micros() is the easy choice for when you want more resolution for
faster things. It increments in steps of 4 µs and is limited to
about 71.6 minutes.
For very fast things, you can get single-cycle resolution if you
configure Timer 1 to count at the full CPU speed, assuming you
don't need the timer for something else. But beware the timer will
roll over roughly every 4.1 milliseconds.
You could also use Timer 1 with the prescaler set at ÷8 in order
to expand the measurable range to 32.8 ms, at the cost of a
degraded resolution.

Here is a table summing up the available methods, sorted by resolution:
method        data type  resolution  max. duration
--------------------------------------------------
millis()       uint32_t        2 ms     49.7 days
micros()       uint32_t        4 µs     71.6 min
Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms

Thank you so much! I have a sub-question: Timer 1 (÷64) and micros() seem equivalent in resolution, will reading Timer1 value be more accurate/reliable than using micros()?

@Harini: Reading TCNT1 will be faster than calling micros(), so you get less overhead, at the cost of a shorted rollover period.


text:
A confusing condition statements
I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a kitchen timer.
In that code I found a statement
currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;
I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it.
What does this statement mean?

it is if (currentMode == MODE_IDLE) {currentMode = MODE_RUNNING;} else {currentMode = MODE_IDLE;}

http://www.tutorialspoint.com/ansi_c/ternary_operator_examples.htm

I think adding parenthesis makes it much more readable:
currentMode = (currentMode == MODE_IDLE) ? MODE_RUNNING : MODE_IDLE;

Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.
if you do not understand ternary operators, it can be re-written as:
if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

You should read up on the ternary operator.  It appears in several languages in various formats and can come in handy in a variety of situations.
In general terms the ternary operator is of the following form (as used in an assignment):
result = (booleanExpression) ? (value if true) : (value if false);

but you can use it in other contexts for example in a function call:
someFn(booleanExpression ? trueValue : falseValue);

does Internet need another ternary operator explanation?


text:
Arduino - line follower car
I want to build a line follower car, but I dont have Infrared sensors, so want to run the car, without sensors as a test
I have Motor Driver on top of Arduino UNO R3, all connections as expected, but all wheels are not spinning. I have no idea on which one is Motor1, 2,...
Code: https://create.arduino.cc/projecthub/adamsstephen/controlling-an-l9100-motor-driver-board-using-arduino-cc5618#toc-step-1--placing-electronics-0
int Motor[8] ; // Array for all Motor Output pins, one more than required

void setup() {
  Motor[1] = 4; // Set output numbers for ports
  Motor[2] = 5;
  Motor[3] = 6;
  Motor[4] = 7;
  Motor[5] = 8;
  Motor[6] = 9; // Set up Port for LED on Head of Arm.
  Motor[7] = 10; // Forward / Reverse selection for ALL motors
  // Switch connected to GND and A0, to locally turn off motors while testing.
  pinMode(Motor[1], OUTPUT); // Open Port to operate Motor on Pincers Forward = In Reverse = Out
  pinMode(Motor[2], OUTPUT); // Open Port to operate Motor Up= High  Reverse = Down
  pinMode(Motor[3], OUTPUT); // Open Port to operate Motor Forward = Forward Reverse = Backward
  pinMode(Motor[4], OUTPUT); // Open Port to operate Motor Wrist Forward = Up Reverse = Down
  pinMode(Motor[5], OUTPUT); // Open Port to operate Motor base Rotate Forward = Right Reverse = Left
  pinMode(Motor[6], OUTPUT); // Open Port to operate LED on head of Arm HIGH = ON LOW = OFF
  pinMode(Motor[7], OUTPUT); // Open Port for Forward / Reverse selection for ALL motors
}
void loop() {
    digitalWrite(Motor[6], LOW); // Turn off LED.
    if (analogRead(A0)< 1){ // switch ON
    digitalWrite(Motor[1], HIGH); // Turn on Motor 1. HIGH turns it on! Pincers
    digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
   Serial.println(analogRead(A0));
}
    if (analogRead(A0) > 200  ){    // switch OFF
    digitalWrite(Motor[1], LOW); // Turn on Motor 1. HIGH turns it on!
    digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
   Serial.println(analogRead(A0));
}
    delay(200); // debounce the switch action
}

I commented the whole loop(), still some wheels are spinning. how is that possible? How can I know - which one is Motor1 ,...M4 and the corresponding Arduino pin numbers.
I want to spin all 4 wheels/ dc motors

Welcome to Arduino Stack Exchange. Please edit your question with add your schematics

why are you trying to control seven motors when you have trouble controlling one? ... reduce your sketch so that it controls only one motor ... figure out which pin you are controlling with your sketch and connect the motor to that pin .... when you get that working, then change to a different pin (edit the sketch) ... keep going until you tested all seven output pins using only one motor ... then try to run two motors  .... etc. etc.

@jsotola I have no idea, that is why I am here. I commented all lines except - PinMode Motor[4] and 3 wheels are spinning. It is literally 1 lines of code and 3 wheels spinning. One time same code - only 1 wheel spinning. So I am seeking for an expert to give a useful answer. thanks

Try to grounds all pinout motors exception one motor wire opened at 7404 chip. That's @jsotola means

no, that is not what I mean ... remove all motors ... remove all wires ... connect one motor ... connect only the wires necessary to run the one motor ... run a simple sketch that turns on the motor, pauses for 2 seconds, turns off the motor ... do not put any code in loop() ... put all code in setup()

Apologies, but the interface to me is the motor driver - Motor Driver Shield L293D. which I think supports 4 wheels [has M1/2/3/4], is placed on top of Uno R3. So, I do not know underlying Arduino  pins. Note: I am connecting via USB and testing, hoping that it has enough voltage. Cant believe how this 1 line -  pinMode(Motor[4], OUTPUT);  is spinning 2 wheels and my head too.

L9100 or l293d is same to me, you can try jsotola suggest. That's very helpful and provide us more informative with add your schematic

Looks like it is voltage issue. the car has, 4 dual shift motors. supplied 2 x 18650 and 3 wheels spinning, sometimes 4. sometimes 1, sometimes 2, sometimes all 4, sometimes only 1 in reverse. Inconsistent results. Not sure how much power needs to be supplied. Do dual shaft  require double the  single shaft ?


text:
Losing top brightness when using tip120 and PWM with 70w LED panel
I have been experimenting with pwm dimming using TIP120 on various high powered LED's, and have noticed a marked drop in the top level brightness compared to original connection without the tip 120 in line.
For instance a 70w panel connected with heavier gauge cable (not using jumper cables) no longer reaches full brightness with pwm set too full.
im using tasmota on a nodemc8266.
Is there something inherent the hardware set up causing the loss that I am missing or is there a software limitation with PWM?
curious
thanks

don't know if it is the cause, but PWM in arduino esp8266 core is software PWM: pin is toggled in timer interrupt

Remove the PWM and just set the pin to HIGH. Then see if there is still a difference. My guess is that there is. I think the TIP120 will have a relatively high voltage drop across it. Making the leds less bright. If that's the case I'd switch to a MOSFET instead of a bipolar (darlington) transistor

One of the main disadvantage of a Darlington transistor pair is the minimum voltage drop between the base and emitter when fully saturated. Unlike a single transistor which has a saturated voltage drop of between 0.3v and 0.7v when fully-ON, a Darlington device has twice the base-emitter voltage drop (1.2 V instead of 0.6 V) as the base-emitter voltage drop is the sum of the base-emitter diode drops of the two individual transistors which can be between 0.6v to 1.5v depending on the current through the transistor.

thank you, all of these comments make such sense and i will experiment with each so I methodically understand the process, and then finally follow up with the specific mosfets as described  by @crossroads.

Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.


text:
Is there a simple HTTP(S) library that doesn't rely on WiFi?
I'm trying to implement a Mobile Network (only) for the ESP32 using Arduino IDE. So to be able to connect to website up/download files etc. I need to be able to handle various HTTP PUT/GET/POST requests. However, the available libraries seem to always rely on additional WiFi related libraries. I don't want to have to load those as well, as they are quire bloated and not needed for my use scenario.
What options do I have for minimalist HTTP request libraries that does not rely on WiFi or BT or ETH?

do you have some library over 'Mobile Network' or only AT commands?

Only AT commands. So now I have to manually construct the request/response with strings, which is a real PITA.

I don't know about mobile network Arduino library with Server implementation. it would require a public IP address so not many would use it

I'm not implementing a server, just a connecting client to download files (to the ESP).

sorry. then you can use TinyGSM. https://github.com/vshymanskyy/TinyGSM

@Juraj That look promising. How do you import that library into the IDE?

is it not in Library Manager?

My bad! I have no idea why I missed it the other day. Thanks.

The TinyGSM library implements Arduino networking Client base class over GSM modem's AT commands. The library is available in Library Manager.


text:
Execute code only once
I am trying to create an if statement that only runs once, the very first time the void loop is started and switches to another code after that. But the following only executes stepper1a(). Any help would be great. Thx !
int var;
int var2;
bool executed = false;

const int M1dirpin = 4; //Stepper Dir Pin
const int M1steppin = 5; //Stepper Step Pin

void setup() {

pinMode(A2,INPUT);
pinMode(M1dirpin,OUTPUT);
pinMode(M1steppin,OUTPUT);
Serial.begin(9600);

}

void stepper1() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=200;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void stepper1a() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=1600;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void loop() {

if (executed == false) {
var = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1a();
  delay(2000);
  executed = true;
  Serial.println("turned 1600");
  Serial.println(executed);
  }
else if (executed == true) {
 var2 = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1();
  delay(2000);
  Serial.println("turned 200");
}
}
}
}

Updated void loop:
void loop() {

    static bool yes_we_did_the_one_time_job = false;

    if (yes_we_did_the_one_time_job) {
        var = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper2();
            delay(2000);
            Serial.println("turned 1600");
        }
    }
    else {
        var2 = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper1();
            delay(2000);
            Serial.println("turned 200");
            yes_we_did_the_one_time_job = true;
        }
    }
}

This works now, thx !!!:
void loop() {
  static bool yeswedid = false;

  if(yeswedid) {
    if(analogRead(A2) > 500) {
    stepper1();
    stepper2();
    }
  }
  else {
    if(analogRead(A2) > 500) {
    stepper1();
    yeswedid = true;
  }

  }
}

you have a typo. else if (executed == true) { is else to if (var > 500) {, not to if (executed == false) {. add one } before else if (executed == true) { and remove one } at the end

and if (executed) {} else {} would be cleaner

Your updated code is still wrong. You have have the code that sets yes_we_did_the_one_time_job to true inside a second if statement, which means it won't get set until after var > 500.

@DuncanC, that is the goal as I understand it. Wait until the analogRead first time reaches 500 and then do the special initialization move. because without the condition it could be executed in setup()

@digit - Question regarding your "Updated void loop:" code. The code if (var > 500) { in the else statement, is it suppose to be var or var2?

Generic solution:
void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}

if this is what you suggest, it did not work:

see updated question. Thanks for your help

@digit: Re “it did not work”: you did not quite implement my suggestion. Read your code carefully and you will see it is not equivalent to what I posted here.

great solution thanks man !

If you have any code you want to run only once at the beggining of your program you can use the setup() method. It can actually do much more than just setting up pins and default values.
The code of main function of Arduino (main.cpp) looks like this:
int main(void)
{
    //(...) I cut some stuff from here

    setup();

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

    return 0;
}

As you can see setup() is just a method and it can do almost exactly the same things as loop().
The setup() method can actually contain a for(;;) loop that will stop the program from running the loop() method. From inside it you can check the sensor value and break from it when condition is met.
void setup()
{
  for (;;)
  {
    var = analogRead(A2);
    delay(10);
    if (var > 500) {
      stepper1();
      delay(2000);
      Serial.println("turned 200");
      break;
    }
  }
}

in this case the loop() is very simple:
void loop()
{
  var = analogRead(A2);
  delay(10);
  if (var > 500)
  {
    stepper2();
    delay(2000);
    Serial.println("turned 1600");
  }
}

It has to react to a sensor while in void loop and not run once at startup. Thanks.

only once, but after a starting condition is met. the OP's code is usable, only a { is missing


text:
Using case statement with IR emitter reciever
I am trying to use two "infrared obstacle avoidance modules" to work with the following sketch.  From all my research, I believe, a case statement is my best option because, (I understand) the sketch will not continue until the case is satisfied, however, I'm getting a weird outcome. When using two sensors with sketch below, the leds blink in an alternating pattern without any near the ir sensors.
If I use only one module the led will light until the sensor sees something, then the led turns off for the programmed delay then turns back on.
The outcome I'm looking for is eventually three modules, that will randomly light, when one lights it waits until something breaks the beam, then another will light and wait...
Does anyone have any ideas how to make this work?
int ledselect;
int led1 = 2;
int led2 = 3;
int ir1 = 4;
int ir2 = 5;
int s1 = A0;
int s2 = A1;

void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(ir1, OUTPUT);
  pinMode(ir2, OUTPUT);
  pinMode(s1, INPUT);
  pinMode(s2, INPUT);

}
void loop() {
  ledselect = random(2);
  switch (ledselect) {

    case 0:
      digitalWrite(led1, HIGH);
      digitalWrite(ir1, HIGH);
      delay(50);
      while (analogRead(s1) >= 100)
      {
        delay(50);
        digitalWrite(led1, LOW);
        digitalWrite(ir1, LOW);
      }
      break;

    case 1:
      digitalWrite(led2, HIGH);
      digitalWrite(ir2, HIGH);
      delay(50);
      while (analogRead(s2) >= 100)
      {
        delay(50);
        digitalWrite(led2, LOW);
        digitalWrite(ir2, LOW);
      }
      break;
  }
}

the sketch will not continue until the case is satisfied ... that is not quite correct ... the case statement is just a decision structure that branches to different sections of the code depending on the value of a parameter .... it is similar to a series of if statements

What happens is:

A random number is selected
A light goes on
It goes off when nothing is near (assuming a low value of an analog sensor means nothing near?)
The same light or another light goes on (depending on the random led)
Continue with 3.

Some reasons why this might fail:

Check the value (should it be higher or lower than 100?)
Maybe the sensor is not so accurate and sometimes give 0 or max values which are incorrect. To change this, read multiple times the sensor and take the average, or remove the lowest and highest few (to remove spikes) and take the average.

UPDATE
The body of the case statements are almost equal, make it a function called from both case statements:
Your code will look like:
void loop() {
  ledselect = random(2);
  switch (ledselect) {
    case 0:
      process(led1, ir1, s1);
      break;

    case 1:
      process(led2, ir2, s2);
      break;
  }
}

void process(int led, int sw, int ir)
{
  digitalWrite(led, HIGH);
  digitalWrite(ir, HIGH);
  delay(50);
  while (analogRead(sw) >= 100)
  {
    delay(50);
    digitalWrite(led, LOW);
    digitalWrite(ir, LOW);
  }
}

If you use the ternary operator ( x ? y : z, meaning if x than y else z), than your loop function will be:
void loop() {
  ledselect = random(2);
  process(ledselect == 0 ? led1 : led2,
          ledselect == 0 ?  ir1 :  ir2,
          ledselect == 0 ?   s1 :   s2);
}

An even more elegant way, is to use an array for the parts (not sure what better name can be), instead of all variables naming 0 and 1, put them in arrays, and you get the following code below. If you make more parts, you just have the change the beginning of the code.
int ledselect;

const int NrOfParts = 2;

int leds     [NrOfParts] = {  2 , 3 };
int irs      [NrOfParts] = {  4,  5 };
int switches [NrOfParts] = { A0, A1 };

void setup() {
  Serial.begin(9600);
  for (int part = 0; part < NrOfParts; part++)
  {
    pinMode(leds    [part], OUTPUT);
    pinMode(irs     [part], OUTPUT);
    pinMode(switches[part],  INPUT);
  }
}

void loop()
{
  ledselect = random(2);
  process(leds[ledselect], irs[ledselect], switches[ledselect]);
}

void process(int led, int sw, int ir)
{
  digitalWrite(led, HIGH);
  digitalWrite(ir, HIGH);
  delay(50);
  while (analogRead(sw) >= 100)
  {
    delay(50);
    digitalWrite(led, LOW);
    digitalWrite(ir, LOW);
  }
}

Update 2
An even better way is to create a structure (so you keep all information of one 'part' together).
This solution uses the & (dereference) operator, meaning it is like a variable pointing to a part.
int ledselect;

const int NrOfParts = 2;

struct Part
{
  int led;
  int ir;
  int sw;
};

Part _parts[NrOfParts] =
{
  { 2, 4, A0 },
  { 3, 5, A1 }
};

void setup() {
  Serial.begin(9600);
  for (int partNumber = 0; partNumber < NrOfParts; partNumber++)
  {
    Part& part = _parts[partNumber];
    pinMode(part.led, OUTPUT);
    pinMode(part.ir , OUTPUT);
    pinMode(part.sw ,  INPUT);
  }
}

void loop()
{
  process(_parts[random(2)]);
}

void process(Part& part)
{
  digitalWrite(part.led, HIGH);
  digitalWrite(part.ir, HIGH);
  delay(50);
  while (analogRead(part.sw) >= 100)
  {
    delay(50);
    digitalWrite(part.led, LOW);
    digitalWrite(part.ir, LOW);
  }
}

Thank you Michel for your response. I used your suggestion to clean the sketch and greatly appreciate you taking the time to analyze my question and answer.

I added some more alternatives, do not use them if you don't feel comfortable.


text:
Trouble operating Servo and GPS at the same time
I have a problem using a servo and a GPS board at the same time on an Arduino Uno.
For the servo, I use the following code:

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

For the GPS module, I follow the guidance on this webpage describing the NEO-6M GPS Module
#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

I combine these two code blocks into one *.ino file (combining the declarations, placing all the setup portions in the void setup(){...} function and the rest in the void loop(){...} part).
Here is the problem:
Each block by itself runs fine. The "GPS block" returns GPS messages and the "Servo block" runs smoothly through its position sweep. However, when this code is combined the servo starts to act erratically and "jerks" back and forth.
After some testing, it appears that starting the serial connection (ss.begin(9600);) changes the behavior of the servo control pin (here 9) and it looses its pulse width modulating (PWM) capability. The servo then starts to "jerk" to random positions.
Does anybody have insight into this phenomenon? Is there a way to operate the servo and the GPS module together?
Here is a functional code block that sweeps through the servo positions smoothly, by commenting out the line //ss.begin(GPSBaud); and replicates the erratic behavior by uncommenting the same line ss.begin(GPSBaud);.
#include <Servo.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(GPSBaud);
  //ss.begin(GPSBaud);
}

void loop() {
  for (pos = 20; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 160; pos >= 20; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Would really help if you said why the system acted unexpectedly.  Guessing, I would first disconnect the servos to see if you have a power supply problem.

Thanks for editing your question.

Usually it is never a good idea to use a software implemented serial communications port. Especially when combining multiple Arduino libraries.  Likely you will have to graduate to a more capable embedded processor to get around this problem.   (You may be the 1st to combine these 2 libraries.)  I still am concerned about the power (are you supplying power to the servos separately from the Arduino and GPS module?).

@st2000, thanks for your comments.

I only use the USB connection for power. I will check if I have an external power supply available.
You recommend using a more capable embedded processor. Do you have a suggestion on which one might be suitable?

@st2000 I connected a 9V battery as external power source in addition to the USB connection. This does not change the behavior.

For 1, USB 2.0 is only obliged to deliver 0.5Amps.  More current than that and the port can rightfully drop the voltage on you.  For 2, there are many platforms in which the Arduino development environment has been ported to.  An Arduino Uno uses an Atmel  ATmega328P.  An Arduino Mega uses an Atmel  ATmega2560.   A processor with many more peripheral features.

FYI, a common Alkaline 9 volt battery does not have the current capacity to drive much of anything.   About 1/2A/h.  A stack of Alkaline D cells could hold as much as 30 times the power.

Should add, in the end you may still have some sort of hardware contention.  And it may not be the processor.  The libraries may not take advantage of all that any given processor has to offer.  Also, you may have to dive deeper into the library options.  You may have to select alternate peripherals (i.e. the second serial port) rather than accept the default (which may be the first serial port).  In the worst case you may have to rewrite one or both of the libraries.  Or, if that's not to your liking, run the Servos and GPS on different Arduino's which talk to each other.


text:
Atmega collecting and relaying interrupt calls
I like to collect all possible interrupt and relay them to an alternative handler interrupt table what the user can set.
In order to do this i have to:
   1) collect all/any interrup request
   2) identify where is the interruption came from
   3) relay the call to another table the user pointed.
If you familiar with interrupts you know if you registers a single function to all interrupt handler there's no way to idenfity the source of the interrupt.
But registering unique interrupt handler that carries the information of the source and calls another function to dispatch call, for each interrupt is a code space wasting. Eg.: the atmega328 has 24 interrupt handlers. Each of the is compiled with the avr-gcc consumes 76 bytes.

But i have and idea how it is possible to register one handler function and identify the source:
00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

If i define an interrupt handler (even if it can fit the 4 byte space) a jmp instruction is placed. If it can be replaced to eg.: call 0xa2 (which can fit in 4 bytes), is can be used to identify the interrupt source address.
Because call stores the return address, the function started at 0xa2 can read back that address and therefor idenfity the caller. Then add an extra pop (pop the stack address accumulated by the call at the interrup table) and reti (to return as like from an interrupt handler) after the function body.
If this can work theorically, to achieve this only one question remains:
How can i replace the jmp instructions to call in interrupt table?

The interrupt vector table is provided by the C runtime. It is
not normally intended to be overridden by user code. You can, however,
do it, if you replace the whole C run time by your own, and compile your
sketch with the -nostartfiles option.
I have played this game once I was trying to accurately assess interrupt
latencies. See the details in this answer (the answer is long,
but you can go right to the last section).

The answer i've accepted is the proper answer for the problem i asked.
However replacing the C runtime requires to attach and maintain a lot of crt.S files oiginally related to the GCC. To avoid this i "slept several times over this prolem" and came out another solution.
After compiling the host application that have to redirect the interrupt calls
(script source). I wrote a utility that rewrites every interrupt jumps at the beginning of the ihex (source) with an offset to the target application.
Ok this solution doesn't collect and identify and relay the incoming interrupts, just relay them. As far as there's no target application, nothing enables these interrupts and cause fault. This solution also doesn't use extra code space.


text:
Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3?
I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.
Writing to SoftwareSerial seems to be working but reading not.
As I write "AT", the module returns me "-5" which should be "OK".
As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.

#include <SoftwareSerial.h>
SoftwareSerial ss(rx, tx);

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

void loop() {
  while (Serial.available()) ss.write(Serial.read());
  while (ss.available()) Serial.write(ss.read());
}

the sketch is OK. something else is wrong. do you have 9600 baud set in Serial Monitor? and both line ends? is the wiring good?

What pins are you using for tx and rx?

@A. L. K., I think we are all making assumptions here.  Please clear some things up by answering if it is the Arduino which is sending the "AT" or if it is the Arduino which is receiving the "AT" and sending back incorrect characters.

With SoftwareSerial 9600 baud is about the maximum rate you can reliably run at when using a 5V 16MHz Arduino. You are using an 8MHz one at 3.3V, so you can expect that speed cap to be halved.
Don't use SoftwareSerial. Ever. Full stop. There is no call to ever use it. If you don't have enough real UART ports on your board then you are using the wrong board. Don't just use a board because it's the one that everyone uses. Look at what you want to do and then pick a suitable board that fits your needs. There are many many 3.3V boards available with multiple (or even one single spare) UARTs - for example the Fubarino Mini, the Teensy 3.x, Any number of ESP32 based boards - all with a similar footprint to the Pro Mini, and with a huge amount more power to boot.

Thank you. Can you recommend me some board like pro mini 3v3 but with more hw serial ports including sleep with external interrupt wake up and timed wake up.

Teensy boards are probably the best supported.

You may get better results if you do not nest the read and write function calls as you did.  That is, read everything then write everything.
The reason for this is that softwareserial.read() returns 1 character.  If you immediately turn around and pass that character to softwareserial.write() you will devote the resources of the processor to sending that character.  In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.
That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the Mega 2560 processor on the Arduino Mega.
Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater.  A hardware serial port or UART can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.

with AT firmware you send a command and then you get a response. so while is ok. the rest of the Answer is not related to the Question

@Juraj, I have improved my answer by explainning why a serial port implemented in software finds it difficult to run fast.  I also explained why a HW UART is better for faster communications.


text:
How to acheive fast and reliable communication between NodeMCUs?
I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have  tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.
Any ideas how could I can acheive speed of 10Hz via WiFi?
Thanks for any help.

the symbol for the unit of frequency measurement is Hz, not hz ... please correct your question

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.
If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read from the WiFiClient object on the other side.
client socket
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


text:
Capacitive Moisture sensor only shows values 1 and 2
I'm new to Arduino and electronics in general. I'm trying to connect the Capacitive moisture sensor v1.2 to my arduino and get values in the serial plotter.
I connected the VCC to 5V, GRD to ground and AOUT to A0. However, I keep only getting values of 1, 2 or 3, while they are supposed to be in the hundreds. What could be a cause of such a problem. I'm using the chinese Wavgat board, but I have previously connected the moisture and humidity sensors and they displayed values normally.
Here's the code I used:
int val;
void setup() {
  Serial.begin(9600);
}

void loop() {
  val = analogRead(A0);
  Serial.println(val);
  delay(200);
}

What's a capacitive moisture sensor v1.2?

Assuming this is what you have, did you go through the OverView for this product including installing the Adafruit_seesaw library?

Ah, not the expensive digital board.  This board has an analog output. At this point you need to start testing and swapping out parts.  Test the voltage at AOUT to verify it does in fact change when dipping the sensor in water.  Try a different sensor.  They are cheep and maybe you have a defective one.  Try a different Arduino.   Maybe the ADC input is broken on the one you have.


text:
Insane heat development with ESP8266
I have a ESP8266 on a Wemos D1 mini board. Simple "Rainbow with FastLED" animation. Shouldn't do much but the board gets so hot I can't touch it and it drains a 2500mAh battery in less than an hour.
Any idea what I'm doing wrong? Especially as a comparable micropython implementation just doesn't get that hot and the same battery keeps for about 5 hrs...
Here's the code

#define FASTLED_ALLOW_INTERRUPTS 0
#include "FastLED.h"
#include <EEPROM.h>

// How many leds in your strip?
#define NUM_LEDS 60
#define DATA_PIN 13
#define CLOCK_PIN 14
#define COLOR_ORDER RGB
int starthue = 0;
int incrementer = 255/NUM_LEDS;
CRGB leds[NUM_LEDS*2];
int address = 0;
int max_modes = 4;
int colormode;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
  FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS*2);
    EEPROM.begin(512);
  colormode = EEPROM.read(address);
  Serial.println(colormode);
  int new_mode = (colormode == max_modes) ? 1 : ++colormode;
  Serial.println(new_mode);
  new_mode = (colormode == 0) ? 1: new_mode;
  Serial.println(new_mode);
  EEPROM.write(address, new_mode);
  EEPROM.commit();
  EEPROM.end();
}

void rainbow_mid(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    for (int i =0; i< NUM_LEDS; i++) {
      leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }
}

void rainbow(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    //addGlitter(80);
    for (int i =0; i< NUM_LEDS; i++) {
      //leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }

}

void loop() {
  switch(colormode) {
    case 1: rainbow_mid(10); break;
    case 2: rainbow_mid(50); break;
    case 3: rainbow(10); break;
    case 4: rainbow(50); break;
  }

}

Same board, same connections in both cases?

The problem does not lie in your code, but in the connections. 60 RGB LEDs can draw about 20mA360 = 3.6A (all LEDs in full white). Showing a rainbow will draw less current, but as Tirdad wrote in his answer, that will still be too much for the onboard regulator. How have you connected everything? How have you connected the battery?

the heat is from the supply lines of board.
it's not the chip itself, as if it gets hot like that the chip should be destroyed.
it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too.
so the heat is not from the chip. its from power supply tracks on the PCB.
use another power source for the LED strip.


text:
How to Specify Array Length during Object Construction within Arduino IDE?
I'm working on a group project to involving the creation of an in-house library using the Arduino IDE. As the Arduino IDE uses C++, the library must be a class. One of the classfields is an array of numbers. We would like it if we could specify the array length during object construction, as there are pros and cons to low and high array lengths. Is it possible to specify or change the array length during object construction?
Unfortunately, the Arduino IDE doesn't allow the usage of C++ vectors, so that's out of the question.

Rather rethink your idea and algorithm. Vectors are not used for a reason. Tiny uC require more consideration. Methods form the big machines usually are useless here

Arduino library doesn't need to be a class

It's not out of the question. There are various ports of the STL (Standard Template Library) for the Arduino. Try searching for them. The Arduino IDE does not itself preclude using them.

As suggested in st2000’s
answer, you could use
dynamic allocation but, if you do that, do not forget to free the
allocated memory in the destructor. Otherwise you have a nasty memory
leak and your program will not live long:
class MyClass {
public:
    MyClass(size_t length) : arrayLength(length) {
        theArrayOfNumbers = new int[arrayLength];
    }
    ~MyClass() {
        delete[] theArrayOfNumbers;
    }
private:
    const size_t arrayLength;
    int *theArrayOfNumbers;
};

One issue with this approach is that dynamic allocation is no very
friendly to the limited amount of memory you have in a microcontroller.
A safer option would be to use a template class instead. This way the
array is statically allocated:
template <size_t arrayLength>
class MyTemplateClass {
    int theArrayOfNumbers[arrayLength];
};

One caveat with this approach is that the users of the library may not
be comfortable with the syntax for instantiating a template. You will
have to provide clear examples in the documentation. Another issue is
that the array size will have to be a compile-time constant.

As suggested in the previous answer - better to link to the answer. There is no such thing as permanent "previous" in Stack Exchange. The order of answers depends on the voting. Each answer has a share link which can be used to get a suitable link to it.

a note: for every use of the template with a different size, compiler generates a different class. every class takes space in program memory

@NickGammon: Good point. Added the link.

Memory allocated using new[] has to be deleted using delete[], not delete.

tttapa is right. That line should read: delete [] theArrayOfNumbers;

Oops! My bad. Turns out, with avr-gcc, operator delete and operator delete[] are implemented identically, as jmp free. But then, of course, this should not be relied upon. I fixed the answer.

Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.
It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):
int memArray[N];
// ...
myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.

Some example solutions can be found in this stackexchange question/answer.  The accepted answer used this code:
private int size;

private String words[];

public WordStore(int n){
     words =new String[n];
}

and releasing the allocated memory? and prevent fast memory fragmentation?

Really good points @Juraj, I'd add them but Edgar has already provided good examples.  Thanks.


text:
Same software on single ESP-12f slower than on NodeMCU
I have programmed a small software to control an LED strip using an esp. I've written a web app which sends a request to the esp which then applies the color. So far everything works, but I've got a weird problem:
When I'm running the software on the NodeMCU, everything is fast and snappy, the web app takes 500ms at max to load. When I'm running the software from an ESP-12f (schematic), it takes way longer to load, about 5 seconds. Sometimes it doesn't even load at all.
Another thing that's weird: I've got two ESP-12f, one of those won't even load very often.
I also have the feeling that the "normal" esps run hotter than the nodemcu, but that could be because they are close to the voltage regulator which gets hot
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoOTA.h>
#include <colorWheel.h>
#include <web_iro_js.h>

#define RED_LED 14
#define GREEN_LED 12
#define BLUE_LED 5

#define BUILTIN_LED 2

const char* ssid = "---";
const char* password = "---";

IPAddress ip(192,168,2,111);
IPAddress gateway(192,168,2,1);
IPAddress subnet(255,255,255,0);
ESP8266WebServer server(80);

int brightness_red      = 0;
int brightness_green    = 0;
int brightness_blue     = 0;

int presets[4][3]       = {{255,119,46},{46,0,39},{0,115,23},{0,0,0}};

boolean blinking        = false;
boolean fading          = false;
boolean jumping         = false;

int blinkDelay[]        = {50, 145, 240, 335, 430, 525, 620, 715, 810, 905};
int speedPosition       = 4;

int fadeOrder[]       = {RED_LED, GREEN_LED, BLUE_LED};
int lastFade          = 0;    //0~2, refers to fadeOrder[]
int thisFade          = 1;    //0~2, refers to fadeOrder[]
int fadeSpeed[]       = {1, 1, 1, 2, 3, 4, 5, 5, 7, 9};

boolean blinkHelper = false;

void handleRequest();
void handleGet();
void setupOTA();
void connectToWiFi();
void turnOff();
void turnOn();
void applyColor();
void applyPreset();
void blink();
void fade();
void jump();

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

    analogWriteRange(255);

    pinMode(BUILTIN_LED, OUTPUT);
    digitalWrite(BUILTIN_LED, LOW);

    pinMode(RED_LED, OUTPUT);
    pinMode(GREEN_LED, OUTPUT);
    pinMode(BLUE_LED, OUTPUT);

    analogWrite(RED_LED, 0);
    analogWrite(GREEN_LED, 0);
    analogWrite(BLUE_LED, 0);

    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);
    WiFi.config(ip, gateway, subnet);

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

    setupOTA();

    server.on("/request", handleRequest);
    server.on("/get", handleGet);

    server.on("/", HTTP_GET, []() {
        server.send(200, "text/html", GUI);
    });

    server.on("/iro.min.js", HTTP_GET, []() {
        server.send_P(200, "application/javascript", IRO_JS);
    });

    server.begin();

    Serial.println("Setup done");
    pinMode(BUILTIN_LED, OUTPUT);
    digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
    if (WiFi.status() != WL_CONNECTED) {
        //Serial.println("no connection");
        connectToWiFi();
    }
    ArduinoOTA.handle();
    server.handleClient();

    if (blinking) {
        blink();
    }

    if (fading) {
        fade();
    }

    if (jumping) {
        jump();
    }

    if (blinking || fading || jumping) {
        delay(blinkDelay[speedPosition]);
    } else {
        delay(20);
    }
}

void handleRequest() {
    if (!server.hasArg("mode")) {
        Serial.println("no mode specified");
        server.send(400, "text/plain", "no mode specified");
        return;
    }

    String request = server.arg("mode");

    if (request.equals("color")) {
        fading = false;
        jumping = false;
        applyColor();

    } else if (request.equals("preset")) {
        fading = false;
        jumping = false;
        applyPreset();

    } else if (request.equals("blink")) {
        if (blinking) {
            blinking = false;
        } else {
            turnOff();
            fading = false;
            jumping = false;
            blinking = true;
        }
        server.send(200, "text/plain", "applied blinking");
    } else if (request.equals("fade")) {
        if (fading) {
            fading = false;
        } else {
            turnOff();
            blinking = false;
            jumping = false;
            fading = true;
        }
        server.send(200, "text/plain", "applied fading");
    } else if (request.equals("jump")) {
        if (jumping) {
            jumping = false;
        } else {
            turnOff();
            blinking = false;
            fading = false;
            jumping = true;
        }
        server.send(200, "text/plain", "applied jumping");
    } else if (request.equals("speed")) {
        if (!server.hasArg("newSpeed")) {
            server.send(400, "text/plain", "no speed specified");
            return;
        }
        int speed = server.arg("newSpeed").toInt();
        speedPosition = 9 - speed;
        server.send(200, "text/plain", "applied speed");
    } else {
        server.send(400, "text/plain", "argument not found");
    }
}

void handleGet() {
    if (!server.hasArg("arg")) {
        Serial.println("no argument specified");
        server.send(400, "text/plain", "no argument specified");
        return;
    }
    String request = server.arg("arg");
    String answer = "";

    if (request.equals("current")) {
        answer += (String(brightness_red));
        answer += (";" + String(brightness_green));
        answer += (";" + String(brightness_blue));
        answer += (";" + String(speedPosition));

    } else if (request.equals("presets")) {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 3; j++) {
                answer += String(presets[i][j]);
                answer += ";";
            }
        }
    } else {
        server.send(400, "text/plain", "argument not found");
    }
    server.send(200, "text/plain", answer);
}

void setupOTA() {
    ArduinoOTA.setHostname("ESP8266");
    ArduinoOTA.setPassword("password");

    ArduinoOTA.onStart([]() {
        Serial.println("Start");
    });
    ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();
}

void connectToWiFi() {
  Serial.println("WiFi connection lost, reconnecting");
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

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

void applyColor() {
    Serial.println("applying new color ");
    brightness_red = 0;
    if (server.hasArg("red")) {
        brightness_red = server.arg("red").toInt();
    }

    brightness_green = 0;
    if (server.hasArg("green")) {
        brightness_green = server.arg("green").toInt();
    }

    brightness_blue = 0;
    if (server.hasArg("blue")) {
        brightness_blue = server.arg("blue").toInt();
    }

    turnOn();
    server.send(200, "text/plain", "applied new color");
}

void applyPreset() {
    if (!server.hasArg("index")) {
        Serial.println("no index specified");
        server.send(400, "text/plain", "no index specified");
        return;
    }

    int index = server.arg("index").toInt();

    if (server.hasArg("save")) {
        Serial.println("saving preset");
        presets[index][0] = brightness_red;
        presets[index][1] = brightness_green;
        presets[index][2] = brightness_blue;
        server.send(200, "text/plain", "preset saved");
    } else {
        Serial.println("applying preset");
        brightness_red = presets[index][0];
        brightness_green = presets[index][1];
        brightness_blue = presets[index][2];

        turnOn();
        server.send(200, "text/plain", "preset applied");
    }
}

has the esp-12f a good antenna and a good reception? sometimes rotating the module with antenna towards the location of the AP makes wonder

@Juraj when pinging the boards they take about the same time to respond, so I think yes


text:
How to connect IRLZ44N to Arduino?

simulate this circuit – Schematic created using CircuitLab
In above schematic;

what value should R1 have? is it even needed?
do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

IRLZ44N DATASHEET

It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source
As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)

Thanks, but what value should R1 have? 220 ohm is enough?

Ohm law. Output voltage is probably 5V and maximum current on avr pin is less than 30mA. So you shouldn't go under 166R. That 220R sounds fine. Bigger values could cause longer transitions between fully on and closed states and bigger losses. But it's the problem on much higher frequencies than the default analogWrite provides


text:
From Strings to int problem
I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.
Arduino code:
String br;

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

void loop()
{
   while (Serial.available()>0)
 {
    br = Serial.readString();
    analogWrite(9, br.toInt());
    Serial.println(br.toInt());
 }
}

Qt code:
void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
{
   this->sendMessageToDevice(QString::number(position) + "n");
   qDebug() << "Grip: " << QString::number(position);
}

void MainWindow::sendMessageToDevice(QString message)
{
   if(this->device->isOpen() && this->device->isWritable())
   {
       //this->addToLogs("Sending information to the device " + message);
       this->device->write(message.toStdString().c_str());
   }
   else
   {
       this->addToLogs("I can not send a message. The port is not open!");
   }
}

Serial.readString() is deeply flawed and should be avoided. Read this: https://majenko.co.uk/blog/reading-serial-arduino

And I am sure you meant to add \n to your outgoing messages, not n...

when debugging a problem such as yours put Serial.println(br); before the analogWrite() to see what is being received

As Majenko wrote in his comment, your problem lies with Serial.readString(). It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. String.toInt() will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the n, that you send). It stops there and returns the already converted value.
This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.
Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.
The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character n is ok here. But mostly the newline character \n is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use \n.
As an example of this serial code, you can take the readline() function from Majenko's blog post:
char buf[80];

int readline(int readch, char *buffer, int len) {
    static int pos = 0;
    int rpos;

    if (readch > 0) {
        switch (readch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = readch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

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

void loop() {
    if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
    }
}

You can convert the character buffer to an int with atoi() in the if statement in void loop() and use it for ´analogWrite()`.