text:
Arduino OTA - difference between Arduino IDE and PlatformIO
I used to OTA sketches and data files using the ArduinoOTA and ESP32 sketch data Upload tools and the ESP32 devkit, for example when using the Arduino IDE.
Versions:

Arduino IDE- 1.8.19
ESP32 on Arduino IDE - 1.0.6
ArduinoOTA 1.0.9

Moving to PlatformIO-
Started a new project using the ESP32 devkit, ArduinoOTA was added from the registry to the project (also 1.0.9 as on Arduino IDE).
And now - when I tried to copy the BasicOTA example from the Arduino IDE's ArduinoOTA example, the compilation failed.
To make sure I don't have any library/version issues, I checked:

WiFi, ESPmDNS is part of builtin.
WiFiUdp was not found not inbuiltin,installed nor registry - not shown in dependency graph during compilation -- ??
ArduinoOTA used from registry.

#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "dvirz_iot";
const char* password = "GdSd13100301";

void setup() {
  Serial.begin(115200);
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 3232
  // ArduinoOTA.setPort(3232);

  // Hostname defaults to esp3232-[MAC]
  // ArduinoOTA.setHostname("myesp32");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA
    .onStart([]() {
      String type;
      if (ArduinoOTA.getCommand() == U_FLASH)
        type = "sketch";
      else // U_SPIFFS
        type = "filesystem";

      // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
      Serial.println("Start updating " + type);
    })
    .onEnd([]() {
      Serial.println("\nEnd");
    })
    .onProgress([](unsigned int progress, unsigned int total) {
      Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    })
    .onError([](ota_error_t error) {
      Serial.printf("Error[%u]: ", error);
      if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
      else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
      else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
      else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
      else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });

  ArduinoOTA.begin();

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

void loop() {
  ArduinoOTA.handle();
}

and got this compilation error:
 *  Executing task in folder esp32_OTA_from_scratch: platformio run --environment esp32dev

Processing esp32dev (platform: espressif32; board: esp32dev; framework: arduino)
-------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
PLATFORM: Espressif 32 (6.1.0) > Espressif ESP32 Dev Module
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES:
 - framework-arduinoespressif32 @ 3.20007.0 (2.0.7)
 - tool-esptoolpy @ 1.40500.0 (4.5.0)
 - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 34 compatible libraries
Scanning dependencies...
Dependency Graph
|-- ArduinoOTA @ 1.0.9
|-- ESPmDNS @ 2.0.0
|-- WiFi @ 2.0.0
Building in release mode
Compiling .pio/build/esp32dev/src/main.cpp.o
Building .pio/build/esp32dev/bootloader.bin
Generating partitions .pio/build/esp32dev/partitions.bin
esptool.py v4.5
Creating esp32 image...
Merged 1 ELF section
Successfully created esp32 image.
Compiling .pio/build/esp32dev/lib8f4/Update/HttpsOTAUpdate.cpp.o
Compiling .pio/build/esp32dev/lib8f4/Update/Updater.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFi.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiAP.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiClient.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiGeneric.cpp.o
Archiving .pio/build/esp32dev/lib8f4/libUpdate.a
Indexing .pio/build/esp32dev/lib8f4/libUpdate.a
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiMulti.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiSTA.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiScan.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiServer.cpp.o
Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiUdp.cpp.o
Compiling .pio/build/esp32dev/libc4b/FS/FS.cpp.o
Compiling .pio/build/esp32dev/libc4b/FS/vfs_api.cpp.o
Compiling .pio/build/esp32dev/lib263/SPI/SPI.cpp.o
Archiving .pio/build/esp32dev/liba9d/libWiFi.a
Indexing .pio/build/esp32dev/liba9d/libWiFi.a
Compiling .pio/build/esp32dev/lib494/SD/SD.cpp.o
Archiving .pio/build/esp32dev/lib263/libSPI.a
Indexing .pio/build/esp32dev/lib263/libSPI.a
Compiling .pio/build/esp32dev/lib494/SD/sd_diskio.cpp.o
Compiling .pio/build/esp32dev/lib494/SD/sd_diskio_crc.c.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorage.cpp.o
Archiving .pio/build/esp32dev/libc4b/libFS.a
Indexing .pio/build/esp32dev/libc4b/libFS.a
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageAVR.cpp.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageESP.cpp.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageRP2.cpp.o
Archiving .pio/build/esp32dev/lib494/libSD.a
Indexing .pio/build/esp32dev/lib494/libSD.a
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageSTM32.cpp.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/OTAStorage.cpp.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/WiFiOTA.cpp.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/utility/rp2_flash_boot.c.o
Compiling .pio/build/esp32dev/lib624/ArduinoOTA/utility/stm32_flash_boot.c.o
Compiling .pio/build/esp32dev/lib6d4/ESPmDNS/ESPmDNS.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/Esp.cpp.o
Archiving .pio/build/esp32dev/lib624/libArduinoOTA.a
Compiling .pio/build/esp32dev/FrameworkArduino/FirmwareMSC.cpp.o
Indexing .pio/build/esp32dev/lib624/libArduinoOTA.a
Compiling .pio/build/esp32dev/FrameworkArduino/FunctionalInterrupt.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/HWCDC.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/HardwareSerial.cpp.o
Archiving .pio/build/esp32dev/lib6d4/libESPmDNS.a
Indexing .pio/build/esp32dev/lib6d4/libESPmDNS.a
Compiling .pio/build/esp32dev/FrameworkArduino/IPAddress.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/IPv6Address.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/MD5Builder.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/Print.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/Stream.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/StreamString.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/Tone.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/USB.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/USBCDC.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/USBMSC.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/WMath.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/WString.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/base64.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/cbuf.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-adc.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-bt.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-cpu.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-dac.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-gpio.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-i2c-slave.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-i2c.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-ledc.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-matrix.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-misc.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-psram.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-rgb-led.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-rmt.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-sigmadelta.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-spi.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-time.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-timer.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-tinyusb.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-touch.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-uart.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/firmware_msc_fat.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/libb64/cdecode.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/libb64/cencode.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/main.cpp.o
Compiling .pio/build/esp32dev/FrameworkArduino/stdlib_noniso.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/wiring_pulse.c.o
Compiling .pio/build/esp32dev/FrameworkArduino/wiring_shift.c.o
Archiving .pio/build/esp32dev/libFrameworkArduino.a
Indexing .pio/build/esp32dev/libFrameworkArduino.a
Linking .pio/build/esp32dev/firmware.elf
Retrieving maximum program size .pio/build/esp32dev/firmware.elf
Checking size .pio/build/esp32dev/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [=         ]   8.0% (used 26164 bytes from 327680 bytes)
Flash: [==        ]  24.6% (used 322233 bytes from 1310720 bytes)
Building .pio/build/esp32dev/firmware.bin
esptool.py v4.5
Creating esp32 image...
Merged 2 ELF sections
Successfully created esp32 image.
========================================================= [SUCCESS] Took 13.72 seconds =========================================================
 *  Terminal will be reused by tasks, press any key to close it.

 *  Executing task in folder esp32_OTA_from_scratch: platformio run --environment esp32dev

Processing esp32dev (platform: espressif32; board: esp32dev; framework: arduino)
-------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
PLATFORM: Espressif 32 (6.1.0) > Espressif ESP32 Dev Module
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES:
 - framework-arduinoespressif32 @ 3.20007.0 (2.0.7)
 - tool-esptoolpy @ 1.40500.0 (4.5.0)
 - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 34 compatible libraries
Scanning dependencies...
Dependency Graph
|-- ArduinoOTA @ 1.0.9
|-- ESPmDNS @ 2.0.0
|-- WiFi @ 2.0.0
Building in release mode
Compiling .pio/build/esp32dev/src/main.cpp.o
src/main.cpp: In lambda function:
src/main.cpp:39:22: error: 'class ArduinoOTAMdnsClass<WiFiServer, WiFiClient, WiFiUDP>' has no member named 'getCommand'
       if (ArduinoOTA.getCommand() == U_FLASH)
                      ^~~~~~~~~~
src/main.cpp:39:38: error: 'U_FLASH' was not declared in this scope
       if (ArduinoOTA.getCommand() == U_FLASH)
                                      ^~~~~~~
src/main.cpp: In function 'void setup()':
src/main.cpp:37:13: error: invalid use of 'void'
   ArduinoOTA
   ~~~~~~~~~~
     .onStart([]() {
     ~~~~~~~~^~~~~~~
       String type;
       ~~~~~~~~~~~~
       if (ArduinoOTA.getCommand() == U_FLASH)
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         type = "sketch";
         ~~~~~~~~~~~~~~~~
       else // U_SPIFFS
       ~~~~~~~~~~~~~~~~
         type = "filesystem";
         ~~~~~~~~~~~~~~~~~~~~

       // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       Serial.println("Start updating " + type);
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     })
     ~~
src/main.cpp:49:6: error: expected primary-expression before ')' token
     })
      ^
src/main.cpp:52:6: error: expected primary-expression before ')' token
     })
      ^
src/main.cpp:60:6: error: expected primary-expression before ')' token
     });
      ^
src/main.cpp:62:20: error: no matching function for call to 'ArduinoOTAMdnsClass<WiFiServer, WiFiClient, WiFiUDP>::begin()'
   ArduinoOTA.begin();
                    ^
In file included from src/main.cpp:5:
.pio/libdeps/esp32dev/ArduinoOTA/src/ArduinoOTA.h:91:8: note: candidate: 'void ArduinoOTAMdnsClass<NetServer, NetClient, NetUDP>::begin(IPAddress, const char*, const char*, OTAStorage&) [with NetServer = WiFiServer; NetClient = WiFiClient; NetUDP = WiFiUDP]'
   void begin(IPAddress localIP, const char* name, const char* password, OTAStorage& storage) {
        ^~~~~
.pio/libdeps/esp32dev/ArduinoOTA/src/ArduinoOTA.h:91:8: note:   candidate expects 4 arguments, 0 provided
*** [.pio/build/esp32dev/src/main.cpp.o] Error 1
========================================================== [FAILED] Took 2.69 seconds ==========================================================

 *  The terminal process "platformio 'run', '--environment', 'esp32dev'" terminated with exit code: 1.
 *  Terminal will be reused by tasks, press any key to close it.

What could be the problem?

All I can see are three issues (plus possible some bonus ones)

You can't daisy chain callback setters like that, it returns void and it doesn't make any sense to have  void.onProgress... and those callbacks doesn't seems to fit current library, so you should just drop them completely.
There is no begin() without parameters. See examples.
In the library I can see only callback setters: beforeApply, onError and onStart
You might be missing #include <Arduino.h> (it doesn't have any preprocessor like ArduinoIDE that adds this to the first line without you knowing it
You might be missing some defines (you can compare Arduino compile commands and Pio one)

Anyway you should take a look into the examples (at least begin is there). Callbacks looks like they are taken from who knows where (probably different library or so).
But they definitely must be complete like:
ArduinoOTA.onStart([](){ /* started */ });
ArduinoOTA.onBeforeApply([](){ /* before aply */ });

EDIT:
After some searching the ArduinoOTA library is directly in esp32 core (google: "arduinoOTA onProgress esp32"), so you don't have to add any lib_deps for ArduinoOTA. Or more likely you shouldn't add any, and the correct library will be used then. If not, you'll have to copy (or download) correct library into lib/ subdirectory.

Hi @KIIV - How can you explain the fact that the example is taken from ArduinoOTA library (when using Arduino IDE), compiles and works as it should ??

Might be different library (or version). Sometimes the cores has libraries with them. You can always find its location and copy that library to the lib subdirectory in your project (and remove that lib_deps ArduinoOTA reference) to use correct version

If you check the ArduinoOTA library in Github it states that this library has not been tested on platformIO
Also note that not all functions are the same, parameters are different when you call in ArduinoIDE and on PlatformIO


text:
Arduino Uno WiFi Rev2 is sending serial data to IDE, but not to C# program
I have an Arduino Uno WiFi Rev2 which I am trying to read data over the serial port from (using C#). The Arduino program periodically emits data to the serial port (for testing purposes). Whenever the Arduino writes to the serial, it also toggles the onboard LED to prove it is still running.
Everything seems to run fine. The LED periodically blinks and thus proves the loop runs as expected. Using the Serial Monitor on the Arduino IDE also correctly echoes the data that the Arduino emits.
Here is the program:
int keepAlive = 500;
unsigned long lastKeepAlive = 0;
char ledState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (millis() > lastKeepAlive + keepAlive) {
    lastKeepAlive = millis();
    Serial.println("Alive");
    if (ledState == 0) ledState = 1; else ledState = 0;
    digitalWrite(LED_BUILTIN, ledState);
  }
  delay(5);
}

Another reason why I know it works is because the TX LED on the Arduino blinks whenever it writes on the port.
However, once I close the IDE, the Arduino "stops" writing to the serial port. Maybe because it doesn't have to - there is no connection. Fine with me. Also: the TX-LED stops blinking while the onboard-LED keeps toggling on and off. So the loop still runs fine.
Now I'd like to read out the serial data via C#. For that I've written a simple program like so:
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
port.Write("123");
while (true)
{
  Console.WriteLine(port.BytesToRead);
  await Task.Delay(1000);
}

I expect this program to tell me how many bytes are waiting to be read. But it keeps printing 0 endlessly. Also: the TX-LED does not light up on the Arduino. On the other hand, note that little port.Write in the program - it's a test to verify the communication between the Arduino and C#. In fact: I can briefly see the RX-LED on the Arduino light up when my program sends the 123. I reckon the port and it's settings are correct then.
When I close my program, and the open up the IDE again, the Arduino starts to emit serial data again, the TX-LED starts blinking again and data arrives in the Serial Monitor.
All the while the onboard-LED keeps toggling on and off merrily.
What am I doing wrong? Why is the Arduino talking to the IDE but not to my program? Do I have to initiate some kind of handshake?

something wrong with the C# program ... that is off topic here

the arduino cannot choose which program receives data from the serial port on your computer ... find a C# tutorial about receiving data from the serial port

@jsotola Did you notice the statement "the TX-LED stops blinking while the onboard-LED keeps toggling on and off"? To me, the problem might not be the PC program. Since I don't have hardware available, I cannot reproduce, but it seems that some kind of hardware handshake is blocking.

I have solved the issue and @jsotola was correct in pointing out the problem lay with the C# program.
What mislead me was the fact that the TX and RX leds apparently only blink when data is read from the respective buffer, not when it is written to. In other words: the Arduino kept happily writing to the serial port (as expected) but the TX led did not light up because no one was reading what it wrote. I dind't know that.
For anyone else having this issue: I had to set DtrEnable to true. This is still a little confusing to me though. I am not new to programming in C# and with serial ports at all. Yet, I have never had to do this. Also, according to documentation this flag is used when using XOn/XOff or RTS handshake. None of which I am using.
I also tried with PuTTY. I did not configure anything aside from the port name and the baud rate and it worked right away. Investigating, I found that PuTTY apparently defaults to XOn/XOff.
So I'm guessing it really is XOn/XOff then ...
I updated my program like this:
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.DtrEnable = true;
port.Open();
...

source: Stack Exchange

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

sort: votes


text:
Are variables declared in main.cpp static, instance, or...?
Let's suppose you've just created a new Arduino project using PlatformIO, or an IDE like Sloeber. You now have a file named "main.cpp" with two functions (methods?):

void setup()
void loop()

Now, suppose you follow Arduino coding norms, and stick something at the top like:
hd44780_I2Cexp lcd(0x27);

Is the hd44780_I2Cexp object instantiated by it static? Or is main.cpp #include'd into some class in a way that makes everything in it private or public members of that class?
If they're instance methods, is it absolutely 100% guaranteed that the instance is, and forever shall be, a singleton? Or is there any conceivable scenario where there could be two simultaneous instances of it (say, if you were using both cores of an ESP32)?
If it's an instance, but guaranteed to forever be singleton on any future platform that calls itself "Arduino", is there any need to care about the distinction between "instance member" and "static variable" (in the context of main.cpp)?
Should main.cpp "really" have a separate main.h file, and "official" public: and private: blocks for the sake of C++ linguistic purity, or would I just be creating real or potential problems for the sake of intellectual exercise and ideology?

public and private are for classes.  main isn't a class nor is it in one.  It's just a function.  The lcd object you describe creating is at global scope.  It's not part of an instance of any class.  I think maybe you are confusing this with java.

The lcd variable you create is not static nor is it an instance variable.  It is an instance of the hd44780_I2Cexp class that is at global scope.  It's not a member of anything.  It's not an instance variable of anything.  It's not static.  It's just a global object.

If you examine the output when building in verbose mode you'll find mentioned an .ino.cpp file in a temp directory. This is the result of the build process, the documentation for which probably tells you everything you want to know, if not .ino.cpp file doesn't.

In the Arduino IDE, setup and loop are functions, not instances of anything.
There is a file included in the compilation sequence, main.cpp, which has the following code (slightly simplified here):
#include <Arduino.h>

int main(void)
{
    init();

    setup();

    for (;;) {
        loop();
    }

    return 0;
}

So you can see that this bit of "sugar" basically calls setup once and loop repeatedly.
The other function, init, initialises some hardware, like the timers, so that millis() and delay() work as documented.
I can't speak for other IDEs but I assume they do similar things, in order to be compatible.

Whatever you define outside of any function will be global, which is static - it lives for the duration of program execution - and visible to all compilation units that are bound into the eventual execution unit.
If you also include the 'static' declaration ahead of the type, the variable will be file-level static, meaning it will be visibile only within the current file.
This is standard C/C++ behavior for any data type - scalars; vectors, structs & arrays; and objects (C++ only, of course).

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


text:
Arduino cant send DHT11 data to Firebase
I have a problem with my project, the problem is that my Firebase can't detect my DHT11 temperature and humidity sensor from the Arduino.
The code runs without an error but the Firebase can't read my sensor.
Here is my code
#include <FirebaseArduino.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>

#define FIREBASE_HOST "*****-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "WE7YUKBpSMo07nUT8ZWYS*****"

#define WIFI_SSID "***"
#define WIFI_PASSWORD "****"

#define DHTPIN D5
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

bool light;
bool fan;

unsigned long previousMillis = 0;
const long interval = 10000;

void setup() {
  pinMode(D1, OUTPUT);
  Serial.begin(115200);
  delay(500);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.println("Connecting..");

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

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  dht.begin();

  delay(2000);

  if (Firebase.failed()) {
  Serial.print("Firebase connection failed: ");
  Serial.println(Firebase.error());
  return;
  }

}

void readDatas(){
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Serial.println(t);
  Serial.println(h);
  Firebase.setFloat("Data/Temperature:", t);
  Firebase.setFloat("Data/Humidity:", h);
}

void loop() {
  light = Firebase.getBool("LightStates/switch");
  Serial.println(light);
  if (light == true){
    digitalWrite(D6, HIGH);
  }
  if (light == false){
    digitalWrite(D6, LOW);
  }

  fan = Firebase.getBool("FanStates/switch");
  Serial.println(fan);
  if (fan == true){
    digitalWrite(D7, HIGH);
  }
  if (fan == false){
    digitalWrite(D7, LOW);
  }

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval){
    readDatas();
    previousMillis = currentMillis;
  }
}

Here is the screenshot of my Firebase for better understanding:

Temporarily, I am using dummy data for the temperature and humidity. Please if you guys know how to fix it, let me know. it will mean so much to me.

Which Arduino are you using.  Actually, better question, are you trying to run this sensor at 3 Volts?  I recall some say it runs better (more dependably) at 5 Volts.

What does your code output to Serial?

@st2000 i use it in 5 volts

@StarCat it says connected and print the temp&humidity

@jsotola yes its my bad, i have edited my question

Well, I wanted to install my temp/humidity sensor in a hard to reach location.  After some problems on the bench w/the DHT part, I bought a batch of Si7021 (not this board, but same chip) and left the DHT's in the parts bin.


text:
Fast wired communication protocols
I have an esp32 connected to an FPGA about 2 cm on a PCB. I am trying to send a constant data stream to the FPGA at a throughput of around 1.5 MB/s.
This is too fast for UART, I've been considering SPI but I don't really know how I can implement it in the FPGA.
Are there any other fast data communication protocols over wires available to me, or even a parallel protocol ?

An SPI receiver-only port is little more than a shift register.

@EdgarBonet I will give SPI a go then, sounds like the most obvious choice

I believe there are wider SPI bus implementations.  Like 2 data lines or maybe even more.  Maybe that will give you more through put.  But do you need full-duplex?  I2C is half-duplex and uses fewer pins. But timing is more critical.  There is also an audio serial bus protocol.  Maybe you should look into that one.

@st2000 thanks, I am only using a half duplex set up, I very briefly looked at I2S but it seemed a little too slow, I may well have overlooked something. I think SPI may be the one.


text:
How to optimize checking for specific string in a UART stream
I want to check for specific string (like "RecordStart") in a UART stream (115 200 baud 8N1) from a camera, to know when it is recording or not/if there is an SD. I am using an ESP32-WROOM-32UE with 16MB flash. I wired the Tx from the camera to one of the pin of the ESP. The ESP32 is programmed with VsCode (platformIO) through Arduino framework. I am using freeRTOS.
The thing is, "RecordStart" or "RecordStop" or other strings, appear just one time. Sometimes (when the camera is powering on), there are many many strings sended, very fast. So, from time to time, I lose some bytes and I can't find the strings I am looking for. I would like to optimize my code to never miss a string.
How the code works ?
If there is at least 1 byte in the serial buffer, the taskUART priority is set to 2 (while other tasks are priority 1. If a null character is detected, the message_UARTcam buffer starts to be filled. Then, each time a byte enters the buffer, I am checking if the buffer contains the strings I am looking for. It is working quite well but sometimes, I lose some bytes and the strings are not detected. I think It is because many other tasks are running and the serial buffer fills up faster than it empties. Increase temporarily the priority of the UART task improves the detection but I am still missing some bytes.
The code:
void taskUART(void *parameter)
{
  while (1)
  {
    if (SerialPortCam.available() > 0)
    {
      vTaskPrioritySet(nullptr, 2);
      char incomingChar = SerialPortCam.read();
      // Serial.write(incomingChar);

      if (flagNullChar == 1 || bufferIndex_UARTcam > 0 && bufferIndex_UARTcam < BUFFER_LEN_UART_CAM)
      {
        message_UARTcam += incomingChar;
        // Serial.println(message);

        if (message_UARTcam.indexOf(stringStart_app) != -1 || message_UARTcam.indexOf(stringStart_button) != -1)
        {
          // Serial.println("Start recording");
          SD_UARTcam = 1;
          record_UARTcam = 1;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringStop) != -1)
        {
          // Serial.println("Stop recording");
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdError) != -1)
        {
          // Serial.println("SD error");
          SD_UARTcam = 0;
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdInitOk) != -1)
        {
          // Serial.println("SD init OK");
          SD_UARTcam = 1;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdRemoved) != -1)
        {
          // Serial.println("SD removed");
          SD_UARTcam = 0;
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }

        bufferIndex_UARTcam++;
        flagNullChar = 0;
      }

      if (incomingChar == 0x00)
      {
        flagNullChar = 1;
        message_UARTcam = "";
        bufferIndex_UARTcam = 0;
      }
    }
    else
    {
      vTaskPrioritySet(nullptr, 1);
    }
  }
}

Camera output example:
␛[0;36m[00105849][CA9] ␀[App - Connected] <OnMessage> Received msg: 0xE001000C (param1 = 0x0 / param2 = 0x0)␛[0m
␛[0m[00105849][CA9] ␀RecCapState:0 RecCurrMode:0 RecNextMode:0 GFlags:0X7 Flags:0 StreamType:0␛[0m
␛[0m[00105849][CA9] ␀[App - Widget] <Off> widgetId: -1␛[0m
␛[0;33m[00105849][CA9] ␀[App_Glob_PWM_Buzzer] PWM Buzzer : 2␛[0m
␛[0m[00105849][CA9] ␀[App - ButtonOp] <MgrTask> Received msg: 0x0 (Param1 = 0x0 / Param2 = 0x0)␛[0m
␛[0m[00105849][CA9] ␀[App - ButtonOp] <MgrTask> Received msg: 0x1 (Param1 = 0x0 / Param2 = 0x0)␛[0m
␛[0m[00105899][CA9] ␀[rec_connected_cam_record_start] Start␛[0m
␛[0m[00105899][CA9] ␀[App - Connected] <RecordStart> REC_CONNECTED_CAM_RECORD_START␛[0m
␛[0m[00105899][CA9] ␀Dechi.motion_detec: 0␛[0m
␛[0m[00105899][CA9] ␀[Applib - ExtendEnc] <_ExtendEnc_SetEnableStatus> Enable flag: 0␛[0m
␛[0m[00105899][CA9] ␀[AppLib - MuxMp4] <SetTrickRecDivisor> Cur TrickRecDivisor: 1, New TrickRecDivisor: 1␛[0m
␛[0;34m[00105899][CA9] ␀[App - Sensor] <GetVinMode> Vin Mode = 11␛[0m

Here is an idea that may work: instead of buffering the input stream
and comparing the buffer with the search string, you could do the
comparison on the fly, as you receive the characters. Then you have no
buffering at all, and no time spent in scanning through the buffer.
Below is a function that searches for the "RecordStart" marker, while
being fed one character at a time. This function remembers how many
correct characters it has received so far (this is the static variable
pos), and updates this count on each received character. It returns
true when it has just detected the marker, and false otherwise:
bool marker_found(int c) {
    const char marker[] = "RecordStart";  // search string
    static int pos = 0;  // correct characters received so far
    if (c == -1) return false;  // shortcut for a common case
    if (c == marker[pos]) {
        pos++;                      // count a correct character
        if (marker[pos] == '\0') {  // we got the complete string
            pos = 0;                // reset for next time
            return true;            // report success
        }
    } else if (c == marker[0]) {
        pos = 1;        // we have the initial character again
    } else {
        pos = 0;        // we received a wrong character
    }
    return false;
}

You would use it like this:
if (marker_found(SerialPortCam.read())) {
    // handle the incoming record
}

Note that you do not need to test for SerialPortCam.available() > 0,
as this is already handled by marker_found().

I tried your code and it is working very well. I am going to test the performances when multiple tasks are running.


text:
How much readable text can fit inside an ATTINY85? Feasibility of scrolling a booklet on a 0.91-inch OLED display
I'm a total beginner, so I've been talking with Chatgpt regarding the capabilities of the Attiny85 microcontroller. But the AI would hallucinate a lot and give only partially right answers (because it relies on patterns and knowledge from its training data or something). So I came here to ask for some guidance and insights on the following questions:

How much readable text can the Attiny85 accommodate considering variables such as the programs, libraries, and fonts?
Is it possible to create a mini text reader using an Attiny85 and a 0.91-inch OLED display, where the text can be scrolled and read like a booklet?

I understand that the Attiny85 has 8kb of flash memory, but I'm unsure about the actual capacity for storing and displaying text, especially considering the potential impact of the compression of the code.
Any advice, experiences, or suggestions on how to optimize the usage of the Attiny85 and the OLED display for this purpose would be greatly appreciated.
Note: Feel free to correct any misconceptions or assumptions I may have made in my questions due to my limited knowledge in this field.

start with one of the menu programs that you can find on the internet ... add text to it until memory is full ... your first question is not really answerable ... the second one is yes

If you keep it at simple ASCII (not some multibyte format), one character is exactly one byte. How much of the 8kB is available besides your program depends on how you write the program. Nobody can tell you that, since you haven't written it yet. And when you have written it, you can test yourself by just compiling it (the Arduino IDE will tell you the programs size). Though driving an OLED display uses rather much spaces probably. And you probably will run out of pins. Is there a reason why you are trying this with such a small controller (in terms of resources, not physical size)?

Hmmm, i dont think i can tell you why i am trying to make this device as tiny as possible... Well, here is a hint: I never graduated from high school.

I will take a SWAG, the approach I would use would be to add external memory such as I2C FRAM. It is not expensive and will work just fine with the I2C bus. I use the 32K x 8 devices. You could connect 8 of them. FRAM can be acquired in SPI as well. I have assumed you are using the I2C for the display so no additional pins on the processor will be needed.

How does the text get onto the FRAM?

By writing it there, this can be done in passes as FRAM is non volatile. I wrote a specific program to do this.  I use a Mega to program mine as it has a lot of flash that I just transfer to the FRAM. I have also done it with UNOs and Nanos, they work just fine. Initially I used a Nano and many #ifdef statements. Then each time I would select different tables and program them into FLASH. The table addresses were predefined for the FRAM. Once the FRAM was loaded I then worked on my program with more FLASH and RAM available depending on where the messages were.

The AtTiny85 has 8KB of program memory, which you could store strings in. The more data you store, the less room you have for program code and vice-versa.
For only slightly more money you could use an Atmega328P which has 32KB of program memory, giving you somewhat more scope for storing data.
For some kind of text reader you might want to consider an external disk (like, a micro-SD card) which can be easily attached with a modest amount of extra hardware. The hardware might be a couple of voltage-level converters, if you are going to run the processor at 5V rather than 3.3V.
The code to interface to the SD card might be too large to fit into 8KB of memory (I'm not sure about that) but certainly would fit into 32KB.
You also need the code to interface with the OLED — I'm not sure how much program space that would take up.
You might do it with the AtTiny85, with no external disk, but you would probably only get a couple of K of text, once you had your code and your OLED interface. You could compress the text, but then you need code to decompress it, which might outweigh the advantage of compressing it.
For some sort of "booklet" I think the external disk is the most practical solution. This is what one looks like, with its voltage-level converter, hooked up to my Uno:


text:
MHZ19B Sensor - Library not found- Please Help!
I can't seem to figure out what the problem is here. I am trying to upload this code to Arduino Uno but it keeps telling me that the library is not found. I did download the library for the MHZ sensors but it doesn't like it.
I am somewhat new to Arduino.
Please help!
This is the code:
// Libraries
#include <DHT.h>
#include <SD.h>
#include <SoftwareSerial.h>
#include <MHZ19B.h>

// Constants
const int chipSelect = 10;   // SD card chip select pin
#define DHTPIN 7             // DHT sensor pin
#define DHTTYPE DHT22        // DHT sensor type
#define MHZ19B_TX_PIN 8      // MHZ19B sensor TX pin
#define MHZ19B_RX_PIN 9      // MHZ19B sensor RX pin

// Variables
DHT dht(DHTPIN, DHTTYPE);
File dataFile;

MHZ19B mhz19b;
float hum;      // Humidity value
float temp;     // Temperature value
int lightVal;   // Light sensor value
int co2;        // CO2 concentration

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

  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");

  Serial.print("Initializing MHZ19B sensor...");
  mhz19b.begin(MHZ19B_TX_PIN, MHZ19B_RX_PIN);
  Serial.println("MHZ19B sensor initialized.");
}

void loop()
{
  lightVal = analogRead(A1);
  Serial.print("Light Value: ");
  Serial.println(lightVal);
  delay(50);

  hum = dht.readHumidity();
  temp = dht.readTemperature();
  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  delay(5);

  co2 = mhz19b.getCO2();
  Serial.print("CO2 Concentration: ");
  Serial.print(co2);
  Serial.println(" ppm");

  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (dataFile) {
    dataFile.println("Light Value: ");
    dataFile.println(lightVal);
    delay(50);

    hum = dht.readHumidity();
    temp = dht.readTemperature();
    dataFile.print("Humidity: ");
    dataFile.println(hum);
    dataFile.print(" %, Temp: ");
    dataFile.println(temp);
    dataFile.println(" Celsius");

    co2 = mhz19b.getCO2();
    dataFile.print("CO2 Concentration: ");
    dataFile.print(co2);
    dataFile.println(" ppm");

    delay(5000);
    dataFile.close();
  }
  else {
    Serial.println("Error opening datalog.txt");
  }

  delay(1000);
}

look at the example code in the library

That's because it should be either #include <MHZ.h> for the MH-Z CO2 Sensors library or #include <MHZCO2.h> for the MHZCO2 one.
How do you typically include the libraries you download? Thru the library manager? The way you can do it in Arduino IDE 2.0 is going  thru Sketch -> Include Library -> the library you want to include -- that should include the correct header.

Yes. The library manager. Thank you for your help. I will try this.

@Maria you're welcome! As jsotola mentions above, take a look at the example in the library (if you're going to use the MH-Z CO2 Sensors one) - the way the sensor is initialized is a bit different than how you've done it in the sketch you've provided.

Ok. I will take a look. I am not fluent with Arduino code but I will check and see if I can modify and make it work.


text:
Can I program ATTINY using Arduino as ISP whilst having other I2C devices connected?
I have an SMD ATTINY that I'm using for a project. Attached to it are 3 I2C devices. When programming it using an Arduino as an ISP, can I have those devices attached? Ie, do I have to program the ATTINY and then solder it on my board or can I solder it and the program (and re-program if necessary).

why don't you just try it? ..  you said that the I2C devices are already connected

@jsotola - Maybe because he'd rather not risk damaging something in case someone else already knows?

Welcome to SE/Arduino! Please [edit] your question and add the schematic, so we can see how you connect the I²C devices, together with the ISP connector.

Yes, the slave devices shouldn't respond unless addressed. When programming, data will obviously be on the lines however the probability of this data accidentally containing the right sequence to correctly query a slave is minimal.

Did you consider that devices are allowed to stretch any low clock pulse?


text:
Initialize ATMEGA32U4 with arduino bootloader with AVR Dragon?
I built my own atmega32u4 board. I wish to use it as "arduino" so I need to upload first the arduino bootloader.
Now, to do that I need another arduino but I don't have it currently.
However I have an AVR Dragon, which was the way to program these chips years back. So: how the heck can I burn the arduino bootloader to the mega32u4 with avr dragon?
Note: I can use AVR Dragon, and it can see the mega. Just I have NO clue on where this ** arduino stores it's bootloader hex file.

You mean like this?

The common simple action to find a file is to use your file manager and ask it to search. You asked your file manager to search "*.hex" in your Arduino installation path, didn't you? Why do the findings not help you?

There is not a single "hex" file in Arduino IDE's folder, hence my question..

Of course not, because there are so many different Arduinos, each one needs its specific bootloader. So you might have to look at the filename. I see "Leonardo-..." as a good hint. ;-) A research on the specific Arduino that uses an ATmega32u4 with the same clock can be expected. -- And if there is still more than one left, then you could ask with the list of candidates. Or visit the project repository to learn more.

You don't need another Arduino if you have a programmer, but there is some problem with the AVR Dargon programmer and avrdude so the Arduino boards package and the MiniCore boards package don't have it configured.
With a supported programmer you can burn the bootloader with Arduino IDE. In Tools menu you select the board most similar to your custom board, then you select in Tools menu the programmer and then you select "Burn bootloader".

See https://github.com/arduino/ArduinoCore-avr/tree/master/bootloaders/caterina
The file you probably want would be Leonardo-prod-firmware-2012-12-10.hex in that folder.
Those files will be in your Arduino installation, in a folder called "bootloaders".

I have an "Arduino IDE" folder in Program Files (Win11). Nothing is related to "bootloader" in that folder. Where am I supposed to find it?

@Daniel IDE 2.x doesn't have it, but he didn't mention anything about ide, neither did I. We both sent url with all bootloaders for 32u4

@Daniel I mentioned the "Arduino installation" - I looked in IDE 1.8.5 on Ubuntu. I can't say where it would be, if anywhere, on your hard disk for Windows 11. However the link I gave is to that folder on Github. You can click on the appropriate link in Github to open the file (it is just text), then RH-click "Raw" and then download it.

Evidently it is a file from 2012, but it doesn't matter. Either the bootloader works or it doesn't, and this one does. ;)


text:
Is it possible to use flash encryption in esp32 in Arduino ide
Just already finished writing the program in arduino ide, but were just thinking if i could use flash encryption in esp32 using arduino ide for commercial use? Cause i am still new to this esp-idf stuffs and wondering if i could set some security config using arduino ide.


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:
problem conversion value
I have two functions that return an int16_t but I need to convert the ints to
char* is for an attiny13
It would be something like this
const char* msg = "value1()"+','+"value2()"+','+"value3()"

like example
#include "TinyRF_TX.h"

void setup(){
  // transmitter default pin is pin #2. You can change it by editing Settings.h
  setupTransmitter();
}

void loop(){

  const char* msg = "Hello from far away!";

  //send function accepts an array of bytes as first argument
  //second argument is the length of the array
  send((byte*)msg, strlen(msg));

  //make sure there's at least a TX_DELAY_MICROS delay between transmissions
  //otherwise the receiver's behavior will be undefined
  delayMicroseconds(TX_DELAY_MICROS);

What are you going to do with this string? If you are going to send it somewhere with Something.print() or Something.write(), you probably don't need to build it in the first place.

thanks for your answer, you will see I need to send that string using tinyRF from what I see it only allows sending strings type pchar*

You will need to build the string yourself. Probably the easiest way is using the sprintf() function which will take a bunch of arguments and convert them to a string based on formatting instructions you give it.
An apropos article here...
https://www.programmingelectronics.com/sprintf-arduino/

"for an attiny13" Code with nothing but avrlibc snprintf()ing of an int to a buffer takes about 1.5k of the available 1k of flash space on an attiny13. This is without involving the Arduino core or serial or anything else. This might work for an attiny85, or 45, or even 25 with not a lot of room to spare. But for an attiny13 you're going to need to do something tighter.


text:
Functions delaying gesture sensor recognition
I am working on a simple little robot to cure my boredom and all it has is a 64 x 32 OLED for the eyes, and a PAJ7620 Gesture recognition sensor with a Seeeduino Xiao as the main board.
Basically, when people swipe above the head where the sensor is, the robot will show the heart eyes. There are different reactions for different actions and all this is controlled through functions. When the sensor does not detect anything, the robot is supposed to cycle through a certain void which is determined based on how much it 'likes' the person.
Right now though, it just cycles through the function and does not respond to the sensor. My code is very inefficient because of all the functions, but it makes it more readable and more easily editable. With all my functions, the gesture sensor takes too long to respond to the actions.
What can I do to fix this? Can someone please help or give advice on how I can improve my code?
    #include <Arduino.h>
    #include <U8g2lib.h>
    #include <Wire.h>
    #include <DFRobot_PAJ7620U2.h>

    int like_score = 3;//Score for how much the bot likes you: this will impact which voids are used.
    int max_like_score = 17;
    char buffer[9];

    unsigned long previousMillis = 0;
    const long interval = 1000;

    DFRobot_PAJ7620U2 paj;

    U8G2_SSD1306_64X32_1F_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

    // fonts https://github.com/olikraus/u8g2/wiki/fntlistall#4-pixel-height
    void setup(void) {
      u8g2.begin();
      Serial.begin(115200);
      delay(300);
      u8g2.clearBuffer();
      Serial.println("Gesture recognition system base on PAJ7620U2");
      while (paj.begin() != 0) {
        Serial.println("initial PAJ7620U2 failure! Please check if all the connections are fine, or if the wire sequence is correct?");
        delay(500);
      }
      Serial.println("PAJ7620U2 init completed, start to test the gesture recognition function");
      paj.setGestureHighRate(true);
    }

    void normalL() {       //normal forward expression
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, normal);
      u8g2.sendBuffer();
    }
    void blinkL() {        //blinks
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, blink);
      u8g2.sendBuffer();
    }
    void left() {          //looks left
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, blinkleft);
      u8g2.sendBuffer();
    }
    void right() {         //looks right
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, blinkright);
      u8g2.sendBuffer();
    }
    void angryL() {        //angry
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, angry);
      u8g2.sendBuffer();
    }
    void loveL() {         //in love
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, love);
      u8g2.sendBuffer();
    }
    void sleepL() {        //sleeping
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, sleep);
      u8g2.sendBuffer();
    }
    void susL() {          //suspicious
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, sus);
      u8g2.sendBuffer();
    }
    void stunL() {         //looks stunned
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, stun);
      u8g2.sendBuffer();
    }
    void upL() {           //Looks up
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, up);
      u8g2.sendBuffer();
    }
    void gleeL() {
      u8g2.clearBuffer();  // clear the internal memory
      u8g2.drawBitmap(0, 0, 8, 32, glee);
      u8g2.sendBuffer();
    }
    void randomEx() {
      int rand = random(1, 8);
      if (rand == 1) {
        normalL();
      } else if (rand == 2) {
        left();
      } else if (rand == 3) {
        right();
      } else if (rand == 4) {
        angryL();
      } else if (rand == 5) {
        loveL();
      } else if (rand == 6) {
        susL();
      } else if (rand == 7) {
        upL();
      } else if (rand == 8) {
        gleeL();
      }
    }

    void likeRoutine() {
      normalL();
      delay(random(1000, 6500));
      blinkL();
      delay(90);
      normalL();
      delay(random(1000, 4500));
      randomEx();
      delay(random(1000, 4500));
      blinkL();
      delay(90);
      loveL();
      delay(random(2500, 4000));
      blinkL();
      delay(90);
    }
    void kindofLikeRoutine() {
      normalL();
      delay(random(1000, 7000));
      blinkL();
      delay(90);
      normalL();
      delay(random(1000, 4500));
      randomEx();
      delay(random(1000, 4500));
      blinkL();
      delay(90);
      loveL();
      delay(random(1000, 3000));
      blinkL();
      delay(90);
    }
    void dislikeRoutine() {
      normalL();
      delay(random(1000, 7000));
      blinkL();
      delay(90);
      normalL();
      delay(random(1000, 6500));
      randomEx();
      delay(random(1000, 4000));
      blinkL();
      delay(90);
      angryL();
      delay(random(1000, 3000));
      blinkL();
      delay(90);
    }
    void hateRoutine() {
      angryL();
      delay(random(1000, 5000));
      blinkL();
      delay(90);
      normalL();
      delay(random(1000, 6500));
      randomEx();
      delay(random(1000, 4000));
      blinkL();
      delay(90);
      angryL();
      delay(random(1000, 3000));
      blinkL();
      delay(90);
    }

    void loop(void) {
      DFRobot_PAJ7620U2::eGesture_t gesture = paj.getGesture();
      if (gesture != paj.eGestureNone) {
        String description = paj.gestureDescription(gesture);  //Convert gesture number into     string description
        if (gesture == 256) {                                  //wave
          gleeL();
          delay(random(1000, 4500));
        } else if (gesture == 2 && like_score < max_like_score) {  //pet
          blinkL();
          delay(90);
          loveL();
          like_score++;
          Serial.println(like_score);
          delay(random(1000, 3000));
          if (like_score == max_like_score) {
            blinkL();
            delay(90);
            loveL();
            delay(random(1000, 3000));
          }
        } else if (gesture == 16 && like_score <= max_like_score) {  //thump
          stunL();
          like_score--;
          Serial.println(like_score);
          delay(random(1000, 4000));
          angryL();
          delay(random(1000, 3000));
        } else if (gesture == 128) {
          u8g2.clearBuffer();
          u8g2.setFont(u8g2_font_t0_11_tf);  // choose a suitable font
          dtostrf(like_score, 6, 0, buffer);
          String scoreStr = String(buffer);
          u8g2.drawStr(0, 20, scoreStr.c_str());
          u8g2.sendBuffer();
          delay(random(2000, 3500));
        }
      } else {
        if (like_score >= 11) {
          likeRoutine();
        } else if (like_score > 7 && like_score < 11) {
          kindofLikeRoutine();
        } else if (like_score > 0 && like_score < 7) {
          dislikeRoutine();
        } else if (like_score < 0) {
          hateRoutine();
        }
      }
    }

Yes, thank you.

Thank you, I will do that.

@jsotola That looked very much like an answer to the question, not a request for clarifying information. Could you please turn it into an answer? Hint: cut and paste should work. Thanks!

My code is very inefficient because of all the functions ... - not at all. Using functions to make code readable is very common, and the slowdown is minimal.

@jsotola I'm just asking that your reasonable comment about using delay() be incorporated into an answer and not a comment. However if you wish provide more code, but that wasn't what I was requesting.

The code is being slowed down by the delay() function because it is a blocking function.
The delay function does not exit until delay time passes, so no other functions can run, such as sensor reading.
The simplest solution for your code may be an FSM library (finite state machine).  It would look after all of the timing for you.
You could also replace the delay() functions with your own delay function, something like

void myDelay(int totalDelay) {

   for (i = 0; i < totalDelay/100; i++) {

                           // do some housekeeping here, like reading sensors

      delay(100);          // this blocks for only 1/10 of a second
   }                       // adjust the delay value if housekeeping takes a lot of time
}

The delay gets broken into a lot of small delays with time to do other things in between.
Another way is to check at the begining of loop() to see how much time has elapsed.
See blinkWithoutDelay example code in the Arduino IDE.
Here is an example in a simulator that may help you.
https://wokwi.com/projects/362275278547275777

Thank you! This definitely helps a lot!


text:
Digispark: check if the USB host is connected
I am trying to detect if the digispark device is actually connected to a host (i.e. the USB line is "active") vs. just powered.
The issue: if I send a keypress while the data line is disconnected, the code hangs perpetually in sendKeyPress.
My theory is that it keeps looping in while waiting for USB to be ready, which makes sense.
    while (!usbInterruptIsReady()) {
      // Note: We wait until we can send keyPress
      //       so we know the previous keyPress was
      //       sent.
        usbPoll();
        _delay_ms(5);
    }

I tried to use the macro usbInterruptIsReady() before calling sendKeyStroke in the main, but with no success. I would expect to see a function that keeps track of this state, but apparently there is none.
Also: it doesn't seem like what I am trying to accomplish being extremely weird, so my expectation is that someone else could have stumbled upon this and figured out a reasonable workaround.
I would like to avoid setting up a watchdog timer.
Code below for example hangs when the device is powered but not connected to a PC.
Thanks
Background: https://hackaday.io/project/191762-automatic-workstation-locker
#include "DigiKeyboard.h"
#include "Arduino.h"

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  DigiKeyboard.update();

  DigiKeyboard.sendKeyStroke(0);
}

void loop() {
  static uint8_t bit = 0;
  bit = 1 - bit;
  digitalWrite(LED_BUILTIN, bit);
  DigiKeyboard.update();
  DigiKeyboard.sendKeyStroke(KEY_Q);
  delay(2000);
}

I've deleted all the comments which had descended into sledging. Please remember, comments under the question are for clarifying it, not attacking each other.

If you wish to complain about the way this site is working please raise an issue on our Meta site.

The question looks reasonable to me, however @Paperino you should not keep re-posting the same question. Try to salvage the original one where possible. As it is now deleted I suggest we run with this one.

The Digispark does not have a proper hardware USB implementation. It is possible that you simply can't do what you are attempting to do. A search I did indicated you are not the only person attempting to do this.
You may want to switch to one of the Arduinos that have a hardware USB interface like the Leonardo or Micro.
I should point out that the Digispark is not an Arduino, and it has its own forum where you may possibly get an answer from their own community.


text:
DEVKIT V1 DOIT 30 pinout board could not read analog value when using wifi library
I am using DEVKIT V1 DOIT board and 30 pinout board.
When I upload this code for checking analog value from serial monitor:
    // Define the analog input pin for the IR sensor
const int analogPin = 13;

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

void loop() {
  // Read the analog value from the IR sensor
  int sensorValue = analogRead(analogPin);

  // Display the analog value in the Serial Monitor
  Serial.print("Analog Value: ");
  Serial.println(sensorValue);

  // Add a short delay to avoid rapid readings
  delay(500);
}

it came just normally fine.
But when I upload this code:
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "JANINA";
const char* password = "sayma01720";
const char* websiteURL = "http://192.168.1.105:4747/araf/phploginscript-master/sense_value.php?uid=56"; // Replace with your website URL

const int analogPin = 19;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

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

void loop() {
  int sensorValue = analogRead(analogPin);
  Serial.print("Analog Value: ");
  Serial.println(sensorValue);

  // Prepare the temperature to be sent
  String temperature = "temperature=" + String(sensorValue);

  WiFiClient client;
  HTTPClient http;

  bool success = http.begin(client, websiteURL);
if (!success) {
  Serial.println("Could not connect to the server");
  return;
}

  // Set content type to application/x-www-form-urlencoded
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpResponseCode = http.POST(temperature);

  if (httpResponseCode > 0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    String response = http.getString();
    Serial.println(response);
  } else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }

  http.end();

  // Wait for some time before sending the next temperature
  delay(2000);
}

It stop read analog value.
This was the result shown in serial monitor,

Analog Value: 0 HTTP Response code: 200

Please help me SIR.

why are you using a different pin than the first example? ... is pin 19 an analog input pin?

No.... I was tried many pins 4, 22, 23, 19, etc. but I can not find the solution.


text:
COM disconnects and program fails when including code trying to initialize SD card (RP2040 Pi Pico W running Arduino)
I'm having an issue where anytime I run a program such as the SD card read write example (Below) the COM port disconnects. The only changes I have made to the example code is I am using SPI1 instead of SPI0 so the pins changed.
When the COM disconnects it comes back about 20 seconds later with an error message in its properties window
"Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed."
Additionally I am suspicious of these lines through isolating them, if I remove all lines relating to SPI the code doesn't fail and I don't have the COM issue. (though the SD card obviously doesn't work)
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);

Thanks!
-Rian
/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
   ** MISO - pin 4
   ** MOSI - pin 7
   ** CS   - pin 5
   ** SCK  - pin 6

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

// This are GP pins for SPI0 on the Raspberry Pi Pico board, and connect
// to different *board* level pinouts.  Check the PCB while wiring.
// Only certain pins can be used by the SPI hardware, so if you change
// these be sure they are legal or the program will crash.
// See: https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf
const int _MISO = 16;
const int _MOSI = 15;
const int _CS = 17;
const int _SCK = 14;

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  Serial.print("Initializing SD card...");

  // Ensure the SPI pinout the SD card is connected to is configured properly
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);

  if (!SD.begin(_CS)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

There is a Raspberry Pi part of Stack Exchange, they may be able to help you better.


text:
RX and TX pins on esp32
hello guys i'm new to this field i really need your help i want to wire a GSM module (SIM808) to a ESP32 board using the TX and RX pins so the pins are labeled RX and TX no pin number like the others how can i declare them in the code.
i already tested the code on an arduino uno on pins 0 and 1 (RX and TX) and it works fine here is the board i'm using :
i already tried using pins 16 and 17 but didn't work i need to try using pins number 40 and 41 according to image below

"Didn't work" is not very descriptive. Please show your code and how you have connected the module. It may be good to known that the ESP32 has a very flexible serial port configuration and serial I/O can be mapped to most of the GPIO pins.

Tx and Rx is used by Serial port for your Serial Monitor. Unlike Arduino Uno, which only has one Serial port, ESP32 has 3. You can use the TxD2 (GPIO17) and RxD2(GPIO16) for connecting to your SIM808 module. You uses the port with Serial2.begin(115200).

First off, thank you for all the guidance and support you've provided. As a beginner in the world of Arduino and embedded systems, it's been tremendously helpful.
The main issue I was facing had to do with not knowing how to declare the TX and RX pins in my C++ code, especially when these pins weren't labelled with their GPIO numbers like the others on my ESP32 board. After a bit of research and reading through your comments, I learned that these pins can simply be declared using their GPIO numbers, which are indicated on the schematic of the board.
For instance, to utilize RX0 and TX0, they need to be declared as 3 and 1 respectively. Here's an example:
 #define RXD 3  //RXD
    #define TXD 1  //TXD

    HardwareSerial SIM808(2);

void setup()
{
  //
  //
   SIM808.begin(9600, SERIAL_8N1, RXD, TXD);
}

I was able to get the SIM808 module working with this method, but I'm noticing that the system isn't always consistent. Sometimes it takes a long time to execute commands, which is something I will have to look into.
I just wanted to express my gratitude for the warm welcome and helpful guidance I've received here. This being my first post, I was worried about asking a "dumb question," but the community has been nothing but supportive.
As I continue to learn and explore more about embedded systems, I'm sure I'll be back with more questions, and hopefully, in time, some answers of my own to contribute!

this is a very bad advice. You want to use SoftwareSerial on hardware Serial pins? and this hardware Serial is already wired to the USB chip which communicates with the computer. You can use Serial2 on RX2/TX2 pins. Serail2 already exists as an object and is initialized for the pins. (as already mentioned in the comment below the Q)

Don't use SoftwareSerial on a device that has enough hardware serial ports to do the job.

can you provide more information about SoftwareSerial and HardwareSerial to help me better understand and also i'm running out of pins in my project is there any solution to reduce the number of pins or use the same pins for multiple purposes?

Hach Rbh, https://en.wikipedia.org/wiki/Bit_banging


text:
How to use multiple PN532 over i2c bus(es) and SPI?
I am working on a project that involves 3 PN532_modules to an ESP32, which sends the Tag_ID over BLE.
Plan A was to use One module on i2c_1, second on I2C_2 and third over SPI.
The SPI one works as expected.
Though I am having issues with using 2 I2c Buses using the same Adafruit Library. Exact issues are-

Unreliable reading while using 2 different i2c buses
Sometimes the SPI bus freezes after scanning a Tag on one of i2c connected readers.
My code is here

#include <Arduino.h>

#include <Wire.h>
//#include <Adafruit_PN532_2.h>
#include <Adafruit_PN532.h>

#define SDA_1 (21)
#define SCL_1 (22)
#define SDA_2   (33)
#define SCL_2   (32)

Adafruit_PN531 nfc1(SDA_1, SCL_1);
Adafruit_PN532 nfc2(SDA_2, SCL_2);

void setup(void) {
  Serial.begin(115200);
  while (!Serial) delay(10);
Serial.println("Serial ready");

  nfc1.begin();
  nfc2.begin();

  uint32_t versiondata_1 = nfc1.getFirmwareVersion();
  if (! versiondata_1) {
    while (1); // halt
  }
Serial.println(versiondata_1);

  uint32_t versiondata_2 = nfc2.getFirmwareVersion();
  if (! versiondata_2) {
    while (1); // halt
  }
Serial.println(versiondata_2);
}

void loop(void) {

  uint8_t success_1;
  uint8_t uid_1[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength_1;                        // Length of the UID (4 or 7 bytes

  uint8_t success_2;
  uint8_t uid_2[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength_2;                        // Length of the UID (4 or 7 bytes

  success_1 = nfc1.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid_1, &uidLength_1);
  delay(10);

  success_2 = nfc2.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid_2, &uidLength_2);
  delay(10);

  if (success_1)
  {
    Serial.println(success_1);
    Serial.print(" UID_1 Value: ");
    nfc1.PrintHex(uid_1, uidLength_1);
    Serial.println("");
  }
  delay(10);

  if (success_2)
  {
    Serial.print(" UID_2 Value: ");
    nfc2.PrintHex(uid_2, uidLength_2);
    Serial.println("");
  }
  delay(10);

}

Why not simply use SPI for all 3 instances of this chip ? You need the 3 basic shared SPI bus pins  SCK, MISO and MOSI. Each chip needs additionally one dedicated CS (Chip Select) pin. See https://learn.adafruit.com/adafruit-pn532-rfid-nfc/breakout-wiring (where this pin is called SSEL) and anyway you have said already that SPI works for you.

Both I2C and SPI is a bus architecture, meaning that multiple devices can share the same bus without needing separate wiring for each device as long as they have different address (in case of I2C) or have separate chip select (in case of SPI). All three can share the same I2C bus or SPI bus. Read I2C and SPI for more details.

@hcheung Thanks for answering, For I have discovered, they have FIxed i2c Address, so having them all on the same Bus isn't possible.  Also having 2 Different buses also doesn't quite solves the problem. As the problem is the Library having only one class for all 3 Interfaces(SPI, i2c and HSU).

Regards

As mentioned by 6v6gt, you could use the SPI with 3 wires sharing among all three devices for MOSI, MISO and SCK, with another 3 GPIO pins configured as CS for each of the board. Class is a footprint (library), you don't use the Class directly, you create an instance of the Class for each board.


text:
Salvaging Arduino board from Google ADK 2012
I found an old Google ADK 2012 in my closet and remembered it came with a Arduino board (?), an ARM 32-bit Cortex M3 micro-processor available at the time (possibly the DUE).
The ADK 2012 design files and source code were included as part of a software download at the event which is no longer available on the Android site, but I found a mirror here:
https://stuff.mit.edu/afs/sipb/project/android/docs/tools/adk/adk2.html
You can also see the kit in action from the Google I/O 2012 event where these kits were given out:
https://youtu.be/ZUaKSs3utrs
Here's my issue(s):

When I try to set up and run the ADK 2012 IDE, I get an error stating "ADK2012.app" needs to be updated and disabled overlay on the icon.

When I try to use the ADK Alternative Build System, I get an error stating ld: symbol(s) not found for architecture i386, which makes sense because Apple removed the ability to compile 32 bit programs on macOS starting with Xcode 10 (my Xcode: 13.4.1; macOS: 12.6.7)

After connecting the board to my computer via USB to micro-USB, when I open the Arduino IDE, I'm able to select the port, but there is no option for this particular board, although from everything I've gathered, its essentially a custom version of the Arduino DUE made just for that event, and others have managed to load the ADK 2012 onto a regular DUE. So I've been trying it with both Arduino DUE boards (native and programmable)

When I try to "Get Board Info" in Arduino IDE, the board name is "Unknown board", but all the other information is available (VID, PID, SN).

After importing the ADK2 library into Arduino IDE and updating the demo code from the source download, I'm able to get the project sketch file to compile and verify without errors, however when I attempt to upload the changes to the board, I receive the following error: No device found on cu.usbserial-AH015U12 Failed uploading: uploading error: exit status 1. The device appears connected to my computer the whole time, including before and after the error.

I think I've exhausted all of my known options and just want to know whether & how it's possible to salvage a 10+ year old (modded but virtual identical) Arduino board.
TLDR; want to tinker with old Arduino board, custom IDE no longer works, Arduino IDE disconnects when attempting upload. Still salvageable or too old?