text:
Power save Sleep Mode Arduino
I'm trying to use this example link
source:
#include <avr/sleep.h>

/* Sleep Demo Serial
 * -----------------
 * Example code to demonstrate the sleep functions in an Arduino.
 *
 * use a resistor between RX and pin2. By default RX is pulled up to 5V
 * therefore, we can use a sequence of Serial data forcing RX to 0, what
 * will make pin2 go LOW activating INT0 external interrupt, bringing
 * the MCU back to life
 *
 * there is also a time counter that will put the MCU to sleep after 10 secs
 *
 * NOTE: when coming back from POWER-DOWN mode, it takes a bit
 *       until the system is functional at 100%!! (typically <1sec)
 *
 * Copyright (C) 2006 MacSimski 2006-12-30
 * Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

int wakePin = 2;                 // pin used for waking up
int sleepStatus = 0;             // variable to store a request for sleep
int count = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  pinMode(wakePin, INPUT);

  Serial.begin(9600);

  /* Now it is time to enable an interrupt. In the function call
   * attachInterrupt(A, B, C)
   * A   can be either 0 or 1 for interrupts on pin 2 or 3.
   *
   * B   Name of a function you want to execute while in interrupt A.
   *
   * C   Trigger mode of the interrupt pin. can be:
   *             LOW        a low level trigger
   *             CHANGE     a change in level trigger
   *             RISING     a rising edge of a level trigger
   *             FALLING    a falling edge of a level trigger
   *
   * In all but the IDLE sleep modes only LOW can be used.
   */

  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                      // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
    /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     * there is a list of sleep modes which explains which clocks and
     * wake up sources are available in which sleep mode.
     *
     * In the avr/sleep.h file, the call names of these sleep modes are to be found:
     *
     * The 5 different modes are:
     *     SLEEP_MODE_IDLE         -the least power savings
     *     SLEEP_MODE_ADC
     *     SLEEP_MODE_PWR_SAVE
     *     SLEEP_MODE_STANDBY
     *     SLEEP_MODE_PWR_DOWN     -the most power savings
     *
     * For now, we want as much power savings as possible, so we
     * choose the according
     * sleep mode: SLEEP_MODE_PWR_DOWN
     *
     */
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    /* Now it is time to enable an interrupt. We do it here so an
     * accidentally pushed interrupt button doesn't interrupt
     * our running program. if you want to be able to run
     * interrupt code besides the sleep function, place it in
     * setup() for example.
     *
     * In the function call attachInterrupt(A, B, C)
     * A   can be either 0 or 1 for interrupts on pin 2 or 3.
     *
     * B   Name of a function you want to execute at interrupt for A.
     *
     * C   Trigger mode of the interrupt pin. can be:
     *             LOW        a low level triggers
     *             CHANGE     a change in level triggers
     *             RISING     a rising edge of a level triggers
     *             FALLING    a falling edge of a level triggers
     *
     * In all but the IDLE sleep modes only LOW can be used.
     */

    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{
  // display information about the counter
  Serial.print("Awake for ");
  Serial.print(count);
  Serial.println("sec");
  count++;
  delay(1000);                           // waits for a second

  // compute the serial input
  if (Serial.available()) {
    int val = Serial.read();
    if (val == 'S') {
      Serial.println("Serial: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
    }
    if (val == 'A') {
      Serial.println("Hola Caracola"); // classic dummy message
    }
  }

  // check if it should go to sleep because of time
  if (count >= 10) {
      Serial.println("Timer: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
  }
}

I'm using a Tester for test really efficient of power saving; I read only a power save of 2 mA. Is it possible the Arduino Mega saves only that in sleep mode? Or am I doing something wrong?

You need a bare ATmega chip if you want to go low power. Otherwise you are continuously powering the 16U2 serial–USB bridge, the 3.3 V regulator and the power LED.

how i can shut down the serial usb Bridge , the 3,3 regulator and led power?

By unsoldering them, or cutting their traces.

I have a page about power saving. About the first suggestion on that page is to not use an Arduino "board" (particularly one with a USB interface chip, power LED and voltage regulator). They all take power - a lot of it. These boards are designed for prototyping, not low-power use in the field.
Something like this would be better:

Of course, that isn't an Atmega2560 chip. They only come in surface-mount and will be hard to solder yourself. You may be able to get an Atmega2560 board in minimal form. Or downgrade to a smaller processor that you can assemble yourself. The Atmega644P comes in PDIP which is easy enough to work with.
If you don't need all that RAM and program memory, you could go down to an Atmega328P which are easy to work with and can get down to 100 nA power consumption under the right circumstances.

You could conceivably do what Edgar Bonet suggested and cut traces on your Mega2560 board, but be warned that if you do that you won't be able to program the board via the USB interface afterwards. You can still program via the ICSP socket however, if you have a suitable programmer.

What are you using as resonator there?

This one - I can't remember where I got it from.

The Arduino Uno has a resonator on it for the main chip (not a crystal) so using a resonator is fine.

Nice information. What are you using as resonator there? The only one I know is using xtal+2cap

See amended answer.

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


text:
ESP-01 Programming
I have had so many problems with this board.  I have a detailed list of everything I've tried at the link below, but for simplicity I will just summarize where I am now:
https://forum.arduino.cc/index.php?topic=673618.new
What I am trying to do
I want to connect my Arduino Nano to the internet using an ESP8266 ESP-01.  Links to board references below:
Arduino Nano:
https://128217-368301-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2017/06/NSE-1004-2_7.jpg
ESP01:

My Arduino is a clone.  Here is the exact model:
https://www.amazon.com/Longruner-ATmega328P-Controller-Module-Arduino/dp/B01MSYWE6B/ref=sr_1_7?dchild=1&keywords=arduinonano&qid=1585358071&sr=8-7
I have a server running on my network that will take two types of requests from these Arduinos.  One Arduino/ESP pair will send data from sensors to the server, another pair will take that data from the server.  These are dedicated processes.  The sender will never receive and the receiver will never send.
Circuit
Three devices are at play: Arduino Nano (AN), ESP, and External Power Supply (EXPWS)
ESP:
VCC   -> 3.3v EXPWS
GND   -> GND  EXPWS
CH_PD -> 3.3v EXPWS
RX -> RX AN*
TX -> TX AN*
GPIO0 -> 3.3v EXPWS*
RESET -> 3.3v EXPWS*
Arduino
GND -> GND EXPWS
GND -> Reset AN*

I have tested various configurations of these.  GPIO0 to ground, Reset of ESP to nothing, inverting RX and TX depending on what I am doing, etc.  GND to Reset on the Arduino is when I try to upload to the ESP using the Arduino as a USB TTL converter.  More on that later.

Where I am
I have been able to communicate with the ESP using the Arduino IDE via AT commands in the Serial monitor.  I have connected the ESP to my WiFi network, can ping it from my Mac, and have set the default baud rate to 9600.
Things I cannot do
I cannot access AT commands when this sketch is uploaded to the Arduino:
void setup() {
  Serial.begin(9600);

}

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

}

But I can access AT commands with the following two:
void setup() {
  // put your setup code here, to run once:

}

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

}

and
void setup() {
  int i = 0;

}

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

}

This tells me that trying to use Serial commands is causing a problem.  I considered trying to work the ESP by sending AT commands via Serial communications, but, as per my description above, I received no responses from the ESP.
I also cannot use libraries intended for the ESP, namely WiFiEsp.  I receive the error:
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
WiFi shield not present

When I run any example sketches provided by the library (even when I change parameters such as baud rate and adding delay statements to the library code).  Here is a link to that library, you can find the examples there: https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino
I also cannot upload sketches directly to the ESP using the Arduino as a USB TTL converter.  I have tried grounding the Arduino reset pin while uploading, grounding it during compiling then pulling that connection when it starts to upload, and doing nothing to the Arduino reset pin.  I have tried different combinations with the GPIO0 pin (ground, vcc, nothing), as well as the other pins.
Conclusion
I am really open to some suggestions here.  The root of the problem seems to be Serial communications - it is the common thread between basic sketches on the Arduino and uploading to the ESP itself.  I have four of these modules and all of them behave the same way.  If I can't get a solution here, I'm going to have to give them back to Satan.

From your connections I guess, you try to use the USB to Serial chip on the Nano to communicate with the ESP directly through the serial monitor. Then it is no wonder, that you cannot communicate that way, when you initialize Serial on the Nano. Keep in mind, that you have 3 devices connected to the same UART interface. That's not good. You may want to try using a SoftwareSerial interface for the ESP and forward data from Serial to SoftwareSerial. Then you can still use Serial for debug messages

Have you tried the WiFiESP library while still having Arduino RX to ESP RX and Arduino TX to ESP TX?

Do yourself a favour and get a 2$ USB TTL converter, flash the esp01 with Arduino software instead of wasting ttime with crutch solutions based on the espressif AT firmware (probably outdated and buggy) Development for this stopped end 2018, Arduino is still active - current 2.6.3. The esp01 is compared to the nano superioir (CPU, flash, connectivity) So in most use cases you can drop the nano

upvote for spending time on your question

First, when you use your Serial for Serial Monitor, you will need another port for communicating with ESP-01, in the case of Nano, since it has only one Serial port, so you will need SoftwareSerial. Secondly, I've been through what you (and many of others) experienced before and have tried WiFiESP, it doesn't work for me and the developer seems stop maintaining the library long ago. I use a library that I fork and fixed some minor bug and modified it  that you can find in my github. It is very stable and use only 11-bytes SRAM.

Wow this was complicated to figure out.  I am able to upload code to the esp, though it doesn't run yet.
Thanks to all who commented, the suggestions did not solve the problem, but they pointed me in the right direction.  Rather than using my Arduino to interface with the ESP01, I switched to a Raspberry Pi so that I could connect it directly to the pins of the computer doing the flashing.  Beyond that, it is still a complicated process, which I will go through here:
Wiring
Format: ESP -> Raspberry Pi
VCC -> 3.3v (I used a breadboard to allow multiple connections)
CH_EN -> 3.3v
GND -> GND
GPIO0 -> GND
TX -> RXD (GPIO 15)
RX -> TXD (GPIO 14)
GPIO0 needs to be connected to GND before you connect VCC to 3.3v.  The purpose of this is so that the chip boots in programming mode.
Uploading
My methodology may be less useful for some, but there is probably something useful here for others.
My Raspberry Pi is headless so I needed to interface with the ESP via command line.  Arduino does not have up to date resources for this, so I tried a couple of my own.

First, I tried Arduino-cli - a package that can be downloaded from GitHub to compile and upload.  I followed the tutorial provided by the video on the page posted below, but Arduino-cli requires you to include the FQBN of the device you are uploading to.  I could not find this for the ESP and my Raspberry Pi did not recognize it on its own, so this was ultimately a dead end for me.

https://www.hackster.io/jithinsanal1610/arduino-cli-c26e6e

esptool.py requires python and can be installed using pip.  I created a virtual environment for the package to keep it separate from the rest of my system.  The tool had trouble compiling sketches, so I used the Arduino Ide on my Mac, exported a compiled binary, and then transferred that to the Raspberry Pi via a smb drive.  Using the command below, I was able to flash the compiled file to my ESP01.
esptool.py --port /dev/ttyS0 write_flash 0x1000 SketchFolder/Sketch.ino.generic.bin

Now here is the important part.  Restart the ESP01 after each flash attempt.  Unplug it from VCC, plug it back in, then upload.  If you upload successfully, then run the exact same command again, it will not upload!  I suspect this may be the same problem I was running into when I was originally using the Arduino Ide. I haven't tested this, but I received a similar message when uploads failed on the Arduino and esptool.py:
Connecting: ----....----....----
Failed to connect

and
Invalid head of packet

These are not copy/pasted error messages, but they should be enough for anyone googling the error.
It is also worth noting that I used an AT command previously to change the default baud rate to 9600.  I specified in the esptool.py command -b 9600.  This did not allow me to upload.  Leave the command alone - the default is 115200 but you don't need to specify it even if you changed the ESP baud rate (though it may be the case that I reset this somehow.  I really don't know enough about the board to say).
Conclusion
There are a lot of bad resources out there for this board.  Frankly, I would have bought a different one had I known.  But it taunted me, and I don't play games.  Good luck to anyone else who tries to work with this board!  I am going to post a new question for my current problem, but for now I would say this one deserves to be marked as solved.

source: Stack Exchange

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

sort: votes


text:
ESP8266 12-E can't connect to any Access Point with converted variables from strings to char arrays
I'm using an esp8266 12-E nodemcu
I wrote a code that scans the available WiFi networks, print them through serial communication,ask the user which network he wants to connect to and then the password for that network. The problem is that the nodemcu won't connect to that network. I think that the problem is when I convert the strings buffer_pw and buffer_ssid to the char arrays password and ssid. Why does it give problems to connect?
#include <ESP8266WiFi.h>

int num_ap; //number of access points
String buffer_ssid = "empty"; //temporary stores the ssid in here because then it has to be converted in a char array
String buffer_pw = "empty"; //temporary stores password and same thing as^^
bool askPW = false; //"Did I already ask the password?"
bool connesso = false; //"Did I already connect?"

void setup()
{
  Serial.begin(9600);
  WiFi.mode(WIFI_STA); //put the nodemcu in sta mode so that it can connect to access points
  WiFi.disconnect();   //it disconnects from any access point it was connected to
  Serial.println("Setup completo");
  num_ap = WiFi.scanNetworks(); //scans for access points
  if (num_ap == 0)   //if there aren't any access points available
  {
    Serial.println("Nessun Access Point rilevato");
  }
  else //if there are some access points available
  {
    Serial.println("Access Point rilevati:");
    delay(200);
    for (int i = 0; i < num_ap; i++)
    {
      Serial.println(" ");
      Serial.print(i + 1);
      Serial.print(") ");
      Serial.print(WiFi.SSID(i)); //print access point's ssid
      Serial.print(" ");
      Serial.print("(Potenza segnale: ");
      Serial.print(WiFi.RSSI(i)); //prints access point's rssi(strength of signal)
      Serial.print(")");
      delay(50);
    }
    delay(500);
    Serial.println(" ");
    Serial.println(" ");
    Serial.println("A quale Access Point ti vuoi connettere?");

  }
}

void loop()
{
  if (buffer_ssid == "empty") //if the variable has the standard value "empty" so if the user has already given an ssid. I need this to execute  this piece of code once
   {
    if (Serial.available() > 0)
     {
      buffer_ssid = Serial.readString();  //stores user input(the ssid) in buffer_ssid
      if (buffer_ssid != "empty") //if the variable isn't empty(if the code has successfully saved the ssid) prints the ssid
       {
        Serial.println(buffer_ssid);
       }
     }
   }

  if(buffer_ssid != "empty") //if the user has given an ssid
  {
   if(askPW == false) //if the code has asked the password(I need this in order to execute this piece of code once)
    {
     Serial.println("Inserire la password per connettersi all'Access Point, se non serve premere spazio e invio"); //"insert the password"
     askPW = true;
    }
    if (Serial.available() > 0)
    {
      buffer_pw = Serial.readString(); //saves user input(the password) in the variable buffer_pw
      if(buffer_pw != "empty") //if the code has successfully saved the password so it hasn't the standard value "empty"
      {
        Serial.println(buffer_pw);
      }
    }
  }

  if (buffer_pw != "empty" && buffer_ssid != "empty") //if buffer_ssid and buffer_pw aren't "empty", so if the user inserted them
  {
    if(connesso == false) //in order to execute this piece of code once
    {
     //converts the strings buffer_ssid and buffer_pw in char arrays(I have to do this because WiFi.begin() doesn't accept strings)
     char ssid[buffer_ssid.length()];
     buffer_ssid.toCharArray(ssid,buffer_ssid.length());
     char password[buffer_pw.length()];
     buffer_pw.toCharArray(password,buffer_pw.length());
     //start connecting
     Serial.println("Connessione in corso");
     Serial.println(ssid); //prints ssid
     Serial.println(password);//prints password so I know that they were converted succesffully
     WiFi.begin(ssid,password);//start connecting
     while(WiFi.status() != WL_CONNECTED) //while it's not connected
     {
      Serial.print(".");
      delay(500);
     }
      Serial.println("Connesso!"); //"Connected!"
      Serial.println("Il mio ip locale: ");
      Serial.print(WiFi.localIP()); //nodemcu's local IP

    }
    connesso = true;  //set connesso to true so that this piece of code doesn't loop
  }
}

Don't cross post. You already asked this on SO.

Ok thanks, I won't do that anymore. I did this because a guy in the comment suggested me to ask this question in this Stack Exchange

Problem is that you set to toCharArray the length of the String. But the second parameter is the maximum allowed length of the output and there is then no space for the terminating zero and string is cut at last character.
The function toCharArray knows the size of the String. The second parameter should be the size of the char array buffer_ssid.toCharArray(ssid, sizeof(ssid));
And next problem could be that you copy the CR/LF characters from input into ssid and password. You can see it in debug printouts.

Thank you very much! One thing is that I had to add "- 1" to the char length, so now it is:                                                                                char ssid[buffer_ssid.length() - 1];
char password[buffer_pw.length()  - 1];

because you left the CR/LF there. this cuts it out. but it is not the right solution. set None or only CR or LF in Serial Monitor and it will be wrong again

@MyAlexro  You're better off avoiding the arrays altogether. You don't need to copy the String contents into them - just use the c_str() String method. You'd call WiFi.begin(buffer_ssid.c_str(), buffer_pw.c_str()) and skip the copies and char[]s. c_str() is very efficient; it just returns a pointer to the String's internal character buffer. Of course, after you trim the CRLF from the end of your Strings.

@JohnRomkey Ok thanks, I didn't know that function

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


text:
Correct way of having loop end when required?
I'm brand new to Arduinos. I'm currently trying to modify a script from here which at the moment, simply turns an LED on or off depending on which HTTP GET request it receives. However, I want to modify this to have the LED modulate on/off when presented with the On HTTP GET request and then simply turn off all together when presented with the Off HTTP GET request. However, I have two conflicting methods that I have found about how to achieve this; the first is:
int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      do
      {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      } while (value = HIGH);
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

Wheareas the other is:
  int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      void loop() {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      }
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

As you can see, the first uses do...while and the second uses loop(). I have a feeling that the first of the two scripts would be more suitable as it should cut out as soon as value is set to LOW (i.e. when requested to turn off)
However, I would really appreciate it if someone could look through the two scripts and tell me which of the two is the correct way to achieve this sort of cut off when the HTTP GET Off is requested (if either for them even is the correct way to do this!).
Thank you in advance for your help,
Kind regards,
Tom

Unfortunately they're both completely wrong. Use a state machine instead.

@IgnacioVazquez-Abrams Thank you for your response; that's a shame, how would I do that?

how does the do...while loop exit in the first snippet?

I assumed that when the off get request is made, you can see from the script that"value" is set to LOW and when this condition is met, the loop should exit

examine the example codes that are part of the Arduino IDE .... pay attention to the use of setup() and loop()   ....... have a very close look at the flashWithoutDelay sketch ..... in your program, set a flag when you receive an HTTP request ..... then in the code that follows the HTTP check, flash LED if flag is set .... turn off LED if flag is not set

also have a look at how the original code is formatted ... the indentation and the positioning of braces {} ..... then look at your code .... your code is badly formatted, so it is harder to read (hard to follow the program flow)

With the do...while value never changes to LOW, since the code that changes it is outside of the do...while and isn’t being run while value is HIGH. try moving the int value... outside the loop function (i.e. global variable), and removing the do...while (only leave the code inside it). Not sure if checking http requests only every 8 seconds will work.

@jsotola Thanks for your response. That sounds like a great solution for this problem. I've had a look for that example sketch and couldn't find it. If it possible and if it is not too much to ask, would you please mind showing how I'd do this in an Answer format as I have very little programming experience with the Arduino IDE. Thank you

@Gerben Thank you for your comment. I understand the solution you are trying to suggest but I agree that I feel checking for a request every 8 seconds only will not work as the request itself would have to be made at exactly the right time. Any other solution you can think of?

The network stuff works in parallel to your code, so it might work.

@Gerben I'll give that a shot in a bit. Might it be better two have two separate loops going at the same time if that is even possible? I.e. one loop which is constantly ready for a new get request and another which can handle the do...while loop as the first loop is then free to change the "value" at any time which could stop the second loop if you see what I mean?

I don’t know if you can (simply) do multithreading on the ESP. a better solution is to do the blinking based on the millis value. That way you don’t need any delays. See the Arduino “blink without delay” page.

As pointed out by Ignacio Vazquez-Abrams and jsotola, you need to use a
state machine, like the one from the Blink Without Delay
Arduino tutorial. Yours would be slightly more complicated because you
need a way to turn it on and off, and because you use different on and
off periods. Here is an example code that abstract the blinking logic
into three functions:

update_led() takes care of the blinking, and it has to be called
quite often in order to achieve a smooth blinking
start_blinking() and stop_blinking(), as their names suggest, are
used to turn the blinking state machine on and off.

const uint32_t ON_TIME  = 3000;
const uint32_t OFF_TIME = 5000;

bool led_blinking;     // are we blinking the LED?
bool led_on;           // is the LED currently on?
uint32_t last_toggle;  // last time it toggled while blinking

void update_led() {
    if (!led_blinking) return;
    uint32_t now = millis();
    if (led_on && now - last_toggle >= ON_TIME) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now;
    }
    if (!led_on && now - last_toggle >= OFF_TIME) {
        digitalWrite(ledPin, HIGH);
        led_on = true;
        last_toggle = now;
    }
}

void start_blinking() {
    digitalWrite(ledPin, HIGH);
    led_blinking = true;
    led_on = true;
    last_toggle = millis();
}

void stop_blinking() {
    digitalWrite(ledPin, LOW);
    led_blinking = false;
    led_on = false;
}

You then have to call these functions from loop() as follows:
void loop() {
    // Keep the LED blinking if necessary.
    update_led();
    ...
    if (request.indexOf("/LED=ON") != -1)  {
        start_blinking();
    }
    if (request.indexOf("/LED=OFF") != -1)  {
        stop_blinking();
    }
    ...
}

Edit, in response to jsotola’s comments:
When answering the question, I was initially tempted to make a
BlinkingLed class, with the functions as its public interface and the
variables private. I resisted the temptation on the grounds that, given
the apparent OP’s level of C++ knowledge, that could end up being well
over his head. Instead, I used documentation as an informal way of
separating the public from the private: you are only supposed to use
what is documented, i.e. the functions. You don't “take a shortcut in
your program and clear led_blinking directly”.
You could, of course, make the led_blinking variable part of the
public interface. That could even be a nice simplification, as you don't
need the start/stop function anymore. But then you loose control over
the initial phase of the blinking pattern. That may not be an issue, but
if you want the LED to turn on as soon as you set led_blinking to
true, then you have to do something like
void update_led() {
    uint32_t now = millis();
    if (!led_blinking) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now - OFF_TIME;  // fix initial phase
        return;
    }
    ...
}

Note that the subtraction can overflow, but that's not as issue because
it follows the rules of modular arithmetics.
I actually kind of like this option, with all the logic in a single
function. This way the variables led_on and last_toggle can be made
static local to the function, which provides true encapsulation without
a class. However, from a pedagogic point of view, I think my initial
proposal is easier to understand.

Thank you so much for your answer! This is exactly what I was looking for! I appreciate all the help that people have supplied me with in the comments but I really appreciate the fact that you have been able to break down the problem into understandable chunks and provide a well structured answer. Thank you!

change this line if (!led_blinking) return;  so that it turns off the LED and then returns

@jsotola I'm confused as to what you mean. Are you saying that this line he has written is incorrect? If so, what should the line read?

no, i am not saying that it was written wrong ... the LED will certainly stop blinking when led_blinking==false ..... if led_blinking is cleared (set to false) by the stop_blinking() function, then the LED will be off ..... however, if you take a shortcut in your program and clear led_blinking directly without calling stop_blinking(), then the LED will stop blinking, but it may be on

@jsotala Ah, I see, that makes sense. How exactly would I adapt that code to have it that when led_blinking==false, the led will turn off completely even if currently on? Would you be able to post some code which may help fix this problem? Thank you very much :)

i do not understand why you are asking for code .... you already have the if (!led_blinking) line given to you by Edgar Bonet ... and you have previously written the turnoff code in what you posted .... look at the second if statement .... just insert the code for turning off the LED before the return command

@jsotola: I am responding to your comments in an edit to my answer.


text:
Entire arrays are not read by Processing sent by Arduino unless cord is unplugged and plugged back in?
I am using an Arduino to read sensors and then send the data to the serial port for Processing to read. It works totally fine when I first download the code and run the Processing program. But if I stop the Processing code and then start it again I will get the error ArrayIndexOutOfBounds. I print the array that Processing reads and it is only 3 indexes long, even though the Arduino code should be sending an array that's 7 long. This error happens because I am calling an index that doesn't exist, but it should exist, Processing just isn't receiving the entire array. If I unplug the USB cord from the Arduino and plug it back in this error won't happen and Processing will receive the entire array. I don't understand why this is happening. I have tried using the button on the Arduino to reset it each time before running the Processing code but this doesn't work, I actually need to unplug the cord and plug it back in.
If you have any input that would be great! Thanks in advance!
EDIT:
I am posting the code because it was requested. There's a lot of unnecessary stuff on reading the sensors and creating graphics for in Processing. The gist is that the user interacts with a Processing program and clicks when the want the data sent by Arduino to be saved. I had been talking to someone else about the problems Ive been having and they think it may have to do with the serial buffer, and that I need to clear it or wait for it to be cleared. I have looked into this and am having trouble figuring out the proper way to do it. I have tried resetting the Arduino code using SoftRestart library, but that hasn't worked.
Here's the Arduino Code:
//need to include these libraries to be able to read from serial and read   the sensors
#include <SoftwareSerial.h>
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <AMS5915.h>
#include <AMS5812.h>
#include <Adafruit_ADS1015.h>

//Create sensor objects.
Adafruit_MCP9808 tempsensor18 = Adafruit_MCP9808(); //sensor with 0x18 address is Dry Bulb Temp
Adafruit_MCP9808 tempsensor19 = Adafruit_MCP9808(); //sensor with 0x19 address is Temp in chamber
Adafruit_BME280 bme; //pressure and humidity sensor
AMS5915 amsD; //sensor being used for reading differential pressure across the nozzle
AMS5812 amsS; //sensor being used to measure static pressure in the chamber
Adafruit_ADS1115 ads; //16-bit ADC sensor (actually 15-bit when used as a single-ended ADC)

//Initializing variables
float tableVals[]={0,0,0,0,0,0,0,0}; //an array that will hold sensor values. If more sensors or readings are added the size of the array needs to increase
float relHum=0;
float dryBulb=0;
float wetBulb=0;
float pressure=0;
float chamberTemp=0;
float pressureDiff;
float pressureStatic;
float rpm;
float correctedADC=0;
float correctedRPM;
float correctedADCx2=0;
float correctedRPMx2=0;
int counts=0;
const float AMS5915_0010_D_B_P_MIN = -10.0;     // minimum pressure, millibar (for sensor reading differential pressure)
const float AMS5915_0010_D_B_P_MAX = 10.0;      // maximum pressure, millibar (for sensor reading differential pressure)
const float AMS5812_0003_D_B_P_MIN = -0.3;      // minimum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_P_MAX = 0.3;       // maximum pressure, PSI (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MIN = -25.0;     // minimum temperature, C (for sensor reading static pressure)
const float AMS5812_0003_D_B_T_MAX = 85.0;      // maximum temperature, C (for sensor reading static pressure)

//Setup function, will run one time. Initializes sensors
void setup() {
  Serial.begin(9600); //set baud rate
  amsD.getAddr_AMS5915(AMS5915_DEFAULT_ADDRESS);   // 0x28
  amsS.getAddr_AMS5812(AMS5812_DEFAULT_ADDRESS);   // 0x78
  ads.setGain(GAIN_ONE); //1x gain +/- 4.096V  1 bit = 0.125mV
  ads.begin(); //starting sensors
  amsD.begin();
  amsD.begin();
  if(!tempsensor18.begin(0x18) || !tempsensor19.begin(0x19)|| !bme.begin())    {  //wait until these sensors are ready
    while(1);
  }
}

//loop function keeps repeating
 void loop() {
  if (counts >100){  //will only enter conditional if counts variable is over 100
    readSensors(); //go to readSensors function below

    tableVals[0]= pressure; //set pressure to the first index in array
    tableVals[1]=relHum;  //rel hum to the second index in array
    tableVals[2]=wetBulb; //wet bulb to the third index in array
    tableVals[3]=dryBulb; //dry bulb to the fourth index in array
    tableVals[4]=chamberTemp; //chamber temperature to the fifth index in the array
    tableVals[5]=pressureDiff; //differential pressure to the sixth index in the array
    tableVals[6]=pressureStatic; //static pressure to the seventh index in the array
    tableVals[7]=rpm; //RPM is the eighth index in the array
    Serial.flush();
    Serial.print(tableVals[0]); //sending all the values to Processing, need commas so Processing can split into different values (don't totally know why I put everything in an array first, that's just how I saw it done in an example)
    Serial.print(",");
    Serial.print(tableVals[1]);
    Serial.print(",");
    Serial.print(tableVals[2]);
    Serial.print(",");
    Serial.print(tableVals[3]);
    Serial.print(",");
    Serial.print(tableVals[4]);
    Serial.print(",");
    Serial.print(tableVals[5],4);
    Serial.print(",");
    Serial.print(tableVals[6],4);
    Serial.print(",");
    Serial.print(tableVals[7]);
    Serial.println(","); //need this last comma for some reason or it gets messed up
    counts=0; //reset counts variable to 0
  }
  counts++; //increment counts
}

//This function is called in the loop() function. It reads all of the sensors
void readSensors(){
  dryBulb = tempsensor18.readTempC(); //read from temp sensor with 0x18 address
  relHum = bme.readHumidity();  //read humidity from bme sensor
  pressure = bme.readPressure()/100.0F; //read pressure, in hpa
  pressure = pressure * 0.029529983071445; //convert pressure to inches of mercury
  wetBulb = dryBulb*atan(0.151977*pow(relHum + 8.313659, 0.5)) + atan(dryBulb +relHum) - atan(relHum - 1.676331) + 0.00391838*pow(relHum,1.5)*atan(0.023101*relHum) - 4.686035; //equation finds approximate wet bulb temp from humidity and dry bulb temp
  chamberTemp = tempsensor19.readTempC(); //read from temp sensor with 0x19 address

  //this chunk of code gets the differential pressure reading and converts it to inches of water
  byte errorDiff;
  int8_t addressD;

  addressD = amsD.ams_i2cAddress;
  Wire.beginTransmission(addressD);
  errorDiff = Wire.endTransmission();
  if (errorDiff == 0){
    amsD.Measure_PressureAndTemperature(AMS5915_0010_D_B_P_MIN, AMS5915_0010_D_B_P_MAX);
    pressureDiff=amsD.getPressure();
    pressureDiff = pressureDiff * 0.40146307866177;
  }

  //this chunk of code gets the static pressure reading and converts to inches of water
  byte errorStatic;
  int8_t addressS;

  addressS = amsS.ams_i2cAddress;
  Wire.beginTransmission(addressS);
  errorStatic = Wire.endTransmission();
  if(errorStatic == 0){
    amsS.Measure_PressureAndTemperature(AMS5812_0003_D_B_P_MIN, AMS5812_0003_D_B_P_MAX, AMS5812_0003_D_B_T_MIN, AMS5812_0003_D_B_T_MAX);
    pressureStatic = amsS.getPressure();
    pressureStatic = pressureStatic*27.679904842545;
  }

  //the next chunk of code takes 300 readings from the ADC, averages them together. Applies two correction equations to the ADC and then converts it to the RPM that is sent to Processing
  float ADCcount=0;
  float ADCtotal=0;
  float finalADC=0;

  int16_t adc0;
  while(ADCcount<100){ //taking 100 ADC readings and averaging them
    adc0 = ads.readADC_SingleEnded(0);
    ADCcount=ADCcount+1;
    ADCtotal=ADCtotal+adc0;
  }

  finalADC=ADCtotal/ADCcount;
  rpm = (40740.0/32767.0)*finalADC;
}

Processing Code:
//initializing variables
import processing.serial.*; //need this library to read serial data
Serial myPort;
int signal=0; //this will signal what part of the draw function to read
Table table;
int count =-1;
int lf = 10; //10 is the ASCII number that represents an enter key
String d_string;
String m_string;
String y_string;
float countVals[];
float pressureVals[];
String voltage=""; //these variables need to be blank strings since these are the variables that come from user input
String current=""; //they will be changed to floats before being saved in the table
String fileName="";
String COM ="";
float Pdiff;
float Pstatic;

//Set up
void setup(){
  size(300,410); //creating the start graphics
  background(255);
  String s = "Click on the rectangle to start.";
  textSize(20);
  textAlign(CENTER);
  fill(25);
  text(s,10,10, 290, 150);
  fill(255, 0, 0);
  rectMode(CORNERS);
  rect(115,85,195,160); //drawing rectangle 'button'

  table = new Table();  //create new table
  table.addColumn("Date");  //make a Date column
  table.addColumn("Reading Number"); //make a Reading Number column
  table.addColumn("Voltage V");  //Voltage column
  table.addColumn("Current A");  //Current column
  table.addColumn("Pressure inHg"); //Pressure column
  table.addColumn("Humidity %");  //Relative Humidity column
  table.addColumn("Wet Bulb Temp. *C");  //Wet Bulb Temp. column
  table.addColumn("Dry Bulb Temp. *C");  //Dry Bulb temp. column
  table.addColumn("Chamber Temp. *C"); //Chamber Temp column
  table.addColumn("Static Pressure inH20");  //Static pressure column
  table.addColumn("Differential Pressure inH2O"); //Differential Pressure column
  table.addColumn("RPM");  //RPM column

  int day = day();  //Find the day
  int month = month(); //find the month
  int year = year();  //find the year
  d_string = str(day);  //convert these integers to strings
  m_string = str(month);
  y_string = str(year);
}

//Draw function is continuously looping
   void draw(){
      if(signal==1){ //if signal is 1 (set in keyPressed) ask the user to enter the COM
        background(255);
        String f = "Enter what number in the list of COM Ports the Arduino is plugged into (This is not necessarily the COM number.) \nPress ENTER to continue.";
        textAlign(CENTER); //center the text on the screen
        fill(25); //setting fill color
        stroke(0);  //setting stroke color
        textSize(14); //setting text size
        text(f,10,10,290,200); //displaying the instructions in the graphics box
        textSize(20); //resetting text size
        text(COM,10,125,290,200); //displaying the COM the user is typing
      }
      else if (signal==2){ //if signal is 2 (set in keyPressed) ask the user to enter the name of the CSV file where the data will be saved
        background(255);
        String f = "Enter the name of the CSV file where the data will be saved. \nThis will be located in the folder called 'data' that is in the same folder as this application. \nPress ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(12);
        text(f,10,10,290,200); //displaying instructions to the user
        textSize(20);
        text(fileName,10,125,290,200); //displaying the user file name the user is typing
      }
      else if(signal==3){ //if signal is 3 (set in keyPressed) ask the user to input the voltage
        background(255);
        String f = "Enter the Voltage in Volts. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions to the user
        text(voltage,10,125,290,200); //displaying the voltage the user is typing
      }
      else if(signal ==4){ //if signal variable is 5 (set in conditional above) ask the user to input the current
        background(255);
        String f = "Enter the Current in Amps. Press ENTER to continue.";
        textAlign(CENTER);
        fill(25);
        stroke(0);
        textSize(20);
        text(f,10,10,290,200); //displaying instructions
        text(current, 10,125,290,200); //displaying the current the user is typing
      }
       else if (signal ==5){ //if signal variable is 4 (set in mousePressed) then read the following chunk of code.
        String val=null;
        while (val==null){
          val = myPort.readStringUntil('\n'); //read serial data sent by Arduino
        }
            val = trim(val); //trim off any white space
            countVals = float(split(val, ',')); //split serial data into individual readings
            delay(500);
            signal =6; //set signal to 6 so next chunk of code will be read
      }
       else if (signal ==6){ //if signal is 6 (set in the above conditional) read the following chunk of code
        TableRow newRow = table.addRow(); //add a row to the spreadsheet
    newRow.setString("Date", m_string +"."+ d_string +"."+ y_string); //write data in the correct columns in the table
    newRow.setInt("Reading Number", count);
    newRow.setFloat("Pressure inHg", countVals[0]);
    newRow.setFloat("Humidity %", countVals[1]);
    newRow.setFloat("Wet Bulb Temp. *C", countVals[2]);
    newRow.setFloat("Dry Bulb Temp. *C", countVals[3]);
    newRow.setFloat("Chamber Temp. *C", countVals[4]);
    newRow.setFloat("Differential Pressure inH2O", countVals[5]);
    newRow.setFloat("Static Pressure inH20", countVals[6]);
    newRow.setFloat("Voltage V", float(voltage)); //values that were strings are converted to floats
    newRow.setFloat("Current A", float(current));
    newRow.setFloat("RPM", round(countVals[7]));
    saveTable(table, "data/"+fileName+".csv"); //saving the data in a folder called 'data' in a file with the user given name
    signal = 7; //signal variable back to 7 to read the next conditional
  }
  if(signal ==7){ //if signal is 7 (set in conditional above or in keyPressed), read serial port data and display graphics Draw function will continue to loop through this conditional until box is clicked so pressures are always updated.
    String pressures=null;
    while(pressures==null){
      pressures = myPort.readStringUntil('\n'); //read serial data sent by Arduino
    }
        pressures = trim(pressures); //trim off any white space
        pressureVals = float(split(pressures, ',')); //split serial data into individual readings
        println(pressureVals);
        background(255);  //reset graphics
        String s = "Click on rectangle to take a data point. Exit out of this box when done.";
        stroke(0);
        textSize(15);
        fill(25);
        textAlign(CENTER);
        text(s,10,10,290,100); //displaying instructions to user
        fill(50, 255, 200);
        rect(115,85,195,160);
        fill(0);
        textSize(12);
        textAlign(LEFT); //next line will display the previous data point if it is not the first data reading (counts needs to be 1 or greater)
        if (count>0) text("Previous Data Point: \n\t" +"Barometric Pressure inHg: " + str(countVals[0]) +"\n\tHumidity %: " +str(countVals[1]) + "\n\tWet Bulb Temp *C: " + str(countVals[2]) + "\n\tDry Bulb Temp *C: " +str(countVals[3]) +"\n\tChamber Temp *C: " + str(countVals[4])+"\n\tDifferential Pressure inH20: " + str(countVals[5]) +"\n\tStatic Pressure inH20: "+ str(countVals[6]) + "\n\tRevolutions Per Min: " + str(round(countVals[7])),10,190, 300,400);
        textAlign(10, 400);
        text("Static: " +str(pressureVals[6]) + " in.H20", 10,400); //display the static pressure on the bottom of graphics window
        textAlign(150, 400);
        text("Diff: "+ str(pressureVals[5]) + " in.H20", 150, 400); //display the differential pressure on the bottom of graphics window
  }
}

//mousePressed function will run when mouse is clicked in box
void mousePressed(){
  if(mouseX <= 195 && mouseX >= 115 && mouseY <=160 && mouseY >=85){ //if the mouse is clicked within the boundaries of the rectangle
     if(count>=0){ //if counts is greater or equal to 0 (counts starts at -1, this was b/c there were some glitches with the first click being registered)
       signal=5;
       String d= "DATA TAKEN"; //display "DATA TAKEN" to signal that a data point was taken
       textSize(15);
       fill(255,0,50);
       textAlign(LEFT);
       text(d, 107, 180);
    }
    else{   //will run if counts is not greater than or equal to 0 (so this will just be on the first click before data is taken)
      signal=1;
    }
    count++; //increment count
    mousePressed = false;  //set mousePressed to false to make sure this function doesn't run again.
  }
}

//keyPressed will run when a key on the keyboard is pressed
void keyPressed() {
  if(signal==1){ //if signal variable is 1...
    if(key==BACKSPACE){ //if the key pressed is BACKSPACE
      if(COM.length()>0){ //if length of what is being typed is greater than 0
        COM = COM.substring(0,COM.length()-1);  //then get rid of the last character
      }
    }
    else if (textWidth(COM+key) < width && key != ENTER){ //if what is being typed is not greater than the width of the graphics window and the key pressed is not ENTER
      COM = COM +key; //add the key pressed to the end of what is being typed
    }
    if(key ==ENTER){ //if ENTER is pressed
      signal=2; //change signal variable
      String portName = Serial.list()[int(COM)]; //COM is not necessarily the COM number the Arduino is plugged into. It's the number in the list of COMS that the COM is listed. I used trial and error to figure this out
      myPort = new Serial(this, portName, 9600);  //setting up baud rate
      myPort.bufferUntil(lf); //I don't know if this is actually necessary
    }
  }
  else if(signal==2){ //if signal variable is 2...
    if(key ==BACKSPACE){ //these first two conditionals for this signal number are the same for all the signal number conditionals.
      if(fileName.length()>0){
        fileName = fileName.substring(0,fileName.length()-1);
      }
    }
    else if (textWidth(fileName+key) < width && key !=ENTER) {
      fileName = fileName +key;
    }
    if (key == ENTER) { //If key pressed is ENTER
      signal=3;  //change signal
    }
  }
  else if(signal==3){ //If signal is 3...
    if(key ==BACKSPACE){
      if(voltage.length()>0){
        voltage = voltage.substring(0,voltage.length()-1);
      }
    }
    else if (textWidth(voltage+key) < width && key!=ENTER) {
      voltage = voltage +key;
    }
    if (key == ENTER) {
        signal=4;
    }
  }
  else if(signal ==4){ //if signal is 4...
    if(key == BACKSPACE){
      if(current.length()>0){
        current = current.substring(0,current.length()-1);
      }
    }
    else if (textWidth(current+key) <width && key != ENTER) {
      current = current + key;
    }
    if (key ==ENTER){
          signal=7; //change signal to 7 and display graphics to take a data point
      key = BACKSPACE;
      background(255);
      String s = "Click on rectangle to take a data point. Exit out of this box when done.";
      stroke(0);
      textSize(15);
      fill(25);
      text(s,10,10,290,100);
      fill(50, 255, 200);
      rect(115,85,195,160);
    }
  }
}

Sorry, this is probably very hard to follow. I do not have that much coding experience so I'm sure my logic isn't very good.

I would suggest that you are seeing reset-stutter from the serial. Basically the sketch is running and filling the serial buffer with data. Then you connect and the board resets, but some data is still in the USB chip's buffer. The sketch then starts running again, and new data is sent.
In effect I am guessing you may be seeing something like:
3.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,
19.44,43.12,14.56,1.01,23.87,4.45,55.13,

where the first line is left over from the previous execution before the reset.  You don't get that with a complete unplug and re-plug because there is no "previous" data in the USB buffer to send.
The simplest solution is just to handle it gracefully.  Take a look at the .length of your float array and see if it's correct or not. Only if it has enough entries in it do you actually want to deal with the data - otherwise, you just throw it away and wait for the next line to arrive.


text:
Serial receiver (Arduino Micro ATmega32U4) in bad state
I have configured two Arduino Micros as a pair of multiplexer/demultiplexers communicating via Tx and Rx.
Everything works great except for one little thing. If I reset the sender (multiplexer) the receiver (demultiplexer) goes into a bad state resulting in random low and high outputs.
Resetting the receiver brings it back to a normal state but I am hoping someone might have a better solution. Using the serial monitor I noticed that during the reset process on the sender there are some seemingly random bits being transmitted toward the end. Not sure if this has anything to do with it.
The code for the sender is:
byte PINBold;
byte PINDold;
byte PINFold;

byte PBmask = B11111110;
byte PDmask = B11010011;
byte PFmask = B11110011;

void setup() {
  Serial1.begin(3704400); // Speed
  DDRB = DDRB & B00000001; // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
  DDRD = DDRD & B00101100; // Sets pins to digital input: 2,3,4,6,12
  DDRF = DDRF & B00001100; // Sets pins to digital input: A0,A1,A2,A3,A4,A5
}

void loop() {
  if (((PINB & PBmask) != PINBold) |((PIND & PDmask) != PINDold) | ((PINF & PFmask) != PINFold)) {
    Serial1.write(PINB);
    Serial1.write(PIND);
    Serial1.write(PINF);

    PINBold = PINB & PBmask;
    PINDold = PIND & PDmask;
    PINFold = PINF & PFmask;
  }
}

The code fore the receiver is:
void setup() {
Serial1.begin(3704400); // Speed
DDRB = DDRB | B11111110; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
DDRD = DDRD | B11010011; // Sets pins to digital output: 2,3,4,6,12
DDRF = DDRF | B11110011; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

PORTB = PORTB | B11111110;
PORTD = PORTD | B11010011;
PORTF = PORTF | B11110011;
}

void loop() {
if (Serial1.available() > 2) {
PORTB = Serial1.read();
PORTD = Serial1.read();
PORTF = Serial1.read();
}
}

There is a bug in your code; in line ████ you should have written ████████ rather than ████████. Try changing it and it will work

Make a protocol for the serial communcation, with a start byte, a checksum and a trailer byte. During reset the tx pin is set as input, thus it is high impedance and will pick up noise. Did you forget a pullup resistor?

@frarugi87 edited to include code.

@Jot I used pull down resistors, should still be okay correct?

@Michael there are some issues in your code; let me write a more complete answer to fix them

@Michael just one question: do you need a full 3*8 byte transfer or you need only 7+5+6 bytes? I mean, you have excluded some pins from the three ports..

The tx signal is idle high. The first low pulse is the startbit. With a pulldown resistor you create a startbit as soon as you reset the arduino. Use a pullup resistor.

@frarugi87 I am only using the pins listed as inputs and I need it to send whenever any pin has changed state.

Without a start byte, a checksum and a trailer byte, at least use the start byte as a sync byte. When you would send the masked value instead of the actual port value, is it possible to send 0xff or 0x01 as sync byte? I think it is possible.

@Jot Switching to a pull up resistor seems to make it work correctly!! I was unsuccessful with a sync byte earlier today, I'll have to play with that some more.

@frarugi87 I've edited my post to include my receiver code. Admittedly this is the extent of my abilities. I tried your codes modifying the receiver to include PORTX = receivedPortX however the receiver is not doing anything. All pins are high. My code works but you have made some great points and some type of protocol would be great.

@Michael I included your code in the receiver code, and added one condition I did not think of previously (when you turn on the receiver, the signal is not sent; now it is). Please tell me whether this works or not; if it doesn't, just tell me and I'll try to test it

@frarugi87 There was no change with the new code.

@Michael sorry, there was a bug. in the receiver, inside the switch, the test with serial available should be >= 3 rather than >3; fixed now; I tested it on two UNOs, using only four bits of PORTB (but now it should work even in your case). Test the two codes

@frarugi87 hmm, Still no change.

@Michael Still one more bug fixed: the Serial1 was Serial in some lines (when sending the 'H' char and when receiving the bytes). Please check with the code now and see if it works (fingers crossed)

@frarugi87 That did it! It appears to function correctly! I will test it thoroughly and report back sometime later. I don't mind telling you this is a piece of equipment in a really cool physics experiment!

@Michael Glad that worked :) As I wrote, I was not able to test it, and so the bugs arose. But in the end we managed to have it working ;)

Ok, there are some issues in your code. First of all, are you sure that a baudrate  of 3.7Mbps is what you need? Can't you go a bit slower?
If you are dealing with mechanical parts (e.g. buttons), then a refresh rate of 100Hz cannot be noticed; to send 3 bytes you need 30 bits, and at 9600 bit/s this means 320 Hz of frequency. Reducing the speed increases the rejection to noise too, so I'd go with a lower speed (even a 38.4kbps is fine).
Then you are reading the PINx registers too many times, which can lead to inconsistency. What happens if the value changes after the if but before the updating of the value? It's better to store it in a variable.
These, however, are not the root cause of your problem. The main issue, as anticipated by Jot, is that you are not using a protocol to synchronize the two elements. This means that at the bootup the receiver does not know if it is at the beginning of the "frame" or in the middle. Moreover start conditions when the sender is not online are not ignored.
So a "protocol" must be agreed between the two. The simplest one I can think of revolves around the fact that you can reserve a bit for the flow control.
Looking at your port masks, I can see that if we split the PINB values in the two nibbles and then move the lowest one one bit to the left, we get that bit 3 is never used for transmitting a pin data:
PINB 76543210 -> 7654x321 (pin 0 was not used)

consequently we use this as a control bit. It has value 1 for the first bit in the frame, and 0 otherwise. On the receiver side, you look for a byte with this bit set, then record also the other two, then check if the other two have a 0 in this position and, if confirmed, you have your frame.
This solution has the highest throughput, but may be a bit fragile when some noise is present (false start of frames, possibly).
For this reason I suggest you to add another byte to the packet, thus having to transmit four bytes. Again, the first one has the bit set in position 3, and the other have zero. But in this case the first byte has a predefined value, and consequently the receiver has just to look for this specific value (and the robustness is increased.
Ok people, I can hear your question. Where is the code? Well, here it is. For the sender, you have to perform a bit of manipulation on the bytes to be sent. I chose the hex value 0x5A because it has a lot of transitions (difficult to replicate from a noise) and it has a 1 bit in position 3. I also changed the things said at the beginning (baud rate and reading PINx only once); feel free to revert the changes if you have different needs. Moreover I initialized the old variables, and I set the direction of the pins based on the mask rather than having it done manually (easier to maintain).
EDIT: I added the possibility to get the current status by sending a char on the serial interface (useful when the receiver boots up)
byte PINBold;
byte PINDold;
byte PINFold;

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

const byte StartOfFrame = 0x5A; // bit 3 is always '1'

void setup()
{
    Serial1.begin(38400); // Speed
    DDRB = DDRB & (~PBmask); // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
    DDRD = DDRD & (~PDmask); // Sets pins to digital input: 2,3,4,6,12
    DDRF = DDRF & (~PFmask); // Sets pins to digital input: A0,A1,A2,A3,A4,A5

    PINBold = ~PBmask; // Force a 1 in a forbidden position -> force a sending at first round
    PINDold = ~PDmask;
    PINFold = ~PFmask;
}

void loop() {
    byte currPINB = PINB & PBmask;
    byte currPIND = PIND & PDmask;
    byte currPINF = PINF & PFmask;

    bool shouldSendData = false;

    if ((currPINB != PINBold) || (currPIND != PINDold) || (currPINF != PINFold))
    {
        PINBold = currPINB;
        PINDold = currPIND;
        PINFold = currPINF;
        shouldSendData = true;
    }

    while (Serial1.available())
    {
        Serial1.read();
        shouldSendData = true;
    }

    if (shouldSendData)
    {
        Serial1.write(StartOfFrame);
        Serial1.write((currPINB & 0xF0) | ((currPINB >> 1) & 0x07)); // send currPINB 7654_321, where _ is a '0'
        Serial1.write(currPIND); // bit 3 is always '0'
        Serial1.write(currPINF); // bit 3 is always '0'
    }
}

On the receiver side, what you need is to wait for the start of frame, then you have your data. I prefer to implement it as a very small state machine. I also added a bonus timeout feature to exit from the payload state after 10ms of inactivity.
EDIT: Added the sending of a char at the beginning, to trigger a resending of the status from the master (if available). Included also the functional code from the question, since the OP added the receiver
const byte StartOfFrame = 0x5A; // bit 3 is always '1'

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

// State machine states
const byte SM_WaitingForSOF = 1;
const byte SM_WaitingForPayload = 2;

byte SM_CurrentState;

bool receivedData;
byte receivedPortB;
byte receivedPortD;
byte receivedPortF;

uint8_t startOfTransmissionMillis;
const byte transmissionTimeout_ms = 10;

void setup()
{
    Serial1.begin(38400); // Speed

    DDRB = DDRB | PBmask; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
    DDRD = DDRD | PDmask; // Sets pins to digital output: 2,3,4,6,12
    DDRF = DDRF | PFmask; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

    SM_CurrentState = SM_WaitingForSOF;
    receivedData = false;
    receivedPortB = 0;
    receivedPortD = 0;
    receivedPortF = 0;

    Serial1.write('H'); // Any byte is ok; it is used to trigger a sending of the status
}

void loop() {
    receivedData = false;

    switch (SM_CurrentState)
    {
        case SM_WaitingForSOF:
            while (Serial1.available() > 0) // can also be a "if"
            {
                if (Serial1.read() == StartOfFrame)
                {
                    SM_CurrentState = SM_WaitingForPayload;
                    startOfTransmissionMillis = (uint8_t)millis();
                    break;
                }
            }
            break;
        case SM_WaitingForPayload:
            if (Serial1.available() >= 3)
            {
                receivedPortB = Serial1.read();
                receivedPortD = Serial1.read();
                receivedPortF = Serial1.read();

                if (((receivedPortB & 0x08) | (receivedPortD & 0x08) | (receivedPortF & 0x08)) == 0)
                { // All the payload bits have '0' as bit 3, so communication was ok
                    receivedData = true;
                }

                SM_CurrentState = SM_WaitingForSOF;
            }
            else if ((((uint8_t)millis()) - startOfTransmissionMillis) > transmissionTimeout_ms)
            {
                SM_CurrentState = SM_WaitingForSOF;
            }
            break;
        default:
            SM_CurrentState = SM_WaitingForSOF;
            break;
    }

    if (receivedData)
    {
        PORTB = (PORTB & (~PBmask)) | (receivedPortB & 0xF0) | ((receivedPortB & 0x07) << 1);
        PORTD = (PORTD & (~PDmask)) | receivedPortD;
        PORTF = (PORTF & (~PFmask)) | receivedPortF;
    }
  }
}

Beware: untested code. I'm confident that no major bugs are present, but some tweaking may be necessary


text:
Two Arduino Control a LCD Display
I´m building a system that has two arduinos (like the image on the botton) linked via ICSP. The "Programer"  programs the second one, called "Worker"( with a .hex file in the SD card of the Programer).
The Worker controls a LCD 16x4 and displays messages to the user.
What I´m tring to do is when the Programmer is programming the Worker it also displays a message like "Programming, wait" in the Worker LCD. But in code, just telling to the Worker displays a message is not going to happen because when it has been programmed it displays garbage in the LCD.
Q So is it possible the the Programmer takes control of the LCD before it begin to program the worker and displays its message?
The LCD works with normal 4-bit mode comunication and I would rather not converte it to I2C if it´s possible.

4-bit mode @jsotola

master / slave?

On the ICSP - Controler master, worker slave. On the LCD the conection is made exclusively by worker (Via Hardware). @tony gil

Have you thought of using I2C for the arduinos as well?  It works pretty well for me and, apparently, would work for you in this application as well.  If you want, I can post an answer expanding on that.  Please advise, otherwise the CONTENT POLICE will shout me down.

"The Worker controls a LCD 16x4 and displays messages to the user. What i´m tring to do is when the Programer is programing the Worker it also displays a message like "Programing, wait" in the Worker LCD, but in code, just telling to the Worker displays a messege is not gonna happen because when its been programmed displays garbage in the LCD" -> this sentence is a bit difficult to parse. Could you please break it down into smaller sentences that are more easy to understand?

@tony gil, yes i did, but for programing is way batter to use ISCP

Thanks for the help @DuckDodgers

Honestly, why put your self through designing a multiplexing solution when LCDs are inexpensive.  I suggest to Keep It Simple and simply use 2 LCDs.  The pain of trying to debug a situation where the "worker" may or may not be talking to the single LCD just sounds terrible.  If you insist on using one LCD I recommend manually switching the LCD between Arduino boards.  This, so you can be certain which Arduino is controlling the LCD.

There may be another solution.  There are some LCDs larger than the standard Hitachi paradigm allows.  Such LCDs appear, in some ways, as 2 independent displays.  But share the same interface.  So there's that.  Let me know if you need more details (that is if you want me to post an answer).  Otherwise it's a bit "off topic" and could be voted down.  So I'll abstain unless there is interest.

There are two solutions that come to my mind, one more HW based and another more SW based.
Solution 1
The HW way is to let the programmer control the LCD through 2:1 multiplexer(s). You will need to connect the LCD pins to the common pin of the multiplexer, the Programmer's ones to one of the two inputs and the Worker's to the other. Then the programmer can choose who controls the LCD through the additional pin. An example of the multiplexer you can choose is the 74LS157, but there are virtually infinite part numbers. The disadvantage of this approach is that you need to write the whole LCD control stack in the Programmer.
Solution 2
An alternative, more relying on the SW, is implementing a way to let the slave know that you want to program it. For instance, when a programming is needed the Programmer raises a pin; the Worker writes the string on the LCD, then stops working, raises another pin and waits to be cleared. The programmer then proceeds to flash the Worker, and the message will remain on the LCD. It may happen that garbage exits from the Worker's pins when being programmed. If so, change the enable pin or find a way to temporarily detach it from the Worker to avoid signals reaching the LCD. This schematic illustrates this concept:

simulate this circuit – Schematic created using CircuitLab
When the Programmer wants to program the unit, it sets the DL_Req pin to high. The Worker sees this, and performs accordingly. I think pins are not moved then, but if for instance some noise appears on the signals during programming (and the LCD displays this noise as weird chars), try changing the pin associated to the enable pins (LCD2 in the example above) or put something to prevent noise on that wire only, so that LCD content is not modified.
Personally I'd go with the second solution, but this depends on how much you can change the behavior of the worker and programmer

I rlly liked the second aproach, but will not generate conflict between the boards?, because the worker needs acess to the enable pin as well, or the enable pin is set to high all the time that the worker is sending information? what i understant is to leave the enable pin to the controler and data bus and RS pin in common to both boards, right?

@Dalequeiroz no, in the second approach the Programmer does not have access to the enable or any other pin of the LCD. I'm not sure if in the programming phase the arduino pins are moved (I think only pin 13 - connected to the onboard led - is changed during programming). I will add a sort of block diagram to the answer for the second solution to explain better

i liked that aproach, in this way i can control when to display the message that i what and when to activate the controller, i will try and give it a feedback, but i think it will work firne.

If you let the worker pull up the enable pin only with it's internal pullup resistor (not actively driven high), the programmer can pull it down without doing any harm, disabling the LCD. If the logic is inverse (LOW for enabled), you could do this with an external pulldown resistor

@chrisl this is a good solution if all the Worker's pins are moving randomly during programming. Or even using a series resistor to let the Programmer decide whether to control the EN pin or not. In any case I think it will not be necessary, since usually pins remain to a stable state when programming


text:
Transistors to use for eight voltage sweeps from two PWM Arduino pins
On my Arduino Mega, there are two PWM pins open. There are eight analog voltage inputs to a datalogger. They are connected through a PCB, and I need test them with a DC voltage sweep. (There are many boards, so that is why I'm making a testing device instead of manually doing each with a variable power supply.)
As an analogy, it's like using four DMMs to measure the the same +Vcc to see if each DMM works.
Is some sort of amplifier circuit needed to output a maximum of 5 V to the eight datalogger inputs? Is an external power source needed? Please give me some direction.
The DC sweep does not have to go to 5 V. For what it's worth:

for(int s = 51; s < 256; s += 51)
{           // PWM: 255 = 5V
  analogWrite(analogWpin, s);      // sweeps thru 1, 2, 3, 4 & 5 V
  delay(500);
  analogWrite(analogWpin, 0);
  delay(500);
}

Related

Connecting many RGB LEDs to same PWM pins?
Controlling multiple pc fans with single pwm pin
Controlling multiple fans using arduino uno
Multiple DC motors from 1 pwm

Can each analog input can have the same value, or is it necessary to give different voltages to each input? Do you need to test them at the same time?

There is a module with the AD5669. It is a 8-channel 16-bit dac. Adafruit and sparkfun have a MCP4725 module, a 1-channel 12-bit dac, perhaps there is a way to use eight of those.

@chrisl It's just sweeping each with the same increasing value. It doesn't have to happen at the exact same time. All the test is doing is showing if the PCB is all connected correctly and functioning properly.

@AdamUraynar then you still can not keep the other channels open/unconnected. To detect a shortcut between channels, you still need to connect the other channels to, for example, 0v/gnd. A dac + mux is not enough.

So the AD5669 module would be similar in function to adding another Arduino Mega (6 pins + previous 2 to output the analog voltage).

analogWrite() does not create an analog voltage (I hate that function name!). It creates a PWM signal. To make it an analog voltage you have to add some signal conditioning to filter out the carrier frequency.

Ok. As long as you understand it that's fine.

There are many 8 channel (sometimes called "octal") dac chips. For example the AD7228. If a conversion from pwm to analog is no problem, then you can try software pwm, or use a dedicated extra arduino board with software pwm. For exampe a cheap arduino nano clone with: https://github.com/Palatis/arduino-softpwm


text:
Soil moisture sensor not working in "pcb"
I have a little and common application in which a sc-28 moisture sensor reads humidity levels and turns a servo (which drives a little faucet) if the soil needs water. Arduino nano is the brain.
All of them is tested and working fine on the proto board. Soil sensor is powered by 5v rail of arduino and everything seems fine even with the servo pulling from 5v rail too.
With all working, I try to translate that to a perfboard. The only difference in circuits are how they are powered.
While the prototype is powered via usb, the definitive one is powered through a 24v psu, leveling the voltage with a lm2596 module down to 5v.
Then this 5v feeds the nano (vin pin) and servo, while the soil sensor still pulls from 5v rail of the arduino to avoid vref problems.
And then, the sensor does not work. No led indicating power or data. This were my steps trying to debug it:

Triple check every connection on the board. While I am a decent programmer, my solder skills are kind of lacking. But everything looks fine, nothing shorted or loose.
measure voltage. On the perfboard, voltage between vcc and gnd connector pins spits 4.78v, which is supposed to be in range for the sensor to work.
Power the board through usb I tried this too, and is not working. Lm module and arduino lights up, code can be executed. I can't explain why the lm2596 module lights up too, and I'm thinking is part of the problem but I do not know. Voltage at soil sensor is still 4.78

And then I'm done. I dont know what could be happening and I only can make wild guesses. It's obviously a board problem, and i am aware I am doing something wrong but I can't see it.
Below, my horror soldering skills and the board. Soil sensor is the 4pin females at the bottom left and servo the 3pin males at the bottom right.

Picture doesn't work. Attach the image directly in the post.

Are you sure, that you are feeding 5V to Vin? 5V is not enough there, since Vin is connected to the regulator, which needs 6 to 12 V. Have you tried to connect your regulated 5V directly to the Nanos 5V pin?

you missed an intermediate step ... power the protoboard from 24V power supply ... your question is pointless until you do that

@jsotola that is not possible. I guess I could make a point to point wiring in site, but I am unable to get 24v on the protoboard at this time.

do the opposite then ... power the prototype from USB

The answer was, in fact, my poor experience with these boards and how they work.
As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.
Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.

Then this 5v feeds the nano (vin pin)

Can't feed 5V into Vin and get 5V out. Connect 5V to the 5V pin.


text:
DC motor does not work using PWN or Digital pins

I have connected pin 3 to a DC motor and using analogWrite and DigitalWrite to try making it start. However, nothing happens.
If I try to move the pin from pin 3 to 5V or 3.3V the motor starts.

Q: What could be the problem since it does not start using pin 3 (or others). I am using HIGH on digitalWrite and 255 on analogWrite.

I just bought a starter kit. It has FREENOVE written on it.
Here is a link to the tutorial and software.

Thanks for any help!

There is a big PDF tutorial that goes with this kit. Did you download it? Did you read the chapter on controlling a motor?

The Tutorial.pdf document that describes the components in the kit does not tell you what the current draw of the motor is. Chapter 10 has 2 tutorials on how to use the motor with a relay or L293D IC. This suggests to me that the motor draws a lot more current than a digital output can provide.
The tutorial using the L293D gives you the ability to vary the speed of the motor using PWM, so it would be a good place to start.
Hopefully pin 3 was not damaged by the excess current flow when the motor was attempted to be powered from it.

The digital/analog pins cannot directly source enough current to run a motor. Use the pin to control a switching device like a mosfet which then controls current flow to the motor.

You should read up on controlling motors from digital circuits and follow a tutorial until you understand the "gotchas".
You have to be careful with the pins on an Arduino and not trying to draw too much current from them. A motor very likely needs several times more current than an Arduino digital pin can provide (you should keep the current draw on an Arduino pin ≤20 mA. Your motor might well draw 10 times that much. You might have damaged or destroyed the pin you used.
Secondly, motors use inductive coils (electromagnets). Inductors have an effect called "back EMF" that causes a reverse surge of current when you remove power from them. That will also fry whatever solid state component is driving the inductor. (The Arduino pin if you're trying to drive the inductor directly, or a transistor if you're switching the current to the inductor using a transistor.) You need a "flyback diode" on the inductor to protect the circuit that drives it.


text:
Control two stepper motors simulatenously?
I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.
My Arduino IDE code is,
==============================
const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);

=================================================
Any suggestion would be helpful for me. Thanks.

Could you please, remove the empty lines, maybe. They just make the code appear longer than it has to be. (Just my opinion)

And align the code (make sure { and } blocks are indented correctly, and indent entire code (use ctrl-k after selecting all code).

Does it work, when you provide both steppers with the same signal line (connecting to the same output pin)?

@Duck Dodgers, Michel Keijzers In Arduino IDE, I correctly wrote my codes. I intentionally put the empty lines to read easily and also indented correctly in Arduino IDE.

@chrisl Do you mean like for example, in pin 2, connect X1, X2 dir and in pin 3, connect X1, X2 step? And thanks for your comments Duck Dodgers, Michel Keijzers, chrisl

@YangKeeWon, I can imagine that you did it correctly in the Arduino IDE. But the Arduino IDE, only you can see. We cannot. We see the code only in this post. And if the code isn't indented/formatted, then it becomes difficult to parse, especially for someone not familiar with the code. In any case, there is at least one closing bracket missing } for the loop() function in your code (which would've been nearly impossible to detect without the code being indented&so on). Sorry to be pedantic about this. Just saying that people can only help you, if you help them see your problem clearly.:)

@YangKeeWon Yes, just connect the pins of both motors to the same set of pins. If that still not works, there is something wrong with your wiring or mechanics

To all, Thanks for your help. And it was simple problem. First, I didn't set opposite direction but it wasn't the real problem because X2 motor still didn't move. I think the breadboard was problem so I changed and it worked. Best regards, YK.

You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.
At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is identical and the motors are essentially attached mirrored on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)
digitalWrite(X1dir,HIGH);
digitalWrite(X2dir,LOW);

Or
digitalWrite(X1dir,LOW);
digitalWrite(X2dir,HIGH);

Then step it like
digitalWrite(X1step,HIGH);
digitalWrite(X2step,HIGH);

delayMicroseconds(2000);

digitalWrite(X1step,LOW);
digitalWrite(X2step,LOW);

delayMicroseconds(2000);
...

Thank you. I didn't realized the motors had to spin opposite direction. The problem was just simple wiring, but after that your comment helped me a lot. Thanks for your kind answer. Best regards, YK.


text:
L298N beeps and malfunctions when receiving certain analogWrite values

I created a simple circuit with an UNO, L298N and a single motor.
Wrote the following code to test controlling the speed of the motor.
Tested motor with digitalWrite() function and it works fine.
Tested motor with analogWrite() function and from 255 down to around 70 motor works at various speeds.

Q: But from around 70 and below, the L298N starts to beep and the motor stop spinning. Any thoughts?
int enr = 9;
int inr1 = 8;
int inr2 = 7;

void setup() {
 pinMode(enr, OUTPUT);
 pinMode(inr1, OUTPUT);
 pinMode(inr2, OUTPUT);
}

void loop() {
  analogWrite(enr, 71);
  digitalWrite(inr1, HIGH);
  digitalWrite(inr2, LOW);
}

The LN298N should not beep and should not be able to. Might it be the motor, who is beeping? That the motor is not moving below 71 can be because the friction is too big for the motor to move

Ok, here is my theory what's happening:
Every motor has an amount of friction at his rotor. You need to pass enough energy to overcome this friction, or the motor will not move. When you use analogWrite(enr, 71) or lower, you pass only a small amount of energy to the motor, so that it cannot overcome the friction.
Now you have to understand, what analogWrite() really does. It does not output an analog voltage. Instead it generates a PWM signal. The voltage changes between HIGH and LOW level (5V and 0V in case of the Uno) at a specific frequency. The relation between HIGH time and LOW time is called duty cycle. That is, what's controlling the motor speed. So instead of supplying different voltages, we turn the motor on and off very fast. Since the rotor has a relatively big inertia (because of it's mass), it cannot react fast enough to follow these pulses. We only give it small pushes very fast. Instead it integrates over all the pulses. If the duty cycle is low (more LOW than HIGH time) only a small amount of energy is passed to the motor.
So, what is the motor doing, when it's got not enough energy to overcome the friction? It will still get little pushes very fast, but cannot actually spin. Instead the passed energy will induce vibrations in the motor, which have the frequency of the PWM signal. These vibrations can then be heard as a continuous beep.
If enough energy is passed to overcome the friction, the rotor spins correctly and does not vibrate, thus you cannot hear a beep.
What to do now:
The described principle applies to every motor, so cannot do much about that. You can simply go the easy way and not drive the motor with such low duty cycles. Another cause might be, that your motor likes to get a higher current to give it's full power. The L298N is quite inefficient, so you could change that to a H-bridge driver, that uses MOSFETs instead of bipolar transistors. Also maybe you can increase the voltage, that you use to drive the motor (depending on the not specified motor).
You didn't describe, how you have connected everything, so 2 other points: You cannot drive a motor from a digital pins power (since a digital output pin can only provide 40mA at max, 20mA recommended) and you should also not power a motor through the Arduino, since you might fry the voltage regulator or the protection diode. You can get away with that, when using small motors without any load, but that doesn't scale well. You should always connect the motor circuit directly with the power supply, so that the motors current does not have to flow through the Arduino.

Awesome info! Thank you. The friction problem makes perfect sense (motors are powered by a 7.5V external source). I got used to Lego Mindstorms motors that can turn really slowly. I shall adjust my expectations for now and look into alternative configurations in the future. I did read that the L258N is ancient technology, but by then I had committed my project! Thank you!


text:
TM1637Display is not updating on loop
Alright so I've been trying to update/change the number on the display during a loop, but nothing really happens. It doesnt change/update, the value is always exactly same.
#include <TM1637Display.h>

#define led_display 1
#define led_display_scnd 3

int analogPin = A0;
int moisture;
int percentage;

int map_low = 686;
int map_high = 350;

TM1637Display display(led_display_scnd, led_display);

void setup() {
  pinMode (led_display, OUTPUT);
  display.setBrightness(1);

  display.showNumberDec(1);
  digitalWrite(led_display, HIGH);
  Serial.begin(9600);

}

void loop() {
  display.showNumberDec(5);
  moisture = analogRead(analogPin);
  Serial.print("Raw: ");
  Serial.print(moisture);

  int sensorValue = analogRead(A0);
  percentage = 100-((sensorValue-110)*100L/(1023-110));

  Serial.print(" | Percentage: ");
  Serial.print(percentage);
  Serial.println("%");

  display.showNumberDec(moisture); // updating the value

  delay(2000);
}

Does the value of "Raw:" change on the terminal? That's the number you are trying to display.

Yeah it does. Here an example from whats In terminal
18:39:41.242 -> Raw: 1018 | Percentage: 1%
18:39:43.294 -> Raw: 956 | Percentage: 8%
18:39:45.353 -> Raw: 955 | Percentage: 8%

That leaves a compiler bug that affects either the library or your call to it, a bug in the library (such as its I2C implementation), or your wiring to the pins being used by the library for I2C (from least likely to most likely, if I had to guess). Double check your wiring against the pins you chose for the display. Also it looks like one of those pins is pin-1, which is the hardware UART's serial transmitter. Try a another pin for the display; you may just be trying to back-drive the UART.