text:
Is it okay to short IN and GND pins of relay module with controller ground?
I have this relay module that is attached to an ESP8266 (Wemos D1 Mini). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from an external power supply
The circuit diagram can be found here.
The module works fine and all but I am wondering: is it okay to operate it like this ?

the schematic is messy, but it looks ok ..... put a 1k ohm resistor between pin D1 and the base of the transistor for current limiting on pin D1 ..... put a bypass diode on the relay coil to prevent voltage kickback when the relay is de-energized .... the kickback may destroy the transistor

It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.
The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "5VDC to 12VDC (some boards may work with 3.3)" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.
Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.
Could try to connect the collector only the IN pin? As in the schematic below.

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.

The relay in the schematic is barebone as I couldn't manage to find the actual module to add to it. I just found the relay that is used on the module as a reference. The relay needs 5v and my microcontroller can only deliver 3v. That's why I'm using my own transistor. As with the schematic, it's my first one ever, first project ever. Thanks for the advice. As with the mains neutral, indeed I'm not connecting it to ground, I messed up the symbol and didn't care after. Again, it was just for reference.

@TermoZour which transistor do you really use? I have added a calculation (below the horizontal line) to my answer. I think 330Ω or 470Ω are good and safe values for the resistor.

I use a BC548B with a 510 ohm resistor on it's input signal

The sdrd-05vdc-sl-c relay is 5v 70mA. The bc548b is maximum 100mA. I'm not happy with that, but it might work. Does the relay work with a 510 ohm resistor to the base? When the transistor is on, you could measure the voltage of the collector. If it is about 0.1v then the transistor is fully turned on and it is okay.

You mean that you pull your Arduino relay control pin LOW, causing it to ground the pin? Yes, that sounds correct. (And you would set it HIGH to not energize the relay.) You might need a low value resistor between the relay's logic pin and the Arduino output if the relay is sinking too much current through the Arduino logic pin. A 100 ohm resistor would prevent sinking too much current through the Arduino logic pin. Try it and see if the relay still energizes.
EDIT:
When I posted my answer the image wasn't loading, so I had to guess as to what you were describing. My guess was wrong, and thus my answer was wrong too.
Since you're driving the gate of a transistor you will need a current limiting resistor or you will overload the logic pin on your microcontroller. (As Jot says in their answer.)
There are 3.3v versions of these logic-driven relay modules readily available, and some even include optical isolation, so why not use one of those?
Take this one for example: https://www.adafruit.com/product/3191
(I don’t think that one has optical isolation.)


text:
Optical Rotary Encoder Index issue
I have the following code working correctly except for the Index portion.
I am not sure if I have the syntax correct for the hardware.  The end result I am looking for is to have the encoder reset to 0 degrees every time the index comes around (360 degrees).
I am also looking for any comments on the code as I would like the encoder output to be as accurate and efficient as possible.
Here is the code:
// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts
#define CLOCKWISE            1       // direction constant
#define COUNTER_CLOCKWISE    2       // direction constant

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT_PULLUP);
  pinMode(ENCODER0PINB, INPUT_PULLUP);
  pinMode(ENCODER0PINI, INPUT_PULLUP);

  // interrupts
  attachInterrupt(3, onInterrupt, RISING);
  attachInterrupt(4, onReset, CHANGE);

  // enable diagnostic output
  Serial.begin (9600);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible
void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b )
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);

  if (i = 1)
  {
  encoder0Position = 0;
  }
}

except for the Index portion is not a good description of the observed behavior .... please clarify what that means

In your onReset() function you have an assignment instead of a comparison:
if (i = 1) // This is always true
{
encoder0Position = 0;
}

i = 1 should be i == 1

Craig, is that the proper syntax for an Optical Encoder, if (i == 1)?  I am not sure if that is the output of the interrupt?

if (i == 1) is correct.

source: Stack Exchange

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

sort: votes


text:
Leonardo Problem
I have boiled this down to a very simple piece of code:
int testKey;

void setup() {

Serial.begin(9600);

}

void loop() {

Serial.println("Input Source ID "); //Ask me the number

while (Serial.available()==0){ } //Wait for me to answer

testKey = Serial.parseInt();  //Store my answer in this variable

Serial.print("Parsed Input is ");  //Print the results on serial monitor

Serial.println(testKey);

}

When I run the code on my Leonardo, or Uno, I expect to have Input Source ID to be printed on the serial monitor. It remains blank (it is set to 9600 baud). If I go ahead and enter a 1, then the serial monitor starts working. However, from this point on, it seems to ask me for the ID again, and print a 0 to the serial monitor:
Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID
It then is waiting for me to enter a new Source ID. If I then enter a 2, this is what I get, in addition to what was already there.
Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID
Parsed Input is 2
Input Source ID
Parsed Input is 0
Input Source ID
My question is, why doesn't the void loop start automatically and immediately prompt me for input? Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why? This seems so straightforward, but it has me stumped. I tried some delay statements here and there, to no avail. Thanks in advance.

You can set the line ending in the serial monitor to all combinations with carriage return and linefeed. Try all the possibilities and you see. No one of use uses the Serial.parse... functions, they are inconvenient.

Ok, thanks to both of you! I have implemented your suggestions, and I am able to get the expected results. Kudos to you!

My question is, why doesn't the void loop start automatically and immediately prompt me for input?

It does. However your serial monitor isn't open at that time and can't receive it.  Unlike the Uno the Leonardo does not reset when you open the serial port.
A common workaround, to make it look more like an Uno, is to add:
while (!Serial);

in setup() after Serial.begin(...), so that it does nothing until you open the serial terminal.

Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why?

Simple: you're parsing the number as a number. You're then parsing a blank line as the number.
If you have the serial monitor set to send CR + LF as the line ending you get the integer terminated by CR, followed by no integer (represented by 0) followed by LF.

This line:
while (Serial.available()==0){ } //Wait for me to answer

Doesn't wait for you to answer, it only waits until the first character is typed. This while loop happens about a million times a second on an Uno. You can't possibly type more than one character in that microsecond. Once you type it, the clock starts ticking, because parseInt() uses a timeout value, so if no valid digit character is entered by the timeout, it exits. The default timeout is 1000ms (1 second).

the entered value is sent from serial monitor after Send button or Enter key. Even at 9600 baud the gap between characters is far less then a second

True; I forgot about serial monitor.

and you plan to leave it here?

Sure. If it's a poor answer, it will get downvoted, as it ought to be.

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


text:
Code not working
Basically, it's an Arduino project in which I am stuck. I using inputs as two sensors and LED as output, for further details and concept video had been attached. I did the wiring and everything correctly but there is something wrong with the code which I couldn't figure out. Here is the code.
I had attached a video for proper understanding.
https://youtu.be/ZQg_xbGQNE0
const int s1 = 22;     // sensor one
const int s2 =  23;      // sensor two
int pot_pin = A0;
int list[15] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 44, 45, 46}; //leds pin
//if u want change the time delay
int timer = 1000;

bool flag1 = false;
void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(s1, INPUT);
  pinMode(s1, INPUT);
  // initialize the LED pin as an output:
  for (int thisPin = 0; thisPin < 15; thisPin++) {
    pinMode(list[thisPin], OUTPUT);
  }

}

void loop() {
  // read the state of the pushbutton value:
  int output = analogRead(pot_pin);
  int led_value = map(output, 0, 1023, 0, 255);

  if (digitalRead(s1) == HIGH) {
    for (int thisPin = 0; thisPin < 15; thisPin++) {
      if (digitalRead(s2) == LOW) {
        // turn the pin on:
        analogWrite(list[thisPin], led_value);
        //digitalWrite(thisPin, HIGH);
        delay(timer);
      }
      else {

        for (int de = 14; thisPin < 15; thisPin++) {
          analogWrite(list[thisPin], led_value);
          analogWrite(list[de], led_value);
          //digitalWrite(thisPin, HIGH);
          //digitalWrite(de, HIGH);
          delay(timer);
          de--;
        }

      }
    }
    flag1 = true;

  }
  if (digitalRead(s2) == HIGH and flag1 == true) {
    for (int thisPin = 0; thisPin < 15; thisPin++) {
      if (digitalRead(s1) == LOW) {

        digitalWrite(list[thisPin], LOW);
        delay(timer);
      }
      else {
        for (int de = 14; thisPin < 15; thisPin++) {
          digitalWrite(list[thisPin], LOW);
          digitalWrite(list[de], LOW);
          delay(timer);
          de--;
        }

      }

    }
    flag1 = false;
  }
}

What exactly is now working? Show us schema of your hardware. Are you using ArduinoUno?

Arduino mega, the second case is not working, you can have a look into the video.

Is the video what it should be? Is the sketch only for CASE-2?

Please edit your post and replace the title with one that gives more information about the question being asked.

the code is for all the cases

how do you know that it is not working? .... you said nothing about what you expect to happen ..... you also said nothing about what actually happens

You might have seen the video, you may see different cases been mentioned now according to me the code I made is ok, now the second case according to video is not working further all the cases are working, now I myself not getting that why it is not working accordingly, and i what i want is all the cases should run in a single program.


text:
displaying double variable problem (Arduino)
so I have a problem with displaying a double variable in OLED & IR remote calculator, like this (using u8g2):
displayTextOnRight(String(100000, 0)); //ex. of an void and a number

It displays: " "
But when I set to ex. 99999 it displays: "99999"
The same is with
displayTextOnRight(String(1000.00, 2));

It also displays nothing. (100.00 displays 100.00)
I tried values below zero and it crashes. When I try 6 it's empty whatever I type on my remote.
Please help.

What's this "displayTextOnRight()" function? What code are you using? Where did you get it? What is it supposed to do?

When the first argument to the String constructor is an integer type, it tries to interpret the second argument as a number base and not as a number of decimal places.
So, in String(100000, 0));, it kind of thinks you're asking for the number to represented in the String in base 0 as opposed to decimal (DEC), hexadecimal (HEX), binary (BIN), etc and base 0 isn't a thing.
With a floating point type first argument like 1000.0 the second argument takes on the meaning of decimal places (seen an decimalPlaces in the documentation).
If you want ".00" after an integer number when it's converted to a String it's probably better to just print it in a second .print() call, or to concatenate it to the string. And if you want you can manually type convert integer expressions to floating point type to force selection of the other constructor, e.g. int a = 10000; whatever.print(String(float(a), 2));


text:
ESP8266 web server not responding when running a http request function
I am trying to build something that can control a stepper motor based on weather information from openweathermap. I've set up a ESP8266 webserver to manually control motor movement with buttons and I have set up the structure to talk to openweathermap API to get the information I want (printing them to serial monitor for now for testing).
However, when I combined the 2 things break. The current code allows me to get weather perfectly but I can no longer connect to my web server running in STA mode. Something in the getWeather() function is messing with the web server because if I remove getWeather() from my loop the web server works.
Any idea what I am doing wrong here?
#include <SPI.h>
#include <AccelStepper.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>  // http web access library
#include <ArduinoJson.h>        // JSON decoding library

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 5
#define stepPin 4
#define motorInterfaceType 1
bool motorStop;
bool motorCW;
bool motorCCW;

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

//Put your SSID & Password
const char* ssid = "[ssid]";  // Enter SSID here
const char* password = "[password]";  //Enter Password here

//OpenWeatherMap API key
String apiKey= "[apikey]";

//OpenWeatherMap location
String location= "lat=37.30&lon=-121.91";
String unit= "metric";

const unsigned long postingInterval = 1000*60*60; // delay between updates, in milliseconds

WiFiClient client;

ESP8266WebServer server(80);

// Set your Static IP address
IPAddress local_IP(192, 168, 86, 248);
// Set your Gateway IP address
IPAddress gateway(192, 168, 86, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(192, 168, 86, 1);

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

// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet,primaryDNS)) {
  Serial.println("STA Failed to configure");
}

  stepper.setMaxSpeed(1000);

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

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  //Print out connection info
  Serial.println("");
  Serial.println("WiFi connected..!");

  server.on("/", handle_OnConnect);
  server.on("/cw_on", handle_CW_on);
  server.on("/cw_off", handle_CW_off);
  server.on("/ccw_on", handle_CCW_on);
  server.on("/ccw_off", handle_CCW_off);
  server.on("/mstop", handle_stop);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {

  server.handleClient();
  if(motorStop)
  {stepper.setSpeed(0);}
  if(motorCW)
  {stepper.setSpeed(400);}
  if(motorCCW)
  {stepper.setSpeed(-400);}

  // Step the motor with a constant speed as set by setSpeed():
  stepper.runSpeed();

  getWeather();
}

void getWeather()
{
  // if there's a successful connection:
  if (client.connect("api.openweathermap.org", 80))
  {
    Serial.println("connected");
    // send the HTTP PUT request:
    client.println("GET /data/2.5/onecall?" + location + "&exclude=current,minutely,hourly" +  "&appid=" + apiKey);
    client.println("Host: api.openweathermap.org");
    client.println("Connection: close");
    client.println();

    const size_t capacity = 8*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(8) + 16*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 8*JSON_OBJECT_SIZE(6) + 8*JSON_OBJECT_SIZE(14) + 1810;
    DynamicJsonDocument doc(capacity);

    deserializeJson(doc, client);

    float lat = doc["lat"]; // 37.3
    float lon = doc["lon"]; // -121.91
    const char* timezone = doc["timezone"]; // "America/Los_Angeles"
    int timezone_offset = doc["timezone_offset"]; // -25200

    JsonArray daily = doc["daily"];

    // tomorrow's forecast (daily_1)
    JsonObject daily_1 = daily[1];
    long daily_1_dt = daily_1["dt"]; // 1596225600
    long daily_1_sunrise = daily_1["sunrise"]; // 1596201109
    long daily_1_sunset = daily_1["sunset"]; // 1596251761

    JsonObject daily_1_temp = daily_1["temp"];
    float daily_1_temp_day = daily_1_temp["day"]; // 306.61
    float daily_1_temp_min = daily_1_temp["min"]; // 288.67
    float daily_1_temp_max = daily_1_temp["max"]; // 306.61
    float daily_1_temp_night = daily_1_temp["night"]; // 288.67
    float daily_1_temp_eve = daily_1_temp["eve"]; // 295.94
    float daily_1_temp_morn = daily_1_temp["morn"]; // 293.26

    JsonObject daily_1_feels_like = daily_1["feels_like"];
    int daily_1_feels_like_day = daily_1_feels_like["day"]; // 303.31
    float daily_1_feels_like_night = daily_1_feels_like["night"]; // 287.59
    float daily_1_feels_like_eve = daily_1_feels_like["eve"]; // 293.77
    float daily_1_feels_like_morn = daily_1_feels_like["morn"]; // 292.42

    int daily_1_pressure = daily_1["pressure"]; // 1015
    int daily_1_humidity = daily_1["humidity"]; // 17
    float daily_1_dew_point = daily_1["dew_point"]; // 278.68
    float daily_1_wind_speed = daily_1["wind_speed"]; // 3.12
    int daily_1_wind_deg = daily_1["wind_deg"]; // 318

    JsonObject daily_1_weather_0 = daily_1["weather"][0];
    int daily_1_weather_0_id = daily_1_weather_0["id"]; // 800
    const char* daily_1_weather_0_main = daily_1_weather_0["main"]; // "Clear"
    const char* daily_1_weather_0_description = daily_1_weather_0["description"]; // "clear sky"
    const char* daily_1_weather_0_icon = daily_1_weather_0["icon"]; // "01d"

    int daily_1_clouds = daily_1["clouds"]; // 0
    int daily_1_pop = daily_1["pop"]; // 0
    float daily_1_uvi = daily_1["uvi"]; // 9.53

    // print out weather information
    Serial.print("Tomorrow's Forecast");
    Serial.print("Temperature: ");
    Serial.println(daily_1_feels_like_day);
    Serial.print("Weather: ");
    Serial.println(daily_1_weather_0_main);
    delay (postingInterval);
  }
  else
  {
    // if you couldn't make a connection:
    Serial.println("connection failed");
    delay (postingInterval);
  }
}

void handle_OnConnect() {
  motorStop = HIGH;
  motorCW = LOW;
  motorCCW = LOW;
  Serial.println("Motor: Stopped");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_CW_on() {
  motorStop = LOW;
  motorCW = HIGH;
  motorCCW = LOW;
  Serial.println("Motor: Running Clock-wise");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_CW_off() {
  motorStop = HIGH;
  motorCW = LOW;
  motorCCW = LOW;
  Serial.println("Motor: Stopped");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_CCW_on() {
  motorStop = LOW;
  motorCW = LOW;
  motorCCW = HIGH;
  Serial.println("Motor: Motor: Running Counter Clock-wise");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_CCW_off() {
  motorStop = HIGH;
  motorCW = LOW;
  motorCCW = LOW;
  Serial.println("Motor: Stopped");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_stop() {
  motorStop = HIGH;
  motorCW = LOW;
  motorCCW = LOW;
  Serial.println("Motor: Stopped");
  server.send(200, "text/html", SendHTML(motorStop, motorCW, motorCCW));
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(uint8_t mstop,uint8_t cw, uint8_t ccw){
  String ptr = "<!DOCTYPE html> \n";
  ptr +="<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>LED Control</title>\n";
  ptr +="\n";
  ptr +="\n";
  ptr +="\n";
  ptr +="
Weather Station
\n";
  ptr +="
Runs either direction continuously
\n";

   if(cw)
  {ptr +="
Motor running Clock-wise
Stop\n";}
  else
  {ptr +="
Motor not running Clock-wise
Run\n";}

  if(ccw)
  {ptr +="
Motor running Counter Clock-wise
Stop\n";}
  else
  {ptr +="
Motor not running Counter Clock-wise
Run\n";}

  ptr +="\n";
  ptr +="\n";
  return ptr;
}

At the end of getWeather() you call delay(postingInterval);
postingInterval is set to 60*60*1000 ... one hour. That means getWeather() won't return for one hour and nothing else in loop() will be processed during that time, including the web server.
You need to remove that delay() call and rewrite your loop to check if postingInterval milliseconds have passed and only call getWeather() if they have.

Thanks this works! However now there is a new problem. I am using millis() in my loop to call getWeather(). However the interval will affect how stepper runs. stepper.runSpeed() is suppose to get stepper to run continuously at the set direction; but now the stepper would pause at interval.

Great, happy that helped. The new problem sounds like a good thing to post as a new question; then you'll get the attention of a lot of people who might answer it and not see it here as a comment :)

Will do. Thank you!


text:
How do I set the DHCP pool for an ESP-WIFI-MESH?
I'm building a mesh with ESP32 dev kits (ESP32-DevKitC V4) using the ESP-IDF VS Code extension and the ip_internal_network example project. The code for the example, common project components, and the API is linked. When the mesh nodes power on and build the network, they use the 10.0.0.0 network. How do I change the internal mesh network?
My operating assumptions:

The root node receives an external IP address from an external DHCP
server.
The root node acts as an internal DHCP server to the mesh nodes.
The root node performs network address translation.
Its DHCPv4 server runs on the lwIP TCP/IP stack.
Internal IP addresses are leased from a pool governed by the root
node (but it's possible that nodes request a particular address from
this network and the server provides the next available; I'm unsure).
The network address is 10.0.0.0/8 (I inferred the subnet mask; it
could be anything).

Obviously, the first thing I tried was searching for this network address in files. There was nothing in the project workspace and too many hits in the repo to be useful. I tried decimal and hex with no luck.
I also tried tracing the function that prints the IP address to the serial terminal to find the IP var, and working backwards to locate the statement that initializes this variable. I'm still reading event handler API documentation so I haven't made quick progress here either.
The programming interface is split among ESP-IDF component header files, build systems (CMake and Ninja?), KConfig options and host tools (idf.py?). C, FreeRTOS and build systems are all new to me so I would appreciate if someone with more experience could weigh in. Thank you.

I figured it out; it's in mesh_netif.c:43. I'm not sure why I passed over this file initially but it caused a lot of unnecessary headache. The relevant struct is this:
const esp_netif_ip_info_t g_mesh_netif_subnet_ip = {
    .ip = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) },
    .gw = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) },
    .netmask = { .addr = ESP_IP4TOADDR( 255, 255, 255, 0) },
};

I changed the 10.0.0.0/16 network to 192.168.0.0/24. The root node assumes the address in .ip. I assume child nodes check the ARP table and increment until an address is available, then send the DHCPREQUEST for that address to root. I say "assume" because although root runs lwIP, I am not sure child nodes run lwIP (they may just communicate in layer 2 ESP-WIFI-MESH frames).
Make sure your DHCP server publishes an IPv4 DNS address or ESP_ERROR_CHECK(esp_netif_set_dns_info(netif, ESP_NETIF_DNS_MAIN, &dns)) (mesh_netif.c:70) will fail and cause the board to power cycle. A way around this is to enable Use global DNS IP in menuconfig. The global DNS field is in hex format, so 10.32.64.128 is written 0x0A204080.
Mesh-internal IP messages are published with MQTT so the name/address .broker.address.uri in mqtt_app.c:74 must be accessible from the router.


text:
How to divide high input frequency by 1.25 like old-school TTL logic by Arduino?
In modern timekeeping, there is a 10 MHz reference frequency (or any power of 10). The digital clock takes 32768 Hz frequency only (or some other power of 2 possible).
The problem is how to convert power of 10 to power of 2 nicely. It is done by a series of 1.25 (every 5 inputs output 4) and 2.5 dividers (every 5 inputs output 2).
I am interested in how this can be done by Arduino.
I have a high input frequency, say 1 MHz, therefore i have to use registers directly. Then I have output frequency 1/2 (counter of 2) of the input and 1/4 of the input frequency and I would like to have output 4/5 of the input (divide by 1.25 counter). So, do I need 3 output pins, 1 for counting twos, one for fours, and one for fives? Or can this be done somehow just by 1 input pin and 1 output pin with 4/5 input frequency?
I tried to modify the code but I can not tell how to skip every 5th cycle.
Let's say in the chaining of these counters I can get from 1 000 000 Hz frequency:
1000000 Hz - 800000 Hz - 640000 Hz - 512000 Hz - 409600 Hz - 327680 Hz - 2262144 Hz
so input = power of ten, then output = power of two
My question is how high could be the maximal input frequency to this code?
and can you please help me to modify that code?
/*
 * From one square wave generate 3 waves 1/2, 1/4 and 4/5 of the original frequency.
 *
 * Original sketch tried to be modified from here:
 *
 * https://arduino.stackexchange.com/questions/63202
 *                               _   _   _   _   _   _   _   _   _   _
 *  input:  digital 13 = PB7    / \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/  1 000 000 Hz
 *                              R1F0R1F0R1F0R1F0R1F0R1F0R1F0R1F0R1F0R1F0R
 *                               ___     ___     ___     ___     ___
 *  output: digital 10 = PB4    /   \___/   \___/   \___/   \___/   \___/    500 000 Hz
 *                              R 1 F 0 R 1 F 0 R 1 F 0 R 1 F 0 R 1 F 0 R
 *                               _______         _______         _______
 *  output: digital 11 = PB5    /       \_______/       \_______/       \    250 000 Hz
 *                              R   1   F   0   R   1   F   0   R   1   F
 *                               _   _   _   _       _   _   _   _
 *  output: digital 12 = PB6    / \_/ \_/ \_/ \_____/ \_/ \_/ \_/ \_____/    800 000 Hz
 *                              R1F0R1F0R1F0R1F00000R1F0R1F0R1F0R1F00000R
 */

int main(void)
{
    DDRB = _BV(PB4) | _BV(PB5) | _BV(PB6) | ~_BV(PB7);  // PB4 PB5 PB6 as outputs and PB7 as input
    for (;;) {
        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                              // rise PB4

        loop_until_bit_is_clear(PINB, PB4);             // wait for rising input
        loop_until_bit_is_set(PINB, PB4);
        PORTB |= _BV(PB5);                              // rise PB5

        loop_until_bit_is_clear(PINB, PB5);             // wait for rising input
        loop_until_bit_is_set(PINB, PB5);
        PORTB |= _BV(PB6);                              // rise PB6

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                             // fall PB4

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                              // rise PB4

        loop_until_bit_is_clear(PINB, PB4);             // wait for rising input
        loop_until_bit_is_set(PINB, PB4);
        PORTB |= ~_BV(PB5);                             // fall PB5

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                             // fall PB4

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                              // rise PB4

        loop_until_bit_is_clear(PINB, PB4);             // wait for rising input
        loop_until_bit_is_set(PINB, PB4);
        PORTB |= _BV(PB5);                              // rise PB5

        loop_until_bit_is_clear(PINB, PB5);             // wait for rising input
        loop_until_bit_is_set(PINB, PB5);
        PORTB |= ~_BV(PB6);                             // fall PB6

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                             // fall PB4

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                              // rise PB4

        loop_until_bit_is_clear(PINB, PB4);             // wait for rising input
        loop_until_bit_is_set(PINB, PB4);
        PORTB |= ~_BV(PB5);                             // fall PB5

        loop_until_bit_is_clear(PINB, PB7);             // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                             // fall PB4
    }
}

Nick Gamon personally :D I saw you so many times here. what an honour.
I do need a source clock for multiplanetary clock, without fractions.
The least common multiple for periods of second for: Earth, Mars, Titan.
If I will keep the ratio between planets exactly, then even if the Earth clock using Arduino resonator will drift by a few tens of seconds per day, Mars clock and Titan clock will drift the same amount of time.
This does not matter to me because if I stop the clock and wait then All 3 planets will be aligned again. But if I would not keep the ratio between planets exactly, for Example Earth would drift 30 seconds per day, Mars would drift 31 seconds per day, and Titan would drift 29 seconds per day- it depends on how close approximation I will take. So, by stopping the clock for 30 seconds to set it correctly, Earth would go back to 0 seconds, but Titan would be 1 second behind and Mars would be 1 second before. I would not correct all 3 just by stopping the clock. I would have to stop the clocks 3 times individually (once for each planet, if not, the error for the 2 remaining planets would accumulate over time, even if correcting Earth)
And trust me, it's not easy to calculate Mars time (ok it is because NASA application already exists) but Titan Time I have only in my Excel, and that one I have to recalculate when setting the clock.
Periods for Earth: 1 s, Mars 1.027 491 251 7 s, Titan 0.998 068 437 5 s,
Obviously, Arduino math is not exact to the 10 decimal places, maximally
32 bytes which is 0.000 000 000 2 and something ... that is 2 to -32nd power.
The options for least common multiple:
Earth:Mars = 291/299, Earth:Titan = 3624/3617
Earth:Mars:Titan = integer:integer:1 054 584 (that is 291 x 3624)
so 1st option, is to generate 1 054 584 Hz (I call it golden Megahertz) which is slightly more than 15 Arduino clock cycles = to be exact 15 and 16 cycles would have to alternate with some leap cycle rule (analogous to our leap year rule) to get this frequency.
Find another, decimal frequency slightly off.
Option 1:
Earth:Mars = 812993/800000 and Titan could be 1/4 cycle off, so 800 kHz
Option 2:
Earth:Mars:Titan = integer:integer:3200000 so 3.2 MHz (5 clock cycles) and Mars, Titan, Earth are better aligned,
Option 3:
9600000 Hz frequency (5 clock cycles on 48 MHz Arduino Zero exactly, or 10 cycles on overclocked 96 MHz Arduino Due), and perfect planet alignment.
These options need to have 24 bit counter, up to 16777216 not just 16 bytes.
If I don't keep the ratio exactly, the clock would drift at different speeds and to correct the clock to stop all 3 clocks at once would not be enough.
Each one would have to be corrected individually (even though Earth would have the biggest error from Arduino resonator, some residual errors from not exact ratios will accumulate over time, and once in a while, additional 2 clocks would have to be stopped and set individually)

Also, i would like to have something like calendar for each planet, what would the fastest and shortest way to configure it? Earth: 365.2425 days, Mars 668.592 days and Titan 673.54388 days. For Earth we have 365 plus every 4th leap but every 100th not leap but every 400th leap. Days in month are 31,28/29,31,30,31,30,31,31,30,31,30,31. For Mars we would have: 56,56,55,56,56,55,56,56,55,56,56,55/56, and every odd and every 10th leap (thats .6) but not every 100  (thats .59 )but every 500 leap (thats .592). Leap month would be 12-th month. For Titan we would have 56,56,56,56,56,57,56,56,56,56,56,56/57, and every odd and every 20th leap (thats .55) but not every 160 th leap (thats .54388). Also, that lenghth mentioned is not 1 Titan day, but 1/16th Titan day, yes Titan day is almost 16 days long. So, i would like to have something like "days in a day" = 8 days week of 24 hours of 60 minutes of 60 seconds of 0.98 above mentioned earth seconds, and AM and PM week. The 8th day would be called "Earthday and would be between Sunday and Monday". For Mars we would have 7 day weeks as on Earth, and in a similar way, Monday 1st, Tuesday 2nd, .... But for Titan we would have 16 times 1st: AM Monday 1st, AM Tuesday 1st, ... AM Sunday 1st, AM Earthday 1st, PM Monday 1st, PM Tuesday 1st, ... PM Sunday 1st, PM  Earthday 1st, and then 16 times 2nd, ... again from AM Monday till PM Earthday. So we can divide terribly long 16 day day into weeks and days. do we have some reasonable function like RTC where i in/out put (year, month, day, week, weekday, hour, minute, second) when i in/out put "unix time" for Earth, Mars and Titan based on different length of seconds? We would have Unix Earth, Unix Mars and unix Titan. Obviously for Earth and Mars, the weekday and date would advance simultaneously and we dont need "week" for Earth and Mars (that would be dislabled) and for Titan there are 8 weekdays and then 2 weeks and then 1 titan day (2 weeks long) so yes 16 days day and 673.54 of them thats almost 30 years long year. the formulas among Earth Mars and Titan Unix time have to be ready yet, but how to break that unsigned long unix time for each planet into the components, and one more (week) component for Titan, an titan day is awfully long, do weekday (and week) here is time, not day, but day within a day, and week within a day.

Nick Gamon, i dont want to be disrespectful, this is my very first question after several years of reading these forums.
There is indeed a capability of Arduino Uno r4 generating 1/256 sec interrupt directly, as there is dedicated library for that, using its bult in RTC clock, which are already part of that Arduino.
Unfortunately, the nice round multiple for Earth, Mars, Titan would be 3.2 million Hz. As Arduino 4 is 32 bit processor 48 MHz, it does math up to 32 bits within one or two clock cycles. and 3.2 million Hz would be exactly 15 clock cycles, however that not much cycles for interrupt. But 256 Hz is plenty of time for 48 MHz 32 bit processor right? im not sure how exact are that RTC clock, need to find out as soon as ill get it. That Arduino uno R4 appeared just few days ago in the shop and its totally new and different. (32 bit, 48 MHz)
1/256 th of second is 12500 / 3200000 second. so Thank god 3.2 million is divisible by 256 without any fraction.
I am enclosing the example for Arduino r4 documentation:
https://docs.arduino.cc/tutorials/uno-r4-wifi/rtc#unix
#include "RTC.h"

const int LED_ON_INTERRUPT  = 22;

void setup(){
  RTC.begin();
  if (!RTC.setPeriodicCallback(periodic_cbk, Period::ONCE_EVERY_2_SEC)) {
    Serial.println("ERROR: periodic callback not set");
  }
}

void loop() {
}

void periodic_cbk() {
  static bool clb_st = false;
  if(clb_st) {
    digitalWrite(LED_ON_INTERRUPT,HIGH);
  }
  else {
    digitalWrite(LED_ON_INTERRUPT,LOW);
  }
  clb_st = !clb_st;

  Serial.println("PERIODIC INTERRUPT");
}

The period can be specified using the following enumerations:
ONCE_EVERY_2_SEC
ONCE_EVERY_1_SEC
N2_TIMES_EVERY_SEC
N4_TIMES_EVERY_SEC
N8_TIMES_EVERY_SEC
N16_TIMES_EVERY_SEC
N32_TIMES_EVERY_SEC
N64_TIMES_EVERY_SEC
N128_TIMES_EVERY_SEC
N256_TIMES_EVERY_SEC

Now, I am also strugglling with how to incorporate that calendar from Unix time, to break it into individual components for Earth, Mars and Titan. Unix time began on 01/01/1970 00:00:00, unix Mars would began on 01/01/192 00:00:00 and Titan Unix would began on 01/01/13 AM Monday 00:00:00, but i would like to have the initial years adjustable because. It will eventually run out of range after 136 earth years, 72 Mars years and some 4.6 Titan years so we could re-use it by shifting initial year, and also, i would like to have it valid at least till 2323, so, only with resolution 4 second, because 300 years has less than 2 to the 32th 4-second intervals. But that calendar is giving me a headache. I saw RTC library but i cant just change numbers to get Mars, and Titan calendar.
The reason i would like to have it, is because in some point in the future, the human colonisation of Mars will begin, and in more distant future, the human colonisation of Titan (Saturns moon) will begin (there is already a nuclear powered helicopter which will operate in Titan high density atmosphere and low gravity and very cold environment, in 2034 (the date is already approved by NASA, it will lift off in 2027, but as u can suppose the flight takes 7 years to cover one billion miles, or 1.6 billion kilometers to Saturn), and plan for nuclear powered submarine which will swim in its liquid methane seas, not sure when, but the concept already exists, its close to liquid nitrogen temperature, liquid methane has temperature of minus 180 degrees Celsius or like minus 300 degrees of Farenheit, so heating by and insulation have to be perfect) and for enery planet we do need different calendar

If i would have to be capable to construct PLL (phase-locked-loop) then i would have to be able to go from 32768 Hz exactly to 3.2 MHz (as exactly as the 32768 Hz crystal is exact), by 5 times multiplying it by 2.5 that is (multiply by 5 and divide by 2). Lol I could not do 5 times multiply by five because i would get 102.4 MHz (and then divide it 5 times by 2) and not even Arduino due is that fast enough to catch that interrupt. But pure TTL logic is capable to to do it (assuming it can multiply by fractions, that is 2.5 to the 5th power)

Hi guys, the lcd keypad shield 1602 A is compatible with which library and which arduino? how the pins have to be set? I just cant make it working

What Arduino are you using? 2. You may, using a hardware timer, convert 1 MHz to 64 Hz (i.e. divide by 15625). Would that be an acceptable frequency to you?

It's unclear what you are trying to do. Are you trying to make a clock that ticks every second, given a 1 MHz clock rate? Or are you trying to measure some unknown input signal and report on its frequency?

If I had to go this way, I'd probably go with counting fractions and occasionally extend period by one (when it gets over decimal point). Eg. 16MHz / 488.28125 = 32768 -> fract += 28125; if (fract > 100000) { fract -= 100000ul; period = 489; } else { period = 488; }

@Peter Thank you for the compliment. Your "answer" is really supporting material for your question so I have respectfully appended it to your question as additional information.

Thank you Nick ... Well im here years... and never talked to you personally. do u know where on Github i can see RTC library for Arduino Uno R4 which is capable of generating 1/256 s interrupts? I would like to see if i can get from there somehow 1/32768 s interrupts, if it is possible so i would like to see that particular RTC library for Arduino Uno R4 which is bulit-in there so no need to install. But before i get it i would like to see that library

Why do you particularly want a 1/32768 interrupt? Do any of the planets have a period which is a multiple of that?

Unfortunately no, the good approximation is 1/3.2 millionth of second.

I still don't understand exactly what you are trying to do. You are building something, that much is obvious. Tell me about the X part. Forget about phase locked loops, TTL logic, multiplying by 5 and dividing by 2, 48 MHz, 32 bits, all that is the Y part of the problem.  Let's imagine you have built this gadget, and a non-technical friend asks "what does it do?". What do you tell them? Does it tell you the positions of all the planets at a given moment? Or maybe the moons as well? Is it predicting tides? Is it telling you when the sun rises on Jupiter? That's what I want to know.

Your focus on “exact” numbers (32768 Hz, 2.5^5...) is probably not going to be helpful. The ratio of the Earth second to another planet's second is not exactly a rational (a ratio of two exact integers). This is why I suggest you reason in terms of rational approximations instead.

what i am trying to do: in general, running 3 different clocks and 3 different calendars (using 3 different length of months and 3 different leap year rules) using 3 different lengths of seconds), without getting the logic too complicated. So, in the future, when multiple another planets will be colonized, i can simply add another calendar-clock. For Example Venus. Yes it is telling time, date and year on Earth, Mars and Titan (Saturn´s largest moon)

@Edgar Bonet I like that 3200 number in the code, indeed 3.2 million is least common multiple of all of them, so that is 3200 ticks per millisecond.

3 different calendars ... using 3 different lengths of seconds -  "Second" has a formal definition. "The second [...] is defined by taking the fixed numerical value of the caesium frequency, ΔνCs, the unperturbed ground-state hyperfine transition frequency of the caesium 133 atom, to be 9192631770 when expressed in the unit Hz, which is equal to s−1." However I'm sure you could convert one sort of second to another (whatever that means) by simple multiplication.

Second can have definition bout it will be useless on Mars, or Titan. Otherwise we would have to have a clock which would reset at different time, on Mars: 24:39:35.244147 and on Titan 23:57:13.113, would they like to have that kind of a clock? i dont think so. Unfortunately, we cant do anything with a calendar, as the days per year is a fact and cannot be changed

Your question is a perfect example of an XY problem: you are asking
something that has little to do with your actual problem, but is rather
about your misguided idea of a solution. Counting Mars seconds or Titan
seconds is an easy problem. Dividing the frequency of a 1 MHz
signal by successive powers of 1.25 is a hard problem. There is little
value in turning an easy problem into a hard one.
I suggest a solution inspired by Bresenham's algorithm for
drawing slanted lines:

configure a timer to deliver a periodic interrupt to your program,
with a period shorter than your shortest relevant second
compute the ratio of your favorite planet's second to the interrupt
period
approximate this ratio by a rational number p/q

In the interrupt service routine:

increment a counter by q
when the counter reaches p, decrement it by p and note that one
second has elapsed.

The lazy way of getting a periodic interrupt is to simply enable the
TIMER0_COMPA interrupt. Timer 0 is already configured by the
Arduino core to count full cycle every 1,024 µs. You may want to
set OCR0A to something near 128 in order to prevent the overflow
interrupt (used by Arduino for timing) and your interrupt from getting
too close.
For the Earth, the ratio is
1 s / 1,024 µs = 1,000,000 / 1,024 = 976.5625 = 15625 / 16
For Mars and Titan, they can be approximated by 22,075/22 and 33,139/34
respectively, to within a fraction of a ppm.
Here is the interrupt service routine:
// Count of elapsed seconds on each planet.
volatile uint32_t earth_secs, mars_secs, titan_secs;

// Executed every 1,024 us on a timer interrupt.
ISR(TIMER0_COMPA_vect) {
    static uint16_t earth_ticks, mars_ticks, titan_ticks;
    earth_ticks += 16;
    if (earth_ticks >= 15625) {
        earth_ticks -= 15625;
        earth_secs++;
    }
    mars_ticks += 22;
    if (mars_ticks >= 22075) {
        mars_ticks -= 22075;
        mars_secs++;
    }
    titan_ticks += 34;
    if (titan_ticks >= 33139) {
        titan_ticks -= 33139;
        titan_secs++;
    }
}

Note that you can build better approximations of Mars and Titan seconds
by using rational numbers with larger p and q, but then you would
have to do 32-bit arithmetics in the ISR. You could also configure
another timer to deliver an interrupt with a longer period: you would
then be able to achieve better accuracy with 16-bit arithmetics, at the
cost of increased jitter.

Edit: Here is a variation on this idea that uses millis() instead
of interrupts. Of course, Nick Gammon is right: you do not need
interrupts for a clock that updates its display a few times per second.
It was just a bit easier to write an interrupt-based code, as the time
between successive calls of the function is a known constant.
Given that you are going to use a 32-bit processor, I wrote this using
32-bit arithmetic. The ratios should be a little bit more accurate.
uint32_t earth_seconds, mars_seconds, titan_seconds;

void update_planet_times() {
    // Compute number of elapsed milliseconds since last update.
    static uint32_t last_update;
    uint32_t now = millis();
    uint32_t elapsed_millis = now - last_update;
    last_update = now;

    // Update Earth time. 1 Earth second = 1000 / 1 ms.
    static uint32_t earth_ticks;
    earth_ticks += elapsed_millis * 1;
    uint32_t elapsed_earth_seconds = elapsed_earth_ticks / 1000;
    earth_ticks -= elapsed_earth_seconds * 1000;
    earth_seconds += elapsed_earth_seconds;

    // Update Mars time. 1 Mars second = 763426 / 743 ms.
    static uint32_t mars_ticks;
    mars_ticks += elapsed_millis * 743;
    uint32_t elapsed_mars_seconds = elapsed_mars_ticks / 763426;
    mars_ticks -= elapsed_mars_seconds * 763426;
    mars_seconds += elapsed_mars_seconds;

    // Update Titan time. 1 Titan second = 3193819 / 3200 ms.
    static uint32_t titan_ticks;
    titan_ticks += elapsed_millis * 3200;
    uint32_t elapsed_titan_seconds = elapsed_titan_ticks / 3193819;
    titan_ticks -= elapsed_titan_seconds * 3193819;
    titan_seconds += elapsed_titan_seconds;
}

Note that using this technique for the Earth may seem superfluous: one
may count seconds by simply computing millis()/1000. This, however,
would fail when millis() rolls over in 49.7 days. The code above
is immune to this rollover, and should count Earth seconds reliably for
the next 136.1 years.

Yes, Thank you, and i am planning to get Arduino Uno R4 which is capable to generate - fastest - 1/256 s interrupts using its in-built RTC - Clock, so this would also probably help. just numbers P,Q would be different right?

@Peter: Right. As stated in my answer, you have to compute the ratio of a planet's second to the interrupt period, then approximate this by a rational number. This Wikipedia section on Best rational approximations gives you a technique for computing the rational number p/q.

@Peter Regarding the 1/256 s comment, please see my expanded answer.

@Nick, I saw the answer, however, if Uno R4 has RTC clock, this clock will be way more exact than millis which probably takes the clock from resonator (or whatever else is attached to Uno R4 microprocessor), not sure, thats my guess.

@Edgar, As Uno R4 has the built in RTC clock, i think i should use advantage to take the 1/256 s interrupt from way more precise RTC clock. I dont think millis are attached to that RTC clock, just they are attached to the 48 MHz clock, using less precise resonator or whatever is attached to that chip as clock.

I am not familiar with the Uno R4 so I can't advise on how to use that. Perhaps Edgar has one.

Sure, i am willing to try both approaches, maybe the resonator will have small tolerance than previous Arduinos which i had. we will see

What you are suggesting is far too complex. Use the internal timers, say timer 0, 1 or 2 on the Atmega328P (Arduino Uno) with a prescaler of 64 (which gives you 4 µs per timer tick) and then count up to 250, giving you a period of 1 ms.
The timer can be configured to toggle an output pin, giving you this frequency as an output. If you are toggling you may want to halve what you count to (one count for the leading edge and the second count for the trailing edge). Or use PWM mode with a duty cycle of 50%.

From a comment to a different answer:

I am planning to get Arduino Uno R4 which is capable to generate - fastest - 1/256 s interrupts using its in-built RTC - Clock

Not at all. The Uno timers can be configured to interrupt at practically any rate (the limit being how fast the interrupt routine can execute).
The software from the IDE configures Timer 0 to interrupt once every 1.024 ms, which is a lot more often than 1/256 s. However you can reconfigure that, or indeed the other timers, to interrupt at virtually any interval, within reason.
See my page about timers for more information.
I could easily give you code that would generate an interrupt every 1/256s or indeed 1/32768s but I don't see how those rather unusual numbers, from the point of view of the planets, would help you.
In fact, probably better from your point of view is to simply keep track of elapsed time and do your calculations from that. For example, millis() tells you elapsed time since startup in milliseconds and will wrap around every 49.710 days. Or micros() which tells you the elapsed time in microseconds, and will wrap around every 71.58 minutes.
Now, you would need to handle wrap-around in any case, so that is no big deal.
It seems to me that your calculations for the planets' positions would simply be to take the current time (eg. using millis()) and then apply some arithmetic for each planet to work out where it must be.
Your desire to get interrupts, and your focus on 32768 as an interrupt interval seems to me to be be an XY problem. You know what they say, "if the only tool you have is a hammer, everything looks like a nail". Well, you have more tools than a hammer here.


text:
Arduino Servo MG90S not moving
I'm new with arduino (nano). I am having problems with Servo MG90S, I cant make it move. Im doing the easiest test, Servo cables connected:
Brown -> gnd
Red -> 5v
Orange -> pin 9
my arduino code is:
#include <Servo.h>
Servo servo;

const int servoPin = 9;

void setup()
{
  servo.attach(servoPin);
  Serial.begin(9600);
}

void loop()
{
  servo.write(40);
  delay(2000);
  servo.write(0);
  delay(2000);
}

As you see its a super simple example, but the result is the servo vibrating slightly.
Extra data: the servo start vibrating with the servo.attach(servoPin); it doesnt matters if I set the servo.write(40);

The parameter of Servo.write() is a value between 0 and 180, so -40 is not valid. Does is change something if you use 50 and 130 instead?

No, the same result. Even if I only set the attach without the servo.write the servo is vibrating with no stop. I don't know if that is a normal behavior

Arduino power source is one of the most common problems.  For example a 9 Volt battery may run an Arduino but is unlikely to have enough power to run a motor.  What are you using as a power source?

Also, if you change your code please edit the question to reflect the change.

As I'm in developing procces, im using the mini usb wire that goes to my desktop pc usb 3.0 port

Did you connect the servo to Arduino GND AND the USB port? That may be your problem. Nowhere does it say that. You just said "Brown -> gnd." That doesn't mean so.

Also, you may be connecting it to just the Arduino, and that could be the problem, too. As usually all Arduino have very little current.

Wait, so... what is the USB connected to? The servo? May you, please, provide more detail? I could give an answer, but I am not sure what the EXACT problem is.

I edited the post and added an image of how it tis connected, all is conected to protoboard and this to the arduino (in my cade arduino nano), the USB wire is the one who power de arduino board, and goes from my pc USB port

Okay... try this: use a separate 5V power supply for your servo. Connecting the red to the positive of the power supply, and black to the GND of the power supply. Let me, then, know if it's still twitching. That may be your problem.

Also, what model is the servo? Like, what is the name of it? It depends of why it is twitching. If it's a micro servo, it would SHOULD be fine. Just Google what you have and post what it is. The more details, the better.

Also, remember: Google is your best friend, in this case.

I compiled the code, it works. So, there seems to be an issue with the hardware. I am trying to decipher between the two: it's either your Arduino Nano or the servo itself. Or POSSIBLY both.

Oh, and I DID use the same exact wiring.

Oh, right. I didn't read. Sorry. The model of the servo is MG90S. I will read the datasheet on that.

Okay, so here is the deal: I have looked up the datasheet for the Arduino Nano and the MG90S. The problem is: you may have killed your Arduino Nano. As the datasheet for the Arduino Nano says, "Max DC Current per I/O Pin... 40 mA." (The Datasheet for Arduino Nano). I am not sure if that's 100% of the issue, so, then I looked up the MG90S and it says "Current (typical during movement)... 120-250mA" (Also, another datasheet). Basically, all that means is that you MAY have to buy another Arduino because you may have used a servo that requires to much (for lack of a better term) "power." Using some math we see that you went approximately: 210 milli-amps over. Sorry.

Okay, so my first answer is WRONG. The reason being is because the MG90S and the SG90 (which are very similar servos, except the gearing and some others) CAN run off that Arduino. As this article shows: How to control the MG90S with the Nano. However, it IS best to run that servo off a separate power supply (5V). The issue lies within your wiring. Somehow, there is some miscommunication between us, you, and the Arduino.

I have tested the output voltage
5v pin -> 4.6v
pin 9 with servo.write(0) -> 0.13v
pin 9 with servo.write(180) -> 0.56v
I don't know if these are acceptable values.

Do you know what I mean by "separate power supply?" I think you need some time to reflect. You seem to steadily NOT want to use another source for your servo. Why? I told you the answer, gave you an article, and even asked, kindly, for more details. What more do you want from me?

That article gives the EXACT instructions. *Edit - please edit your response with more detail, as I still can't seem to help you (which I really do).

Honestly, I think I am starting to second guess myself on my first answer. I will post it for your sake. I think you BURNT your Arduino. Outputting those results, they seem terrible. So, yeah, I think you BURNT your Arduino.

Sorry, I didn't realize there were two answers cause they appeared together and I only saw one. I think the other one is okey.
Thank you for taking your time to help.

Well, like I said, the first answer (that you accepted ) is flat out wrong. That was my assumption. But I am okay as long as you are okay, with the answer, of course. And sorry, if I came across as a jerk or frustrated. That was not the intention. Hope your project goes well, though! I just want you to learn about this Googling thing. Again, sorry.


text:
Connecting multiple MAX30100/30102 via I2C
I want to connect multiple (up to 4) MAX30100 or MAX30102 oximeter sensors to an Arduino via I2c. But I could not find a solution to change/assign the I2C address.
implementing-pulse-oximeter-using-max30100
datasheet MAX30100

it appears that the slave address is fixed, as per page 24 of the linked document ...... there is a typo in the document that refers to Table 18 ..... it probably should say Table 17

maybe the address register is undocumented ..... try reading all 128 registers ..... see if one of them contains the value AE

LTC4316 is what you need. I haven't used it yet, but I know it from a project that did: mocap. It is an I2C translator IC.
Of course, if you need those ICs to be far away from each other, use a uC (or a separate Arduino) with all of those, and connect them with a different protocol!

Good suggestion. (voted). I did not know that such chips existed. (Note that the data sheet I found online (https://www.analog.com/en/products/ltc4316.html#product-overview) says "At least one model within this product family is in production and available for purchase. The product is appropriate for new designs but newer alternatives may exist." Thus there might be newer chips that serve the same purpose and are likely to be available longer-term.

And that chip appears to be surface-mounted. I'm not equipped to do surface-mount soldering. I did find this option on SparkFun: https://www.adafruit.com/product/2717?gclid=EAIaIQobChMIk7S1-PLm4AIViZ-fCh39PQWEEAQYBSABEgJZ1PD_BwE

@Duncan C: MAX30100 is surface-mounted as well, so that's hardly a problem for OP. But thanks for the suggestion anyway! I haven't used it yet, I'm only familiar with this chip because I've read the above project. (I had to look for that mocap site to get the precise IC type.)

Is there any other way of solving this issue?
I do not want to increase Hardware dependency.
I found out this article - which lets you use multiple i2c devices with the same address by employing different data lines: https://bitbanksoftware.blogspot.com/2019/01/controlling-lots-of-oled-displays-with.html
The Github source: https://github.com/bitbank2/Multi_BitBang
To my knowledge, I, either have to implement this library my own way or us the TCA9548APW chip as described by @Duncan C in the above answer

Welcome to Arduino:SE This doesn't appear to provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

Nyos's suggestion of an I2C address translator is the ticket. I hadn't heard of these chips before, so I started searching. I found that the one they recommended may be being phased out. It also looks like it's surface-mounted. I found a TI data sheet that lists a DIP package chip TCA9548APW that lets you map up to 8 I2C devices to different addresses. You might want to check those out as an alternative.


text:
Shift register 74595 does not shift values
I am using a 74HC595 shift register IC connected to my Arduino board to drive 8 RGB LED modules. The LED modules have built in resistors and require a +5V at anode which I provide from the Arduino. Following is a rough schematic of the circuit, the pins numbers correspond to those on the Arduino UNO microcontroller.

Following is a small code for the same:

const int latchPin = 8;
const int clockPin = 12;
const int dataPin = 13;
const int redValuePin = 9;
const int greenValuePin = 10;
const int blueValuePin = 11;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(redValuePin, OUTPUT);
  pinMode(greenValuePin, OUTPUT);
  pinMode(blueValuePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Reset");
}

void loop() {
  analogWrite(redValuePin, 0);
  analogWrite(greenValuePin, 255);
  analogWrite(blueValuePin, 255);
  if (Serial.available() > 0) {
    int bitToSet = Serial.read() - 48;
    registerWrite(bitToSet, HIGH);
  }
}

void registerWrite(int whichPin, int whichState) {
  byte bitsToSend = 0x00;
  digitalWrite(latchPin, LOW);
  bitWrite(bitsToSend, whichPin, whichState);
  Serial.println(bitsToSend);
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);
  digitalWrite(latchPin, HIGH);
}

However, the shift register does not seem to be shifting values. This is verified as only O0 is high in MSBFIRST and only O7 is high in LSBFIRST mode of shiftOut(), irrespective of the bitsToSend value. That is, only the first line is high. Is there any reason in the hardware/software that caused this, or do I just have a faulty IC?

where are the current limiting resistors?

Try printing this value out int bitToSet = Serial.read() - 48; Depending on how you have configured the serial monitor you may have terminating characters in there.

The comment about the current limiting resistors is a very important one, especially because you haven't mentioned what those are actually doing. My guess is they are not lit, because they were over-currented and are now open.

Sorry I haven't shown this in the schematic above but I am sort of using an LED module that has the resistors with it.

Hint: A Power Supply the Arduino is NOT! You are probably having the arduino's regulator overheating and shutting down. This is a SWAG as the schematic does not show power sources other then the Arduino.

Yes it is true that I am using the Arduino as a power supply. I will try using an external power supply. Hopefully that solves it.

This problem has been resolved. As it turns out, the error was with the serial monitor, as it sent more than one value to the variable (the second one causing the bitToSet to be negative). This is most likely due to terminating characters as pointed out by @6v6gt. I guess it is much better to use standard functions like atoi() to convert serial monitor data to integers.

In relation to my previous comment, the problem was due to my Serial monitor adding a NL (new line) character to my inputs, once configured to not do this, the program works fine.

I guess that qualifies as an answer which you can add yourself and maybe you get a few brownie points. Thanks anyway for reporting back.

Yeah actually I tried doing that but cannot since the question was closed. I have edited it and submitted for reopening though.


text:
Multiple TFT's not displaying
I am trying to connect about 5 TFT's to my Arduino Uno and I got to the point of hooking two of them up without any issues. However, after a code upload, they stopped working. I then took all the code out and tested each in isolation and they still function. However, together only one of them displays data.
The TFT's I am using are the ST7789v2 found here. https://www.waveshare.com/wiki/1.69inch_LCD_Module#Hardware_Connection_3
I have wired them up according to the schematic with "all" pins being shared except the CS pin. Each display has its own.
The code looks like this;
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>

#define TFT_CS1 10
#define TFT_CS2 3

#define TFT_RST        8 // Screens shared
#define TFT_DC         7 // Screens shared
#define TFT_BACKLIGHT  9 // Backlight for all screens

Adafruit_ST7789 tftHour1 = Adafruit_ST7789(TFT_CS1, TFT_DC, TFT_RST);
Adafruit_ST7789 tftHour2 = Adafruit_ST7789(TFT_CS2, TFT_DC, TFT_RST);

Adafruit_ST7789 setupScreen (Adafruit_ST7789 tft){
  tft.init(240, 280);
  tft.fillScreen(ST77XX_BLACK);
  return tft;
}

void setup(void) {
  tftHour1 = setupScreen(tftHour1);
  tftHour2 = setupScreen(tftHour2);
}

void loop(){
  tftHour1.print("1");
  tftHour2.print("2");
}

When this executes, display 2 shows output but display 1 does not. Weirdly if I take the CS from display 1 and pop it into the same line on the breadboard as CS2, and then put it back into its original position, display 1 and 2 seem to work. But only till the next power cycle or upload.
Also oddly, setting the colour of each screen works even if one is blue and the other is say green. Both change to their respective colours. But when I try to write text to them, only one of them has text.
If I comment the code for tftHour2, then tftHour1 starts showing text. If I swap the setup code for ftfHour1 and tftHour2, then the display that is last to init, is the one that shows the text and the other stays blank.
Like I said, I had all this working and then a simple font change upload and it all stopped working.
Any help on this is really appreciated.
I should mention that I am a programmer and very new to electronics so please keep it simple.
#Update. If I have separate RST pins then it works. But I need 5 screen and will run out of pins in that case. Is there a way to get around that?

your code is inconsistent ... there is a definition for two object names tftHour1 and tftHour2 and then you throw in an object name tft

so that's within a function where I can send it a tft object, init that and return. The name of the object, inside the function, is tft. it's for reusability and to cut down on the amount of code and thus space

Off-topic: Your function setupScreen() takes a Adafruit_ST7789 as argument, that is perfect to use the same code. But 1st, why does the function need to return that argument? And 2nd, why do you overwrite the existing objects in tftHour1 and tftHour2 with themselves?

I did that initially because I wasn't quite sure whether the Arduino IDE considered the passed object context as local or not. However, it makes no difference whether I return the object, and overwrite the global one, or not.

@thebusybee he probably needs it because he is passing it as copy of original, so it doesn't affect the original object without making copy back into it :D Hint: he should use pass by reference (or pointer, but reference is more straightforward) void setupScreen (Adafruit_ST7789 & tft) { // now changes to tft will be changing original object too

According to the data sheet, the RST signal is accepted without an active CS, so when sharing this signal, all displays are reset if you initialize just one of them. That explains the behavior you observe.
You found the solution: Do not share the RST signal in all instances of Adafruit_ST7789.

Now you worry about the needed number of pins, and that is indeed an issue.
One possible solution is to use a decoder that takes n inputs to activate 1 of 2n outputs, like this:

simulate this circuit – Schematic created using CircuitLab
To control 5 RST lines you will need only 3 pins. Use a binary value to select one of the unused outputs to deactivate all RST lines.
The same is true of the CS lines.
However, the library in use does not support this kind of control. Therefore, I'm afraid that you need to consider another Arduino model with more pins.

As a work-around, you might want to try this alternative:
Assign the same Arduino pin to all instances of Adafruit_ST7789, as in your first attempt. But do not connect it to the RST inputs of the displays. Leave the Arduino pin unconnected.
Instead, use another Arduino pin and connect that to the displays. Then during initialization, reset all displays with your own code. See the data sheet for correct levels and timing.
Or try to connect the RST inputs of all displays to VCC, as they may work without an explicit hardware reset just fine.

In a comment you brought up the idea of using a multiplexer.
Without any other change, you would need the selection signals as additional pins to the multiple CS pins, in your case 3 more.
Instead you can also share the CS signal in the same way:

simulate this circuit
It is very important that you use multiplexers that output the inactive level as required by the displays on not selected outputs!
Even now you should instantiate as many Adafruit_ST7789 as you have displays, because each instance most probably stores internal information necessary for its correct working. But you can use the same pins on all of them.
Before you call any method of an instance, switch the multiplexers to the associated display.
To be sure that all data is completely transmitted, you might need a small delay after the called method. Perhaps the called method already blocks until all data is completely transmitted. You might try to read the library's source to learn more.

Assigning a single pin. I will try that because I can simply reset them at intervals when a value changes, for example, when the minute changes over.
What if I used a multiplexer? Could I then hook up the RST and the CS to it? Unsure how that might work

@griegs Unless the library code does set CS before doing the Reset, it won't work for you. And the question is if the TTFs can handle CS during RST. Maybe try NOT_A_PIN (or how it's named) for RST passed into tft objects and toggle the real RST pin for some time by yourself before going into TFT init functions

@griegs Is it necessary to reset a display before it can show new content? I don't think so, it would be quite strange. -- Concerning the multiplexer idea, I'll extend my answer.

@griegs add a couple of gates so that the RST can be asserted only when CS is asserted ... that way you would need only one pin to drive the RST line

@thebusybee, pretty sure the screen does not require a reset to draw new content. I "could" reset once a day and simply black out the area I want to write to ahead of any write. Then at 2am, do a reset to clear the cache


text:
Why does my code or Serial Monitor hang with analogRead?
I have the following code in loop() to collect values from an electret microphone
for(int i=0; i<sampleSize; i++){
  analogVal[i]= analogRead(ADC_Pin);
  sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.
My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

You claim  “the Serial Monitor hangs and does not display any values” even though the code doesn't have any references to Serial output!  Obviously that's the problem! ¶ Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.

I've added the serial prints that immediately follow the for loop. It does not matter whether the Serial.print is inside or outside the for loop. The serial monitor does not show anything.

Now the obvious problem is that you didn't say Serial.begin(115200); [or whatever the data rate is that you have your serial monitor set at] ¶ Anyway, I don't know what the problem is, and if you don't edit your question to include a Minimal, Complete, and Verifiable example of code -- with visible definitions of every variable used, etc -- perhaps nobody else will be able to tell either.

Yes, MCVE please. There's nothing wrong with the code in your question which would result in this particular problem. (There's another problem but never mind that for now.) The problem is with code you haven't shown.

What is analogVal? What is sumOfSquares? What is the sq() function? In short: DO NOT POST SNIPPETS LIKE THIS - POST A COMPLETE PROGRAM SO WE CAN SEE THE ENTIRE PROGRAM AND VARIABLE DECLARATIONS.

Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.
I suppose, that analogVals[] is declared as int and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome 48 bytes for all your others variables (including int i in the for cycle and Serial outside it) and stack for calling functions (like analogRead and sq) and all theirs variables and functions and arguments.
So int i = 2B, Serial = 2B, sumOfSquares = 2B, "Sum of squares: " = 17B of what I see takes anothe 23 bytes of those 48 bytes leaving us with only 25 bytes for all else.
I bet, that you try to use more REAM, than you have and so your stack overflows and

destroys some variable content on the vay
is overwriten by assigning to some variables, which then leads to all sort of problems.

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


text:
I2C Arduino ESP8266 Bad Reading
I have a NodeMCU, which I program with the Arduino IDE. I have connected a VOC sensor to pins D1, D2, which are the SLC/SDA pins for NodeMCU. They have pull-up resistor at 4,3kohm to 3.3V.
First I used I2C scanner code, provided by Arduino, and got a response that I have the sensor connected at address 0x70, which is the correct address, indicated on the datasheet for the sensor.
After I tried to read values from the sensor with command 0b00001001 (provided in the datasheet also), I only get 0s as output! Probably something weird in the coding, perhaps someone could assist me in what I am doing wrong here?
In the code, I request 100 bytes just to make sure to get everything, but I receive only 32 back. The datasheet says it should be 6 bytes on address 0x9. And I have tried hex and dec form but that doesn't work. Binary is the proper way I assume.
My Output:
Start
Bytes Available: 32
Data read: 00000000000000000000000000000000

Code:
#include <Wire.h>

int miscadr = 0b1110000;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  delay(100);
}

void loop() {
  Serial.println();
  Serial.print("Start");
  Serial.println();
  Wire.beginTransmission(miscadr); //Start bit
  Wire.write(0b00001001); //Asking for registry 9
  Wire.endTransmission();
  Wire.requestFrom(miscadr, 100);
  Serial.print("Bytes Available: ");
  while(Wire.available()==0);
  Serial.print(Wire.available());
  Serial.println();
  Serial.print("Data read: ");
  while(Wire.available()!=0) {
    Serial.print(Wire.read());
  }
  Serial.println();
  delay(2000);
}

Check your sensor is operating and responding OK,some basic code here for an UNO,a little simpler than HGrabas Library. https://github.com/AmphenolAdvancedSensors/Telaire/tree/VOC-Sensor-VX89-TE

If your ESP8266 device NodeMCU is not using the Arduino ESP8266 Library standard pins for I2C ( SDA=2, SCL=14) then you must change the Wire.begin() statement to Wire.begin(SDA, SCL) inserting your values for the SDA and SCL pins. See this note for another ESP breakout (Sparkfun) Arduino ESP8266 Wire

Thank you for the reply! It didnt do any difference though. I did get a respons from the sensor on what adress it is on, and other sensors works good. So the pin output should be properly configured for the i2c.
Let me know if you have other suggestions! Thank you.

Which VOC sensor is it ? I like to see the datasheet myself. My crystal ball tells me it is a MiCS-VZ-86/89. When the i2c scanner finds address 0x7, then you should use 0x7. In your sketch the miscadr is now 0x70.
The read and write bit is taken care of by the Wire library. You could print the return value of Wire.endTransmission and Wire.requestFrom. The Wire.endTransmission  returns an error and the Wire.requestFrom returns the number of read bytes. Those return values can tell if the I2C transaction was wrong.
There is no need for a while-loop to wait for data after the Wire.requestFrom. You can remove that first while statement.
You can not request 100 bytes. The Wire library has a buffer of 32 bytes.
When you use the term "address", please use "i2c address" or "register address".
The Wire.requestFrom reads bytes from the Slave (the VOC sensor), but the sensor can not stop the I2C transaction after 6 bytes. The Master (the ESP8266) should set the number of bytes to read. If you need only 6 bytes, then you should read only 6 bytes.

Thank you very much for the reply! The i2c adress of the MiCS-VZ-89TE(great crystal ball you have btw!) is 0x70, not 0x7 as I wrote. So the code was right on that part.
Serial.print for endTransmission returns 0, and for requestFrom returns 7.
Still, all I get is a bunch of 0s in return from the sensor! Cannot figure out the reason for this. I have changed the pullup resistors to 4.7kohm also, without any difference.. Any more suggestions what I can try? Thank you!

Zero errors from Wire.endTransmission means you are communicating with the sensor. Request 6 bytes and see what happens.

I only receive 0s, 32bytes or 6bytes requested.. Scratching my head here!

On this page http://www.sgxsensortech.com/sensor-selector/#prod_4569 under the tab "Application notes" I selected the I2C application note. It says that you need to send 6 bytes, and you will receive 7 bytes. Older versions of that sensor require only the command 0x09, but according to the datasheets the MiCS-VZ-89TE always requires those 6 bytes. The Upgrade Guide appliction note shows a short CRC calculation function.

@Martik I am late to the party and you might have fixed your issue by now. If it helps I wrote a lib for the  MiCS-VZ-89TE, I have it working on the EPS8266-01  https://github.com/HGrabas/MICS-VZ-89TE

authors: Александр Пинчук

authors: Олег Красавцев

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


text:
Lora SX1278 stops receiving after a short time
I am working with two Lora ra-02 sx1278 modules and two Arduino Uno.
Programming on Arduino IDE 2.1.1
sender

receiver

The problem is the receiver receives a few packets successfully, but then the board no longer receives the signal. I know the sender is sending data constantly because the RX LED on Arduino blinks.
Every time I reset the receiver board, it starts receiving again and then stops after a few packets.
I have this problem when running the basic send and receive example of the Lora library itself.
Here's the library I'm using from Arduino IDE libraries:
link of the Lora library
(I just changed the frequency to 433 for my area, and reduced the delay of sending packets from 5 seconds to 1 second)
I couldn't find anything helpful on the internet.
Any suggestions?
Update: My project is a hand-gesture-controlled car. I uploaded the project's program on boards. With this code, if the command to the robot car is "stop", it receives some packets every 1 second and then after an acceptable time, doesn't receive anymore. But if I move my hand so it sends move commands to the car, it receives the move command and motors work but it doesn't receive the next packet.
When I detached the motor drivers from Arduino, it received at least 15-20 packets. Apparently, it receives packets but after motor drivers and motors work, it suddenly doesn't receive anything. I'm confused.
Sender:
#include <SPI.h>
#include <LoRa.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

int counter = 0;
String msg = "";
int xdata = 0;
int ydata = 0;
int flag=0;
Adafruit_MPU6050 mpu;

void setup() {
  Serial.begin(9600);
  while (!Serial)
  Serial.println("LoRa Sender");
  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");
  LoRa.setTxPower(10);
}
void loop() {
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);
  xdata = a.acceleration.x;
  ydata = a.acceleration.y;
  Serial.println(counter);

  if((xdata>2)&&(flag==0))
  {
    flag=1;
    msg = "l";
    Serial.println("l");
    }
  if(xdata<-2 && flag==0)
  {
    flag=1;
    msg = "r";
    Serial.println("r");
    }
  if(ydata>2 && flag==0)
  {
    flag=1;
    msg = "b";
    Serial.println("b");
    }
  if(ydata<-2 && flag==0)
  {
    flag=1;
    msg = "f";
    Serial.println("f");
    }
  if((xdata<2)&&(xdata>-2)&&(ydata<2)&&(ydata>-2)&&(flag==1))
  {
    flag=0;
    msg = "s";
    Serial.println("s");
    }

  LoRa.beginPacket();
  LoRa.print(counter);
  LoRa.print(msg);
  LoRa.endPacket();
  counter++;
  delay(1000);
}

Receiver:
#include <SPI.h>
#include <LoRa.h>

int motor1pin1 = 3;   //front left
int motor1pin2 = 4;
int motor2pin1 = 5;   //front right
int motor2pin2 = 6;
int motor3pin1 = A0;  //back right
int motor3pin2 = A1;
int motor4pin1 = A2;  //back left
int motor4pin2 = A3;
String  msg="";

void setup() {
  pinMode(motor1pin1, OUTPUT);
  pinMode(motor1pin2, OUTPUT);
  pinMode(motor2pin1, OUTPUT);
  pinMode(motor2pin2, OUTPUT);
  pinMode(motor3pin1, OUTPUT);
  pinMode(motor3pin2, OUTPUT);
  pinMode(motor4pin1, OUTPUT);
  pinMode(motor4pin2, OUTPUT);

  Serial.begin(9600);
  while (!Serial);

  Serial.println("LoRa Receiver");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = LoRa.parsePacket();
  yield();
  if (packetSize) {
    // received a packet
    Serial.print("Received packet '");
    // read packet
    while (LoRa.available()) {
      msg=(char)LoRa.read();
      Serial.print(msg);
    }
    //Serial.println(msg);
    if(msg=="f")
    {
      digitalWrite(motor1pin1, HIGH);
      digitalWrite(motor1pin2, LOW);
      digitalWrite(motor2pin1, HIGH);
      digitalWrite(motor2pin2, LOW);
      digitalWrite(motor3pin1, HIGH);
      digitalWrite(motor3pin2, LOW);
      digitalWrite(motor4pin1, HIGH);
      digitalWrite(motor4pin2, LOW);
      Serial.println(" :  Forward");
    }
    else if(msg=="b")
    {
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, HIGH);
      digitalWrite(motor2pin1, LOW);
      digitalWrite(motor2pin2, HIGH);
      digitalWrite(motor3pin1, LOW);
      digitalWrite(motor3pin2, HIGH);
      digitalWrite(motor4pin1, LOW);
      digitalWrite(motor4pin2, HIGH);
      Serial.println(" :  Back");
    }
    else if(msg=="l")
    {
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, HIGH);
      digitalWrite(motor2pin1, HIGH);
      digitalWrite(motor2pin2, LOW);
      digitalWrite(motor3pin1, HIGH);
      digitalWrite(motor3pin2, LOW);
      digitalWrite(motor4pin1, LOW);
      digitalWrite(motor4pin2, HIGH);
      Serial.println(" :  Left");
    }
    else if(msg=="r")
    {
      digitalWrite(motor1pin1, HIGH);
      digitalWrite(motor1pin2, LOW);
      digitalWrite(motor2pin1, LOW);
      digitalWrite(motor2pin2, HIGH);
      digitalWrite(motor3pin1, LOW);
      digitalWrite(motor3pin2, HIGH);
      digitalWrite(motor4pin1, HIGH);
      digitalWrite(motor4pin2, LOW);
      Serial.println(" :  Right");
    }
    else if(msg=="s")
    {
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, LOW);
      digitalWrite(motor2pin1, LOW);
      digitalWrite(motor2pin2, LOW);
      digitalWrite(motor3pin1, LOW);
      digitalWrite(motor3pin2, LOW);
      digitalWrite(motor4pin1, LOW);
      digitalWrite(motor4pin2, LOW);
      Serial.println(" :  Stop");
    }
    LoRa.receive();
  }
}

There are 10 sketches in the library, you need to be more specific which is/are the one you are using. We don't want to guess which one. 2) Does it crash/stop working if you change the interval to 5s instead of 1s? 3) BTW, Lora is designed for Long range communication(as compare to WiFi) for a limited shared frequency resource, before you decide to blasting the airwave every second (even you are using it as peer-to-peer), please be away of duty cycle requirement.

@hcheung thanks for your reply. 1)I'm testing LoRaSender and LoRaReceiver. 2) Yes. With more delay, it receives more packets but it stops again. 3)I don't have much information about it. Can you tell me the limitations? I'm using 433 MHz. I read the link you provided but don't know what the duty cycle is in my case.

I found a solution !!!
Many people have experienced this but until now no one had found a solution:
https://github.com/sandeepmistry/arduino-LoRa/issues/447
https://stackoverflow.com/questions/63861160/arduino-nano-with-ra-02sx1278-freezes-after-receiving
This is a good workaround, but it wouldn't hurt for SEMTECH to understand why it happens
and also that he would give us the official solution, or fix the defect in his chips.
// ============================================================================
//  Each time the OnReceive callback is called there is a small error chance
//  this could be approximately every 1000, 3000 or sometimes 10000 calls.
// ----------------------------------------------------------------------------
//  When this happens the DIO0 interrupt pin remains stuck high
//  with a voltage fixed to 3.3V and interrupt receiving no longer works.
// ----------------------------------------------------------------------------
//  To correct this problem we test in the loop() if the DIO0_PIN is HIGH
//  and in this case we redo all the initializations.
// ============================================================================

// ============================================================================
//  RESTART RECEIVER INTERRUPT IF LOCKED
//  This function must be called periodically from the loop()
// ============================================================================
void RestartReceiverInterruptIfLocked()
{
  if (digitalRead(DIO0_PIN) == HIGH)
  {
    RTX_Init();
  }
}

// ============================================================================
//  RTX INIT
// ============================================================================
void RTX_Init()
{
  // ---------------------------------------------- BEGIN
  while (!LoRa.begin(RTX_FREQUENCY))
  {
    Serial.println("Error initializing LoRa module");
    delay(100);
  }
  // ---------------------------------------------- SETTINGS
  LoRa.setTxPower(17); // do here your additional settings
  // ---------------------------------------------- REGISTER CALLBACK
  LoRa.onReceive(RTX_OnReceive);
  // ---------------------------------------------- START RECEIVE
  LoRa.receive();
}

The first thing that comes to mind is that the delay between sends is too short. Not only are you flooding the airwaves with your packets (fair use, 1% airtime and all that), but after a few packets your receiver might not be able to keep up and start missing packets.
Also, there's the definite possibility that another device in the neighourhood is sending packets too, and interferes with your transmission. You are after all on the standard 433 MHz frequency, with default settings.
Try:

Change frequency to something less crowded.
Change SF / BW to something less standard.
Set delay between pings to around 30 seconds.
Depending on the LoRa library you are using, consider using CAD, Channel Activity Detection.

I just saw you are using the arduino-LoRa library. It has CAD, not in the master branch, but in a separate branch.


text:
Where to find interrupt flag for 3rd-party Arduino board cores?
This question might be a bit broad, but I'm running into an apparently classic problem with Arduino interrupts, where the rising or falling edge flag is triggered prior to a rising or falling edge technically occurring before a pin is pulled high/low and the microcontroller "remembering" that event occurred, running the interrupt the moment it gets attached to a pin. In this case, I'm working with Sparkfun's Artemis module (using the Apollo3 microcontroller). The code in question can be seen below:
#define SLEEP_INTERRUPT   4

void setup
{
    pinMode(SLEEP_INTERRUPT, INPUT);
#ifdef DEBUG
  Serial.print("About to attach interrupt");
#endif
  attachInterrupt(digitalPinToInterrupt(SLEEP_INTERRUPT), sleepModeSwitch, FALLING);
#ifdef DEBUG
  Serial.print("Interrupt attached");
#endif
}

void sleepModeSwitch()
{
#ifdef DEBUG
  Serial.print("Interrupt triggered! button status: "); Serial.println(digitalRead(SLEEP_INTERRUPT));
#endif
  if(sleep_mode_status == false)
  {
    goToSleep();
  }
  else
  {
    wakeUp();
  }
}

void goToSleep()
{
  sleep_mode_status = true;
#ifdef DEBUG
  Serial.println("Going to sleep");
  delay(50);  //Wait for serial to finish
  Serial.end(); //Power down UART(s)
#endif
  // turn off the led.
  digitalWrite(LED_BUILTIN, LOW);

  // Stop the BLE advertising.
  BLE.stopAdvertise() ;

  powerControlADC(false);

  for(int x = 0; x < 50; x++)
  {
    if(x != 4)
    {
      am_hal_gpio_pinconfig(x, g_AM_HAL_GPIO_DISABLE);
    }
  }
  //Power down Flash, SRAM, cache
  am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_CACHE); //Turn off CACHE
  am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_FLASH_512K); //Turn off everything but lower 512k
  am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_SRAM_64K_DTCM); //Turn off everything but lower 64k
  //am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_ALL); //Turn off all memory (doesn't recover)

  // // Enable interrupts to the core.
  am_hal_interrupt_master_enable();

  // //Enable the timer interrupt in the NVIC.
  // NVIC_EnableIRQ(STIMER_CMPR6_IRQn);

  //Go to Deep Sleep.
  am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP);
}

void wakeUp()
{
  am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_MAX);

  // Re-enable UART0 pins
  am_hal_gpio_pinconfig(48, g_AM_BSP_GPIO_COM_UART_TX);
  am_hal_gpio_pinconfig(49, g_AM_BSP_GPIO_COM_UART_RX);

  am_hal_pwrctrl_periph_enable(AM_HAL_PWRCTRL_PERIPH_UART0);

  initializeADC();

#ifdef DEBUG
  Serial.begin(115200);
  Serial.println("Waking up! Hello world!");
#endif
  deepSleepTimer = millis() ;
  sleep_mode_status = false;
}

Based on my research, the solution for this is to just clear the interrupt flag manually before attaching the interrupt to your desired pin. Unfortunately, so far the methods for doing so that I've found only work for AVR boards, and I'm not certain where to look to find more information about how to access an interrupt flag in a sketch for a 3rd-party Arduino core. Does anyone have a suggestion or two on where to start?

Not sure I understand the issue, but it sounds like you could declare a volatile bool, isReady=false, and in the top of the handler say something like if(!isReady)return;, and add isReady=true; after your attachInterrupt call. Or maybe just snuff the first call with if(!isReady){ isReady=true;return;} in the handler.

Can you rule out the following possible cause of your problem? https://github.com/sparkfun/Arduino_Apollo3/issues/416

@6v6gt Would a 10k pullup resistor negate this issue?

It does appear from that problem report, if it is relevant to your case, that an external pullup would solve it. If you are invoking attachInterrupt() in setup() only then you could also do a trick (workaround)  with a global variable say endOfSetup and ignore any calls to the ISR where this was not set. Cleaning up, clearing flags etc., before using attachInterrupt() is very common so IMHO it is wrong that you have to go under the abstraction layer to do it.

@6v6gt I followed advice from elsewhere (and from dandavis) and made a software debounce with the millis() function to prevent the interrupt from getting too far if it's called too often. I also talked with someone on the Sparkfun forums about this and we might have fixed it. Seems it was a problem in the core's commonInterrupt.cpp file. Not certain, but I've at least stopped that premature interrupt from screwing up the device, even if I'm not certain I've stopped it from running at all. Still experimenting

the rising or falling edge flag is triggered prior to a rising or falling edge technically occurring before a pin is pulled high/low and the microcontroller "remembering" that event occurred, running the interrupt the moment it gets attached to a pin

There is no "technically" about it. This is what is supposed to happen. Once you configure the interrupt to happen (as you do in setup) then the processor will remember that the condition has happened, whether or not interrupts are enabled.
If you want the interrupt only to be processed after a certain point, then yes, you should clear the "interrupt has happened" flag in the MCU, before enabling interrupts.
Your question is pretty non-specific about exactly which processors you are talking about, but I would certainly clear any appropriate flags before attaching the interrupt.

I'm not certain where to look to find more information about how to access an interrupt flag in a sketch for a 3rd-party Arduino core

The datasheet of the device on this particular core?

Judging by the datasheet for the Apollo3 Blue SoC:

6.3.2.15 INTCLR Register
IO Master Interrupts: Clear
OFFSET: 0x00000228
INSTANCE 0 ADDRESS: 0x5000C228
Write a 1 to a bit in this register to clear the interrupt status associated with that bit.

However I don't have one of those processors around to test it.

Added a link to the device and a link to the datasheet for the microcontroller it contains. In this case, it's Sparkfun's Artemis module, containing Ambiq's Apollo3 Blue SoC. And you're right, I was asking this in a more general fashion, intending to learn in general where to learn how to clear these flags for when I'm working with another microcontroller I'm getting to grips with

@E.HP.S See amended answer.


text:
VSCode Platformio Schedule.h: No such file or directory
I suppose this might be more an environment question regarding Platform.io and VSCode, as my code works great in the Arduino IDE, however the lack of syntax highlighting is driving me mad.
I've setup a Platform.io project in VSCode, copied my code across and setup my board (Wemos D1 Mini)
My platformio.ini file looks like:
[env:wemos_d1_mini32]
platform = espressif32
board = wemos_d1_mini32
framework = arduino

There are a couple of headers that are highlighted as having errors:
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

I've installed FirebaseESP8266 to my project from the PlatformIO libraries, however it still says:

include errors detected. Please update your includePath. Squiggles are disabled for this translation unit
  (C:\Users\Greg\Documents\PlatformIO\Projects\Lovebox\src\main.cpp).C/C++(1696)

If I try to build it errors with src\main.cpp:1:22: fatal error: Schedule.h: No such file or directory
As for the ESP8266WiFi library, it simply says cannot open source file "ESP8266WiFi.h"
Anyone know where I'm going wrong?

Did you install the libraries you need / use?
You could do it either via the platformio screen or add the names directly to the
platformio.ini
lib_deps =
    Firebase ESP8266 Client@>=2.7.8

And additionally ESP8266WiFi.h is an ESP8266 library
for the ESP32 you should use the lib #include <WiFi.h>
EDIT: To update the project libraries, select 'Update Project Libraries' from the project tasks.


text:
AES 128 CBC mode Help
Firstly i printed input[16] then encrypted it and printed the cipher and finally decrypted and printed input[16] but why my result is not matching after decryption ???????
I tried with different baud rate and also different input output array but not working.
Library Used: https://rweather.github.io/arduinolibs/classCBC.html
#include <CBC.h>
#include<AES.h>
CBC<AES128> cbc;

 void setup() {
 // put your setup code here, to run once:
 Serial.begin(9600);

 uint8_t key[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
 uint8_t iv[16] = {0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3};
uint8_t input[16] = {0,1,2,3,0,0,0,0,0,1,1,1,2,2,3,3};
size_t len = 16;

cbc.setKey(key, 16);
cbc.setIV(iv, 16);

for(int i=0; i<16; i++)
Serial.print(input[i]);
Serial.println("");

cbc.encrypt(input, input, len);
delay(1000);

Serial.print("input:");
for(int i=0; i<16; i++)
Serial.print(input[i]);
Serial.println("");

cbc.decrypt(input, input, len);
delay(1000);

Serial.print("input:");
for(int i=0; i<16; i++)
Serial.print(input[i]);
Serial.println("");

cbc.clear();
}

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

}

Create a separate output array. Currently the output variable is the same as the input. Depending on the algorithm this can be problematic.