text:
Odd behavior of defines - is this Arduino specific and how does it work?
A question I have long had regards an interaction between #define statements and a library header include. I've seen several Arduino libraries use this rather convenient configuration system where you can write a #define statement, then include the #include header instruction and the library will change its behavior.
Does anyone know why this does or does not work? My understanding of how #include works is that it copies the file into its place in the new file and that C/C++ code with headers should thus form something of a tree shape. It would thus make sense that any lines of code present before I #include a library would have to be seen by the library when the preprocessor does its thing and copies the #include-d file.
But I've previously been told it doesn't actually work this way (despite actual examples, but by that point I had misplaced the libraries that did it). However, I've finally tracked down an example of someone doing this, and I'd like to know how this behavior works. Is it a feature of Arduino in specific or something?
Here's a library that does it: https://github.com/madpilot/mDNSResolver

From my reading of the source code for that library I can't see that it can work as described. The library code (cpp files) are different translation units to the sketch where the #define would be located.

Can you explain translation units? I've heard of them, but they seem very nebulous to me.

When you compile a .c or .cpp file it gathers all the header files contents together and literally does string replacement on the #includes and then the #defines. Then compiles that one big resultant file. That's a translation unit. In general for every cpp or c file you have one translation unit. It's a self contained thing which can't be modified by anything outside. The only exception is in Arduino if you have multiple .ino files in a sketch they get concatenated together into one gigantic translation unit.

If I were doing what you describe I'd be using a class with a constructor whose code is in the header file and thus gets recompiled for each translation unit (i.e. within the sketch for example). That constructor would be called with macros you can override from the sketch since the constructor forms part of the same TU as the sketch.

the missing define is not missing from your sketch, it's missing from the lib's cpp file, which is it's own thing. one neat trick i've used is to put all the lib code in an H file instead of the cpp file. The result is basically that that H-file code just pasted in-place in the sketch, which means prior defines are available to it. I don't know  if there's downsides to it, but it works as I expect...

The mDNSResolver library README has

You can change a few settings by defining some constants before including the mDNSResolver header file [in the sketch]

I added "in the sketch", because it is where you include mDNSResolver header file.
This will not work because mDNSResolver.cpp, which uses the values of the defines, is compiled without any knowledge of the ino file content.
A deeper explanation would be too long and out of scope for Arduino SE.

In the first few lines of the library .h file you linked, it tests a symbol it has not defined, ESP32 (#if defined(ESP32)) and alters the compilation according to the definedness of that symbol.
Since the compiler input will be one long file with all the #include files already "spliced" inline, you (or a previously included .h file) have the option to pre-define that variable to alter the compilation as this library writer provided.
Update:
@RDragonflydr: I believe you are correct, that the ESP32 symbol is defined by the compiler (or more likely, the makefile) for the target processor. And to clarify my statement that "the compiler input will be one long file", I'm referring to the compilation of each module of your project, not to the entire project at once. Each library will each be compiled, separately, and each of your modules will be compiled separately, and in each of those cases, the compiler input will consist of the module code with all of the #included files "spliced" into place, the #defined symbols and macros substituted, and comments stripped out.
The library code (the .cpp) is not #included so it does not become part of the translation unit. Only the library header file is included. That is common - and necessary - to all environments, and one of the functions of the C or C++ preprocessor. This happens for each module - separately - in a multi-module compilation. The library files will have been

With a good background in C and C++ since many years, I'm quite stunned. Are you saying that the Arduino build process concatenates all sources of a sketch into one big translation unit? Boy, I wasn't aware of this! Is this also true for default Arduino libraries, or just added libraries?

I'm not quite sure what you're trying to say here. AFAIK the ESP32 define is set by the Arduino core and/or compiler to inform the code what it's running on. That one doesn't have anything to do with the "setting" defines I was asking about.

I know that Arduino's build process concatenates all the files - is that what allows the "settings" defines to work? I'm not sure if there's a way to get this working in other environments than the Arduino IDE specifically. If this works at all, is it only in Arduino and it's fragile if you use a different IDE to code for Arduino?

@thebusybee, only the ino files in the sketch are concatenated to one cpp file, not the C, C++, S files (of course)


text:
Inconsistent behavior of include statements?
This question deals with fonts. Well, actually, singular include files with constants that form bitmap fonts or images for LCD or OLED displays, such as this one: https://github.com/ThingPulse/esp8266-oled-ssd1306/blob/master/src/OLEDDisplayFonts.h. A strangely hard to research (but common) problem occurs when anyone attempts to include one of these font files in multiple files in an application.
Even with an include-guard present, reuse of this .h file will cause strange linker errors about redefinition of a variable. It turns out that any variable actually declared in a .h file will cause it to be created multiple times in the program, and then when the different files depending on the font.h file are linked, the variables collide. An example of it would be here: https://stackoverflow.com/a/4936294/11381501, or in my very own question some time ago here: How to create large progmem arrays and not annoy the linker
The issue is, I've seen some libraries that avoid this error (such as https://github.com/ThingPulse/esp8266-oled-ssd1306/blob/master/src/OLEDDisplay.h#L64) despite having variables declared in .h files. I've even included this OLEDDisplay.h file (indirectly via the main library file for my screen) in multiple of my own .h files in one project and it hasn't caused linker errors. What causes this globally-scoped variable in a .h file to not produce linker errors when my own code usually does?

Include guards only protect against multiple inclusion within the same translation unit. Variables declared in headers like that should be static but really should be just declared in the header as extern and defined in their own separate TU.

This is how I do fonts in my display library: https://github.com/CariadDisplayLibrary/WhiteRabbit/tree/master/src

@Majenko, there is an alternative to static vs extern declaration (with definition elsewhere) in C++17 onwards, where inline may be applied to variables following a one-definition-rule scarcely different (if different at all) from inline specified functions.

@timemage There are far far too many "alternatives" in C++ nowadays. It's become a horrible tangled mess of "features"...

@Majenko Well, it's a solution that involves the insertion of a single keyword. I thought that would have been something helpful to know.

The esp8266-oled-ssd1306 has it wrong, but with examples of the library it is saved by optimization. Other files where the font gets included don't use it so it is optimized away. Otherwise it would be duplicated.
OLEDDisplayFonts.h is included in OLEDDisplay.h which is included in OLEDDisplay.cpp and in SSD1306Wire.h which is included in the sketch. This creates two instances of the variables defined in OLEDDisplayFonts.h. But the instance in OLEDDisplay.cpp is optimized away, because that file doesn't use fonts. So for the linker there is only one instance of the variable.
relevant part from .map file for the SSD1306UiDemo.ino example
 .irom.text.OLEDDisplayFonts.h.857.11
                0x000000004023b7fd     0x25ab ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.434.10
                0x000000004023dda8     0x13b9 ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x000000004023f161      0xaab ./SSD1306UiDemo.ino.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x000000004023fc0c      0xaab ./libraries/esp8266-oled-ssd1306/src/OLEDDisplay.cpp.o
 .irom.text.OLEDDisplayFonts.h.10.9
                0x00000000402406c7      0xaab ./libraries/esp8266-oled-ssd1306/src/OLEDDisplayUi.cpp.o

The right way is to put variables in a cpp or c file and if they should be visible from other file, then use extern keyword in that file (usually over an included .h file) to declare that the variable exists.

source: Stack Exchange

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

sort: votes


text:
Type S Automotive underglow LEDS not responding to program in FastLEDS library
hey y'all first post here so my apologies if I'm a bit of a NEWB, I'm currently trying to control a set of individually addressable 3-pin led strips I got from the  type S formula drift LED kit model number LM532654-1. Ive used FastLEDS for a few projects now but this one is stumping me. I may have the wrong type maybe or there could be a special line of code I need to enter to talk to the chip-sets. Any help would be greatly appreciated. Also thank you all so much here on the forum, its saved my tail on so many occasions.

//#include <WS2812Serial.h>
//#define USE_WS2812SERIAL
#define FASTLED_INTERNAL
#include <FastLED.h>
#include <FastLED_NeoPixel.h>
FASTLED_USING_NAMESPACE

#define DATA_PIN1           2
#define DATA_PIN2           3

#define COLOR_ORDER         GRB
//#define LED_TYPE            WS2812SERIAL
#define LED_TYPE            SM16703
#define NUM_LEDS_1 50
int i=NULL;

CRGB leds_1[NUM_LEDS_1];
FastLED_NeoPixel_Variant strip(leds_1, NUM_LEDS_1);

void setup(){
  //pinMode(DATA_PIN1,OUTPUT);
  Serial.begin(9600);
  FastLED.addLeds<LED_TYPE,DATA_PIN1,COLOR_ORDER>(leds_1, NUM_LEDS_1)
        .setCorrection( TypicalLEDStrip );
        FastLED.addLeds<LED_TYPE,DATA_PIN2,COLOR_ORDER>(leds_1, NUM_LEDS_1)
        .setCorrection( TypicalLEDStrip );

}

void loop(){

  strip.begin(FastLED.addLeds<LED_TYPE, DATA_PIN1, GRB>(leds_1, NUM_LEDS_1));

  for(i=0; i<NUM_LEDS_1; i++){
    leds_1[i] = CRGB :: Green;
    FastLED.show();
    }

    for(i=0; i<NUM_LEDS_1; i++){
    leds_1[i] = CRGB :: Green;
    FastLED.show();
    }

No code as image please. Copy and paste the code as text into the question and format it correctly as code. Also please provide the link to that product page

probably not individually addressable

https://typesauto.com/products/type-s-formula-drift-pro-series-smart-led-exterior-lighting-kit-lm532654

Added the code in the description and posted the link above.

Ive gotten other Type S LEDS to function as Individually Addressable so as far as im aware these should function the same. But I am willing to test them out if you know of a way.

Now please format the code correctly. For that edit your question, select the code in the editor and them click the {} bitton.

How do you know that the LED-TYPE is correct? How do you even know, that the FastLED library can control them? The product page that you linked doesn't say anything about the used driver chips

I think that did it, I don't know the LED type, that's one of the things that I'm trying to figure out. The page I listed is unfortunately the only thing I have to go on. WS2812B worked for previous strips but ive mostly been shotgunning the different types that FastLEDS can support. Im currently searching the IC Chip smd5050 16703 amacrw1

https://viaisled.en.made-in-china.com/product/mjKxXShvlBVz/China-SMD5050-Addressable-Digital-16703-LED-Strip.html
the search leads me to some cheap chinese LEDS that run the same chip and those give some odd LED types Ws2811/Ucs1903/Sm16703

until you determine the exact model of the LEDs, this question is unrelated to the Arduino

Very well, Appreciate the help.

if i zoom in on the image of the strip showing the chip, it looks like it says xws28xx. Since you have the strip in-hand, search for the chip ids and that will tell you what led type you can feed fastled.

16703 amacrw1 is the chip ID, but it really doesnt bring up much on google. The link is above to some cheap LEDS that run the same chip.

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


text:
Arduino shield stacking issue
I'm having issues stacking shields on my Arduino Mega 2560. I would like to add to the mega a ethernet shield (https://store.arduino.cc/products/arduino-ethernet-shield-2) and on top of that the dragino lora shield v1.4 (https://wiki.dragino.com/index.php?title=Lora_Shield). When I connect only the dragino lora shield to the mega I do get the lora to initialize but the moment I add the ethernet shield to the mega and the dragino lora shield to the ethernet shield the lora initialization fails. Is this stacking possible and if so any advice on how to get all to work together?
Thanks in advance.

idk about those 2 particularly, but in general, lots of shields are incompatible with other shields because they want to use up the same pins (gpios). Look that up in datasheet or sketch/libs.

Both those boards use pin 10 for chip select by default. You will need to change that.
Probably the simplest one to change is the LoRa board. If you look at the WiKi page you link to it lists a set of resistors and jumpers which can be altered to modify the connectivity of the board.  By default R9 is populated which connects to pin 10. If you move that to the R10 position next to it you will instead be connecting to D5 for the chip select pin. Moving surface mount resistors can be tricky though so you may want to practice working on a scrap board first.
And of course when you have changed the chip select pin you will also have to change your code to use that new chip select pin instead.

Thank you for your answer. I wanted to give it a try but found that my LoRa board is more like the v1.2 instead of the v1.4. It's hard to see since it's not written anywhere on the board. Can you maybe see a way around this problem on the v1.2 LoRa board?

@Ayayron They have obviously identified that this is a commonish problem and fixed it in the later version. You can remove R1 which will isolate pin 10, but they have no easy facility for connecting chip-select to somewhere else. You will have to solder a fine wire on the board between the pad of R1 furthest from the header to where you want it. Or (as long as this shield is the top of the stack) cut pin 10 off from the header and jumper between that pin's socket and the pin you want to use. Or if the pins are flexible enough bend it out of the way so it doesn't insert into the ethernet shield


text:
Weird SoftwareSerial behaviour with Arduino nano when multiple SoftwareSerial objects are configured
So I have been stuck with this for quite some days now and am really unable to put my finger on what's wrong here. Any help would be great. Try not to list down the disadvantages of SoftwareSerial, I know about them. Is this issue happening cause of it?
What I am trying to achieve? Two Arduino (Nanos) are connected to each other and are trying to communicate with each other via SoftwareSerial UART (multiple Arduinos are connected to multiple Arduinos but for the sake of keeping the code minimalistic, assume one-to-one communication).
Code for Arduino 1:
#include <SoftwareSerial.h>

String val = "4";

SoftwareSerial a(6, 7); // rx, tx
SoftwareSerial b(8, 9); // rx, tx
SoftwareSerial c(10, 11); // rx, tx
SoftwareSerial d(12, 13); // rx, tx

String a_s, b_s, c_s, d_s;

void setup() {
  a.begin(9600);
  b.begin(9600);
  c.begin(9600);
  d.begin(9600);
  Serial.begin(9600);
  a_s = "";
  b_s = "";
  c_s = "";
  d_s = "";
}

void loop() {
  delay(100);

  d.print(val);

  if(d_s == "") {
    if(d_s == "" && d.available()) {
      char rd = d.read();
      Serial.print("ddddddddddd ");
      Serial.println(rd);
      d_s = rd;
    }
  }
}

Code for Arduino 2:
#include <SoftwareSerial.h>

String val = "5";

SoftwareSerial a(6, 7); // rx, tx
SoftwareSerial b(8, 9); // rx, tx
SoftwareSerial c(10, 11); // rx, tx
SoftwareSerial d(12, 13); // rx, tx

String a_s, b_s, c_s, d_s;

void setup() {
  a.begin(9600);
  b.begin(9600);
  c.begin(9600);
  d.begin(9600);
  Serial.begin(9600);
  a_s = "";
  b_s = "";
  c_s = "";
  d_s = "";
}

void loop() {
  delay(100);

  b.print(val);

  if(b_s == "") {
    if(b.available()) {
      char rd = b.read();
      Serial.print("bbbbbbbbbbbb ");
      Serial.println(rd);
      b_s = rd;
    }
  }
}

Actual and Expected output for Arduino 1:
ddddddddddd 5
Actual output for Arduino 2: (no output!!)

Expected output for Arduino 2:
bbbbbbbbbbbb 4
While debugging, I realized if I comment out c.begin(9600) and d.begin(9600) from the code for Arduino 2, the actual output is the same as the expected output.
//   c.begin(9600);
//   d.begin(9600);

Ohh and yes, the connections are as follows:

ard1
ard2

GND
GND

D12
D9

D13
D8

Both the Arduinos are connected (and hence powered) via individual cables to the same laptop.
Is there something I am missing out on? I know SotfwareSerial has its downsides but is this something SoftwareSerial is causing? If yes, why is the actual output of Arduino 1 is same as the expected output? Shouldn't it have the same effect on both the Arduinos?
TIA!

Is one of the downsides of SoftwareSerial that you know about the fact that only one SoftwareSerial can be set to receive data at a time?
You have to select one and only one instance to receive data using the .listen() method.
If you want to be able to receive from multiple devices at once you will have to use either hardware UARTs or a single SoftwareSerial and a "bus" infrastructure (RS485 or similar).


text:
Integer division
I want to divide two integers and get how often one of them fits into the other completely, so there will always be an integer as an output. In python you do this kind of operation with //.

So... just pure integer division (doing division without the rest behind the decimal point)? Thats just the division operator / with integers. For example 13/4 will get you 3 (because both operants are integers, so the part behind the decimal point is ignored). Is that what you mean?

cast both numerator and denominator to integers of appropriate type and use division: (int)num/(int)den produces an int result (2-byte signed in arduino).   you may want to use stdint.h (aka cstdint) types like int16_t which make the types clear regardless of compiler (int is 4-byte signed in some places)
you may find that casting at math operations is useful in other scenarios too.  for example, sometimes you want to handle integer rollover (255+1 will roll to 0 if they are 1-byte unsigned).

In C++, the integer division operator is /, and the floating point
division is also /. The compiler chooses according to the types of the
operands:

if either or both operands are floating points numbers, you get a
floating point division

if both operands are of some integer type, you get an integer
division.

Thus:

5.0/2.0, 5.0/2, 5/2.0 all have the same value, namely 2.5

5/2 is 2.


text:
On an esp8266 what is faster, 64-bit math or float math?
I need to do some math with vars from an attitude sensor (acclerometers and gyroscopes) on an esp8266. int32_t math with those vars does not have enough range and the float math operations are abyssmally slow.
I'm hoping to use a fixed-point format with 24 bits on the left of the decimal point and 8 bits on the right side.  So a number would be stored in a int32_t as 0xffffff.ff.  A typical operation would be a multiply like ((i64) x * y) >> 24).
So 64-bit math is needed. Would this be significantly slower than a float multiply?

do 10,000 operations of each ... time the results

By the way, if I was downvoted because the answer seemed obvious then they should read the rest of this thread.

If you need fast single-precision float operations, consider the ESP32 instead of the ESP8266.  It clocks in at 240MHz instead of 160MHz, has two cores, and has hardware single-precision FPU.  Especially if you want to use the WiFi or anything else that depends on interrupts you can do your DSP on the second core and not have to worry about your calculations getting sidelined by whatever else is going on in your main loop.

Yes, I've used the esp32 before with this attitude chip.  I just made every var a float and it breezed along.  But this is for a cheap toy and the extra $2 for the esp32 is too much.

Calculating the relative performance of 64 bit integer versus floating point multiplication is a little more difficult than it would appear.
It's easy to time a loop that does thousands of calculations, but unless you do something with the result the compiler will happily optimize them away. It's tempting to multiply constants, but the compiler will also happily optimize that away.
To keep the code as simple as possible and not introduce anything into the loop that would take more time, you need to disable or bypass the compiler's optimizations. An easy way to do that is to use the volatile modifier on the variables. volatile tells the compiler that it can't assume the variable hasn't changed, so the compiler will disable optimizations like caching the variable in a register or noticing that the same calculation is being done over and over again and just doing it once.
Using this technique, with a couple of tests to verify that the compiler would perform optimizations that interfere with timing, I get these results:
non-volatile uint32_t microseconds 1
constants uint32_t microseconds 5
uint16_t microseconds 162513
uint32_t microseconds 137513
uint64_t microseconds 1287533
int16_t microseconds 337513
int32_t microseconds 300023
int64_t microseconds 1287513
float  microseconds 912529

64 bit unsigned or signed multiplication takes about 1.4x the time as floating point multiplication.
The first test verified that non-volatile variables are optimized out. The second test verified that multiplying constants is also optimized out.
Turning off Wifi also helps keep test results consistent.
#include <Arduino.h>

#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif

#define TIMES_TO_LOOP 1000000

volatile uint16_t ux16, uy16, uresult16;
volatile uint32_t ux32, uy32, uresult32;
volatile uint64_t ux64, uy64, uresult64;

volatile int16_t x16, y16, result16;
volatile int32_t x32, y32, result32;
volatile int64_t x64, y64, result64;

volatile float xf, yf, resultf;

uint32_t x32n, y32n, result32n;

uint16_t seed16() {
  return random(0, 0xffff);
}

uint32_t seed32() {
  return random(0, 0xffffffff);
}

uint64_t seed64() {
  return seed32();
}

float seedfloat() {
  float x, y;

  x = seed32();
  y = seed32();

  return x / y;
}

void setup() {
  uint32_t i;
  uint64_t micros_start, micros_end;

  Serial.begin(115200);
  Serial.println("hello world");

  WiFi.mode( WIFI_OFF );

  delay(1000);

  x32n = seed32();
  y32n = seed32();

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32n = x32n * y32n;
  micros_end = micros();

  Serial.print("non-volatile uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32n = 540000 * 15;
  micros_end = micros();

  Serial.print("constants uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux16 = seed16();
  uy16 = seed16();
  x16 = ux16;
  y16 = uy16;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult16 = ux16 * uy16;
  micros_end = micros();

  Serial.print("uint16_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux32 = seed32();
  uy32 = seed32();
  x32 = ux32;
  y32 = uy32;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult32 = ux32 * uy32;
  micros_end = micros();

  Serial.print("uint32_t microseconds ");
  Serial.println(micros_end - micros_start);

  ux64 = seed64();
  uy64 = seed64();
  x64 = ux64;
  y64 = uy64;

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    uresult64 = ux64 * uy64;
  micros_end = micros();

  Serial.print("uint64_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result16 = x16 * y16;
  micros_end = micros();

  Serial.print("int16_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result32 = x32 * y32;
  micros_end = micros();

  Serial.print("int32_t microseconds ");
  Serial.println(micros_end - micros_start);

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    result64 = x64 * y64;
  micros_end = micros();

  Serial.print("int64_t microseconds ");
  Serial.println(micros_end - micros_start);

  xf = seedfloat();
  yf = seedfloat();

  micros_start = micros();
  for(i = 0; i < TIMES_TO_LOOP; i++)
    resultf = xf * yf;
  micros_end = micros();

  Serial.print("float  microseconds ");
  Serial.println(micros_end - micros_start);
}

void loop() {
}

I ran your code and the results matched mine. Float is faster than 64-bit.
int64_t microseconds 650010
float microseconds 456266

Do note that 64 x 64 -> 64 bit multiply is typically 4x slower than the 32 x 32 -> 64 bit multiply that was in the original question.

I don't doubt this, but it is kind of surprising. For example: why is int16_t so slow compared to uint16_t? Multiplication is the same operation for those two types. Similarly for int32_t and uint32_t. Really bizarre. Is it possible that volatile is a bit too pessimistic in the sense that it also prevents strength reduction optimizations, whereas in a real app those would be available?

@jpa -- If you look closely you will see the muliplication is 64x64-bit, not 32x32.

@mark-hahn Then you have a different way of implementing fixed point math than I'm used to. C compilers are smart enough to know that if you have a 32-bit variable and cast it to 64 bits just before multiplication, the upper bits are zero and don't need to be handled.

OK, I took the trouble to code fixed-point routines and test them.  Here is the code ...

// fixed-point routines for 20 bit integer / 12-bit fraction
// format 0xfffff.fff, max value is +-524288.9998

#define FP_I 20     // integer bits,  e.g. 0xfffff.0
#define FP_F 12     // fraction bits, e.g. 0x0.fff
#define fpMul(_x,_y) ( (i32)( ((i64) _x * _y) >> FP_F) )
#define fpDiv(_x,_y) ( (i32)(  (((i64) _x) <<   32)      \
                             / (((i64) _y) >> FP_I) ) )
#define decToFp(_dec) ((i32) (_dec * 4096))   // e.g. decToFp(-1.2)
#define fpToI32(_fp)  ((i32) (_fp  / 4096))

I did a 1000 loops and used the loop counter as the operation argument.  So each loop was one operation plus one floating-point increment.  I did this for fixed-point multiply, floating-point multiply, fixed-point divide, and floating-point divide.
The results were shocking.  The fixed-point multiply took almost exactly the same time as the floating-point. The fixed-point divide took 60% longer than the floating-point.  I went over my code and tried everything I could think of.  I built it in debug and release mode.  I tried 80MHz and 160MHz.  I found floating-point speeds on the web and my floating-point tests closely matched those.
I am at a loss as to how the 64-bit math could be slower than the floating-point.  Both are implemented in software.  I'm sure the floating-point is highly optimized with some tricks and coded in machine language.  But my fixed-point code is just shifts and 64-bit multiply/divides.  I don't think there are any tricks that could be used for it.
At least this makes the decision easy. I guess I'll use floating-point as sparingly as possible and cross my fingers that I can get my app to work fast enough.
I hope this is helpful to some passing-by googlers.  I couldn't find anything when I googled it.

I didn't turn off wifi but I did use all the other recommendations you have here. I have played with this all day and it was hard to get right but I'm pretty confident in the results. Especially since my float results matched the results on the web from several other people who did a lot of work on this stuff. If anyone wants to insert my fixed-point code into their speed tests then let me know if your findings match mine. I've already burned up more time than I should have on this.

Hey, this is not a forum where we play ping pong with answers. When you write an answer it should contain a solution to the problem stated in the question. No back and forth please. Just questions and self contained answers. If you think you solved your own problem you should merge all your answers. If not, then you can add the additional info to your question. And please make sure that others can still understamd your question/answer, so they too can learn from it

And, welcome to Arduino Stack Exchange! Thanks for the update.

I don't understand.  Every forum I've used before was all ping-pong.  Where should we be having this discussion?

Have you considered implementing 32-bit multiplication as multiplications of 2-digit base 2^16 numbers? Something like this. It may be faster than converting both 32-bit numbers to 64-bit numbers before multiplying. Signed multiplication is also possible with two extra conditionals, if that's really important (I think it's not?).

...and if multiplying two 30-bit numbers to get a 60-bit number is enough for your application, you can drop the 4 cheap multiplies from my previous link to just 3 using the Karatsuba multiplication algorithm.

@mark-hahn: SE isn't a forum, it's a Q&A site. You'll note that the interface is structured differently, and the social conventions differ too. The site tour highlights some of the differences, as does our help center page on how to write a good answer. Anyway, for issues that do need some back-and-forth discussion, the appropriate place for that is either here in the comments or (especially if the discussion gets very long or drifts off topic) in chat.

BTW, your fpDiv implementation looks a bit wonky to me: e.g. fpDiv(decToFp(10), decToFp(2)) gives a division by zero error. Normally you'd want to do the right shift after the division, I think. (Also, I don't know if that's the case on the esp8266, but at least for some platforms / compilers / optimization settings, setting FP_F to a multiple of the/a "native" word size like 8, 16 or 32 bits might yield somewhat faster code. It could at least be worth a try.)


text:
Turn on a relay for a specified amount of time after the press of a momentary switch
This is my first time programming an Arduino. I have a small brushed DC motor that I want to control using a 5V relay, which in turn is connected and controlled by the Arduino.
What I would like to do is this: Command the relay to turn ON for a specified amount of time, after pressing a momentary push button, then turn OFF once the specified amount of time has passed.
Once that's done, I would like it to reset itself, so to speak, so if I press the push button again it does the same thing.
My current script is:
const int relay = 8; //motor relay
const int button = 9; //momentary trigger switch

int status = true;

void setup() {
  // put your setup code here, to run once:
  pinMode(8,OUTPUT);
  pinMode(9, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(button) == true) {
    status = !status;
    digitalWrite(relay, status);
  } while (digitalRead(button) == true);
  delay(500);
}

What it currently does is: if I push the push button once, it will command the relay ON until I press the button again, which then turns the relay OFF until further input.
I know that I should use the millis() function for the timer functionality, but for the life of me I haven't been able to figure out how to make it work thus far.
Any suggestions?

I suggest to ask the IDE to auto-format your code (Ctrl-T). Maybe you could see that what you wrote doesn't match your intention.

Yes I adapted some code I found online in order to test if everything was setup correctly hardware wise. I now want to add the functionality I described in my original post but I can't figure out how. I have tried to adapt code from similar use cases to mine but I just can't get them to work properly, if at all.

your code is if button is pressed then change the state of the relay, and if the button continues to be pressed, then wait .5 sec .... you want if button is pressed then turn on relay, wait .5 sec, turn off relay

Okay, so the code probably needs to be scrapped. I know that I must do the following:

De bounce the button
Use millis() preferably to time the relay, so it can be turned off after a specific amount of time

However, I have been unable to figure out how.

there is no need to debounce because the first contact closure results in a 500 ms delay ... the contact bounce will never get detected ... just change the few lines of code inside the if block

I have been unable to figure out how ... it is literally spelled out in english ... if button is pressed then turn on relay, wait .5 sec, turn off relay ... you already have all the necessary command lines ... just rearrange them


text:
64 led strips and 8 shift registers (connected to 64 sensors) connected to 5V and ground of arduino
I have connected 64 led strips and 8 shift registers (connected to 64 sensors) to 5V and ground of arduino. Voltage received at led strip is 3.1V and at registers is 3.2V. I plan to add an led display as well a small buzzer to it. Can I connect it to the same 5V? What should I make sure in this in terms of voltage supply so that there is no less supply as well loss of power? What if I add a 9V battery instead?
Note: I am just a beginner in this topic.

How big are the LED strips? You do know you can't draw more than 500-800mA from the 5V pin, don't you?

I guess you are currently powering all this through a USB port on your PC. You are lucky if you haven't fried anything on the Arduino. When the 5V pin goes down to 3.1V this means that either you have fried the power electronics or you are currently totally stressing the power supply out. Power supplies, which are overloaded often drop the voltage significantly, or just fail outright.
All the LEDs, shift registers and sensors draw current. With this much LED strips you can easily get into the territory of many amps of current needed for driving them (depending on the number of LEDs and the current draw of each LED). A PC USB port will only provide 500mA by default. An Arduino can handle a current output from the 5V pin of about 1A, including the current, that the Arduino itself needs. So lets say 800mA. When you provide power through the barrel jack this also depends on the voltage of your power supply. The linear voltage regulator dissipates the voltage difference to 5V as heat, so supplying a higher voltage means more heat, means it can handle less current.
What to do now:

You need to power your LED strips, shift registers and sensors directly from your power supply. The current for them should not go through the Arduino. If you use a power supply with a higher voltage than 5V, you need to buy a voltage regulator for 5V that is capable of providing the total needed current (+ at least 20% headroom to be safe and reduce heat). Go for a switching "buck" converter type, not for a linear converter. They are way more efficient and provide less heat. There are ready-to-use modules available on the typical sides (for example the one named like the biggest river). Often they have a small potentiometer on them, which you can spin with a small screwdriver to set the wanted output voltage (here 5V).
Make sure, that the used power source is actually capable of providing the total needed current. For this you first need to calculate how much current the project will draw. For example: Standard addressable LED strips with WS2812 will draw 60mA per LED when on full brightness white. Multiply with the number of LEDs to get the total current for them. GO through all components of your project and write down the current draw (look at the datasheet for such info). Add it all up. Then get a power source (and if needed voltage regulator) that can handle at least 20% more than that.

What if I add a 9V battery instead?

As written above you will need an external voltage regulator for your project. Also: If you mean the standard 9V block batteries, then just forget it. They are not meant for high power applications and can only provide very low current. You should look in the direction of LiIon or LiPo batteries. When you use them please also buy a fitting charger module (since these are rather particular about how they want to be charged).
But before choosing a battery you first need to know how much current your project draws. Then you need to set a time range how long the project should run on the battery without charging. Then you can choose a battery based on that.

Then as per your suggestions, total current supply or Icc of each component used in this project adds to 4436mA. Should I multiply it with 4 to be able to run the circuit for 4 hours?

Yes, then you have the needed battery capacity in mAh. Also adda bit headroom on top

By headroom on top, do you mean some extra mAh of battery for better life? 5V needs to be supplied to the circuit which buck converter will do the job. Is output current of battery a factor too or just voltage and mAh are required to decide a battery for this project.

Yes, I mean some extra mAh. You need a buck converter which can take the batteries voltage, can convert it to 5V and can provide the needed current. Thats enough info to find a fitting one. You can even use multiple of them if you don't find one which this current rating. Make sure its current rating is higher than needed (you don't want to drive it at its limit the whole time).

About battery current: you need to transmit power, meaning voltage multiplied by current. With lets say 5A at 5V you have 25W to transmit. When the battery is higher voltage than it need to provide less current. For example: if the battery is 10V, then for 25W you only need 25W/10V=2.5A. The battery needs to be able to provide at least that amount of current without dipping the voltage too much.


text:
Using Analog Pins for Power
I'd like to power something needing 5V DC using the Arduino Uno analog pins. Specifically, I'm following the "Fun Plug-in Hack for Arduino UNO" section of this Adafruit tutorial. It states:

"If you set analog pin A3 to an OUTPUT and HIGH and A2 to an OUTPUT
and LOW you can power the RTC directly from the pins!"

It doesn't seem to work, so I try this with a multimeter hooked up to A2 & A3:
void setup() {
  pinMode(A2, OUTPUT);
  pinMode(A3, OUTPUT);
  analogWrite(A2, LOW);
  analogWrite(A3, HIGH);
}

void loop() {}

I only measure ~0.8V, trying 2 boards including a brand-new unboxed one. This is the same whether the board is powered via USB or via 9V battery in the barrel jack.
But I can measure ~5V from those pins if I set the "ground" pin as INPUT_PULLUP (using the built-in pull-up resistor) instead of OUTPUT:
void setup() {
  pinMode(A2, INPUT_PULLUP);
  pinMode(A3, OUTPUT);
  analogWrite(A3, HIGH);
}

void loop() {}

I don't believe Adafruit is wrong, since conceptually it makes more sense to set both pins to OUTPUT, with one being HIGH and the other being LOW. So what am I doing wrong?

What were you trying to power?

@Majenko DS1307 RTC

The analog pins are only analog inputs but digital outputs (and inputs too). You use digitalWrite() to control a pin's HIGH or LOW state.
ànalogWrite() is for use with the PWM pins (I hate the name the chose for that function it's so wrong on so many levels).
Also this powering trick only works for things that need very small currents (< about 20mA) since that is the maximum an IO pin can deliver.

Incidentally, you can use analogWrite() on a non-PWM pin, but it's either fully on (analog value >= 127) or fully off (analog value < 127). The macros HIGH and LOW are 1 and 0 respectively, so that equates to "fully off" and "fully off" on a plain non-PWM pin.


text:
Playing a sound file with Arduino Uno Wifi
I have an Arduino Uno Wifi (Rev2) and I want to play a sound file. I found two libraries so far but neither of them work. The TMRpcm library (https://www.arduino.cc/reference/en/libraries/tmrpcm/) only works on the base Arduino Uno and anther library called AudioZero (https://www.arduino.cc/reference/en/libraries/audiozero/) does not seem to be compatible with Arduino Uno Wifi.
Is there any other library that I could use to play a sound file. I have an SD card attached and a library that can read in a .wav file but no library to actually output the sounds on a basic speaker.
I need to use the Arduino Uno Wifi for what I am trying to achieve since communicating with the internet is crucial.
Using a base Uno with a wifi attachment did not prove to be promising since the attachment acted as it's own board and need to be flashed.

The Uno a) doesn't have analog outputs and b) only a tiny RAM. You better look for a more suitable microcontroller or at least a hardware extension to do the job of buffering and playing the output signal.

Hi @SimSon thank you for your reply. Do you have any recommendations? I have only used the Arduino Uno so far and I am not very familiar with other microcontrollers.

I have no experience with playing audio files on microcontrollers, but I'd personally start with a controller that has a reasonably large RAM (e.g. ESP32) and an external DAC.

If the controller is compatible with the Arduino environment, there shouldn't be much difference from how you would program the Uno

No sounds library seems to exist that is compatible with the architecture of the Arduino Uno Wifi specifically. Other micro-controllers need to be looked into.


text:
Can't get Adafruit MusicMaker and Ethernet to work at the same time
Working on an IoT project.
Environment:

Adafruit Feather M4 Express
Adafruit MusicMaker FeatherWing (amplified, this is a VS1053 at heart)
Silicognition PoE FeatherWing (electrically compatible with the Adafruit Ethernet FeatherWing)
PlatformIO with Visual Studio Code on a Mac (all libraries are up-to-date)

The Problem:
I can get either the Ethernet to work or the MusicMaker to work, but not both at the same time.
There are no errors during initialization, they just don't work.
Specifically, the MusicMaker's sineTest() method doesn't generate any sound if Ethernet has been initialized. Likewise, the Ethernet client's connect() method is unable to connect if the MusicMaker is initialized. Both methods work fine if the other device hasn't been initialized.
Feather Pins:
Purpose                    Pin
-------------------------- ---
VS1053 Chip select           6
VS1053 Data/command select  10
VS1053 Data request          9
SD Card Chip select          5
Ethernet Chip select        14

Note that I'm not currently using the SD card and haven't called its begin() method.
Note also that the Ethernet chip select is on a non-standard pin because the default conflicts with the VS1053 data/command select.
Also, the PoE FeatherWing has an EEPROM on it with a unique MAC address and reading this works fine.
One other note: I thought that I had this combination working in an earlier prototype a few months ago, but that may have been with the Feather 32U4.
TIA.
The prototype code:
#include <Arduino.h>
#include <Adafruit_VS1053.h>
#include <Ethernet.h>
#include <IPAddress.h>
#include <SPI.h>
#include <Wire.h>

//
// Pins for the Ethernet and MusicMaker FeatherWings.
// NOTE: These definitions assume a Feather M4 Express with a PoE FeatherWing
//       modified to have its chip select on pin 14 because the default conflicts
//       with the MusicMaker's DCS pin.
//
#define VS1053_CS       6     // VS1053 chip select pin (output)
#define VS1053_DCS     10     // VS1053 Data/command select pin (output)
#define SD_CARD_CS      5     // Card chip select pin
#define VS1053_DREQ     9     // VS1053 Data request, ideally an Interrupt pin
#define ETHERNET_CS    14     // Ethernet chip select pin. Note that this is custom because the default conflicts with VS1053_DCS.

//
// PoE FeatherWing.
//
#define MAC_EEPROM_I2C_ADDRESS      0x50  // I2C address of the 24AA02E48 EEPROM chip that contains our MAC address (on the PoE FeatherWing).
#define MAC_EEPROM_REGISTER         0xFA  // Register within the 24AA02E48 that contains the first byte of our MAC address.

#define HANG      while( true ){ delay( 10 ); }
IPAddress         host = { 172, 24, 110, 1 };
uint16_t          port = 8000;
const char*       path = "/sounds/DingDong.mp3";
Adafruit_VS1053   player{ Adafruit_VS1053( -1, VS1053_CS, VS1053_DCS, VS1053_DREQ ) };
EthernetClient    client;
uint8_t           mp3Buf[VS1053_DATABUFFERLEN];
uint32_t          contentLength;
byte              macAddress[6]{};

uint32_t          beginRequest();
void              readMacAddress( byte* );

void setup()
{
  Serial.begin( 115200 );
  while( !Serial ){ delay( 10 ); }
  Serial.println( "MusicMaker/Ethernet Prototype" );

  Wire.begin();

  Ethernet.init( ETHERNET_CS );
  readMacAddress( macAddress );
  if( !Ethernet.begin( macAddress ))
  {
    Serial.printf( "Unable to initialize the network; hardware status is %d\n",
                   Ethernet.hardwareStatus());
    HANG;
  }

  Serial.print( "Mac address: " );
  for( int ii = 0; ii < 6; ii++ )
  {
    if( macAddress[ii] < 16 ) { Serial.print( '0' ); }
    Serial.print( macAddress[ii], HEX );
    if( ii < 5 ) { Serial.print( ':' ); }
  }
  Serial.println();
  Serial.print( "DNS IP:      " ); Serial.println( Ethernet.dnsServerIP());
  Serial.print( "Local IP:    " ); Serial.println( Ethernet.localIP());
  Serial.print( "Gateway IP:  " ); Serial.println( Ethernet.gatewayIP());
  Serial.print( "Subnet mask: " ); Serial.println( Ethernet.subnetMask());

  if( !player.begin())
  {
    Serial.println( "Unable to initialize the MusicMaker" );
    HANG;
  }
  Serial.println( "Initialized the MusicMaker" );
  player.setVolume( 40, 40 );
  player.sineTest( 0x44, 1000 ); // 1KHz tone for one second.

  contentLength = beginRequest();
  Serial.printf( "HTTP content length: %d\n", contentLength );
}

void loop()
{
  if( player.readyForData())
  {
    if( client.available() > 0 )
    {
      uint8_t bytesRead = client.read( mp3Buf, VS1053_DATABUFFERLEN );
      if( bytesRead > 0 )
      {
        player.playData( mp3Buf, bytesRead );
        contentLength -= bytesRead;
        if( contentLength <= 0 )
        {
          Serial.println( "That should be all of our sound" );
        }
      }
    }
  }
}

uint32_t beginRequest()
{
  if( !client.connect( host, port ))
  {
    Serial.print( "Unable to connect to " );
    Serial.print( host ); Serial.print( ':' ); Serial.println( port );
    HANG;
  }

  Serial.print( "GET " ); Serial.print( path ); Serial.print( " HTTP/1.1\r\n" );
  Serial.print( "Host: " ); Serial.print( host ); Serial.print( "\r\n" );
  Serial.print( "Connection: close\r\n\r\n" );

  client.print( "GET " ); client.print( path ); client.print( " HTTP/1.1\r\n" );
  client.print( "Host: " ); client.print( host ); client.print( "\r\n" );
  client.print( "Connection: close\r\n\r\n" );

  char http[] = "HTTP/";
  client.find( http );                  // Skip over the HTTP/ part of the header.
  client.parseFloat( SKIP_WHITESPACE ); // Skip over the HTTP version number.

  int httpStatus = client.parseInt( SKIP_WHITESPACE );
  if( httpStatus < 200 || httpStatus > 299 )
  {
    Serial.printf( "GET request failed; HTTP status is %d\n", httpStatus );
    client.stop();
    HANG;
  }

  char lengthHeader[] = "Content-Length:";
  client.find( lengthHeader );
  int contentLength = client.parseInt();

    char endOfHeaders[] = "\r\n\r\n";
  if( !client.find( endOfHeaders ))
  {
    Serial.println( "Invalid HTTP response (missing trailing line endings)" );
    client.stop();
    HANG;
  }
  return contentLength;
}

void readMacAddress( byte* addr )
{
  Wire.beginTransmission( MAC_EEPROM_I2C_ADDRESS );
  Wire.write( MAC_EEPROM_REGISTER );
  int failed = Wire.endTransmission();
  if( failed )
  {
    Serial.printf( "Unable to retrieve MAC address; endTransmission returned %d\n", failed );
    HANG;
  }

  byte* b = addr;
  int bytesRead = Wire.requestFrom( MAC_EEPROM_I2C_ADDRESS, 6 );
  if( bytesRead < 6 )
  {
    Serial.printf( "Unable to retrieve MAC address; fewer than six bytes\n" );
    HANG;
  }

  while( Wire.available())
  {
    *b++ = Wire.read();
  }
}

is a SD card inserted? if yes, then remove it or set the CS pin HIGH at the beginning of setup(). set the CS pin of the player HIGH before Ethernet.begin()

Set both the SD card CS and the player CS to outputs and set them high prior to Ethernet.init() and Ethernet.begin(). If both Ethernet and player are initialized, neither works. player's sineTest() method doesn't do anything and EthernetClient's connect() method returns zero. They both use SPI. Could there be some sort of conflict there?

Turned out to be a hardware problem.
The PoE FeatherWing's default CS pin conflicts with the MusicMaker's DCS pin. The PoE CS pin can be changed by cutting a trace on the back of the board and bodging a wire from a pad to whatever pin you want to use instead. I had done that.
Turns out though, that I hadn't cut it completely. This was causing the Ethernet library to pull the MusicMaker DCS low every time it pulled the Ethernet CS low.
I finally figured it out when I hooked up a logic analyzer to all of the CS pins and the SPI pins. It was very clear that MusicMaker DCS was going low with Ethernet CS.
Yay Logic Analyzer.


text:
String Comparison
I am trying to compare two string but each time i am getting awkward results. When i use Equals() function i always get the wrong answer and never satisfy the IF statement. When i use compareTo() function i always get the right answer (which is btw not correct) but it always just satisfy the IF statement.
String input;
String Answer = "cat";

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

void loop()
{
  while (Serial.available() == 0)
  {
    Serial.readStringUntil('\n');
    if (input.equals(Answer))
    {
      Serial.println(input + ", Correct");
    }
    else
    {
      Serial.println(input + ", wrong");
    }
  }
}

Above is the code i am using to learn the string Comparison.

You have defined a variable named input, but you never assign a value
to it. It should thus always have its initial value, which is an empty
string.
Here:
Serial.readStringUntil('\n');

you probably meant
input = Serial.readStringUntil('\n');

Edgar Bonet thanks. I have initialised the input as you mentioned. But results are same. I don't know what's getting wrong here.

@ASADALI, add input.trim() after input = Serial.readStringUntil('\n'); to remove \r


text:
Why use multiple filters output thousands value, use one or two filter can output normal value?
Problem
If the loop runs only one simulated pin and uses a filter, it will output normally (analog 1600~2200, filter 0~500), but creating an array to store multiple filtered simulated pin values will cause problems, and the output will be abnormal (10000~80000).

If analog read six sensors, and their value is 1600~2200.
It used the code below.
#include "EMGFilters.h"
#define SERIAL_TX_BUFFER_SIZE 4096 //修改串口接收缓冲区大小为2048
const int SensorInputPin[] = {A0, A1, A2, A3, A4, A5};
EMGFilters myFilter[6];
SAMPLE_FREQUENCY sampleRate = SAMPLE_FREQ_500HZ;
NOTCH_FREQUENCY humFreq = NOTCH_FREQ_50HZ;

void setup()
{

    for (int i = 0; i < 6; i++)
    {
        myFilter[i].init(sampleRate, humFreq, true, true, true);
    }
    Serial.begin(115200);
    Serial1.begin(250000);
    analogReadResolution(12);
}
void loop()
{
    long time = millis();
    int x[6] = {0,0,0,0,0,0};
    int analog[6] = {0,0,0,0,0,0};

    for (int index = 0; index < 6; index++)
    {
        //x[index] = myFilter[index].update(analogRead(SensorInputPin[index]));
        analog[index] = analogRead(SensorInputPin[index]);
    }
    while ((millis() - time) < 2)
    {
        delayMicroseconds(100);
    }
    Serial.printf("filter:%d %d %d %d %d %d analog:%d %d %d %d %d %d\n", x[0], x[1], x[2], x[3], x[4], x[5],analog[0],analog[1],analog[2],analog[3],analog[4],analog[5]);
    Serial1.printf("<%d,%d,%d,%d,%d,%d>", x[0], x[1], x[2], x[3], x[4], x[5]);
}

Change index<6 to index<2, and uncomment \\x[index] = myFilter[index].update(analogRead(SensorInputPin[index]));
It will be a normal output using two inputs and filters.

But changing index=0;index<2 to index=0;index<6 will be abnormal output.

If changing to index=3;index<4 or index=2;index<3...etc, it will be normal output:

Sketch:

XIAO MCU schematic in the HTML: https://files.seeedstudio.com/wiki/Seeeduino-XIAO/res/Seeeduino-XIAO-v1.0-SCH-191112.pdf
I don't have a sensor schematic.
Filter code: https://github.com/oymotion/EMGFilters/blob/master/EMGFilters.cpp
I hope each simulation output to look like the first Gif(normal output), what should I do to achieve this?

You need one filter per input...?

You didn't provide any context on what you are actually measuring, but I second Majenko with the guess, that you need one filter per analog input. Also I don't really understand your problem description. If this is because of the language barrier, maybe someone can help you, who speaks english better, and help with the wording of the question.

@Majwnko yes. Is there any way to solve this problem?

@chrisl I'm sorry, I may not be as fluent in English as my mother tongue. I hope each simulation output to look like the first Gif.

You currently use only one filter: myFilter. But you can define multiple filters in the same way and put them into an array for use in the for loop. Something like this: EMGFilters myFilters[6]; (define an array of 6 EMGFilters). In setup(): for(int i=0;i<6;i++) myFilters[i].init(sampleRate, humFreq, true, true, true);. And in the for loop: envelops[i * 6 + x] = square(myFilters[x].update(analogRead(SensorInputPin[x])));.

But I think you also need to think about what you are outputting. Currently you try to output the values of individual sensors in a new line each. The serial plotter interprets this as new datapoints of the same signal, though actually you have 6 data points, one for each signal. I think the Serial Plotter supports plotting multiple lines, when you print the datapoints in one line seperated by a space.

@chrisl I have tried to create a filter for the simulated output, but the output is still abnormal(The post has been updated and the picture has been uploaded). The loop function outputs normally only if it has only one line of instructionsquare(myFilter.update(analogRead(SensorInputPin[per input]))). I don't understand why only one line should output normally.

@chrisl I found using third analog input case error, what do you think is the reason?   I measured the third analog input separately and found no problems. It seems that as long as I use the third one, no matter what the third analog pin is, it producing thousands of values. The issue has been updated.

What Arduino board you are using? You are assuming that each integer is 2-byte long, this is true if you are using an Arduino Uno, but it will not be the case if you are using an STM32 or SAMD-based Arduino, for those, an Int is 4-bytes.

@chrisl Hello, I reconstructed the post.

@hcheung OK. I have been updated.

This is a bug in the filter library you are using. It has already been
reported (by you, maybe?).
As Majenko and chrisl suggested in comments, the crux of the problem is
that you need one filter per input channel. Using multiple instances of
EMGFilters seems like the obvious solution. Alas, the library keeps
the filter state in global variables, which essentially means your six
filter objects all reference the same actual filter.

Yes. It's my Issue. How do I prevent referencing global variables of the same filter? Need to reference "EMGFilters1.h","EMGFilters2.h"...etc?

@C.SH.K: No. You should fix the library, or wait for the authors to fix it. If you want to do it yourself, just turn the filter state into instance data. C.f. my comment to your issue.

@C.SH.K: Or you may use the branch from this pull request.

Thank you! Solved the immediate problem!

Image Image2After using your file, some pins have a strange place, some emG output tens of thousands of values, some normal output. Before, with the raw filter code, it would print like thisBefore index=0;index<1...etc

Oh. Just bad sensor contactThe sensor AREA I bought is too large, so it is not easy for the dry electrode to fully contact the skin when touching the arm, which is prone to baseline drift.


text:
How to prevent replacing of the value for a key in Preferences?
#include <Preferences.h>

Preferences preferences;

const char* roomname_long = "String 1";
const char* roomname_short = "String2";
const char* roomname_long_test = "String 3";
String roomname;

void setup() {
  Serial.begin(115200);
  preferences.begin("app",false);

  preferences.begin("credentials", false);
  preferences.putString("roomname_long", roomname_long);
  preferences.putString("roomname_short", roomname_short);
  preferences.putString("roomname_long", roomname_long_test);

  roomname = preferences.getString("roomname_long", "");

  Serial.println(roomname_long);
  Serial.println(roomname_short);
  Serial.println(roomname);

  preferences.end();
}

void loop() {

}

I try to save some data on my esp32 it works actually but if I try to save another variable with the same key it writes over the String before how can I interrupt that?
on the Serial Monitor I got this:
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1324
ho 0 tail 12 room 4
load:0x40078000,len:13508
load:0x40080400,len:3604
entry 0x400805f0
String 1
String 2
String 3

I want that if I put another variable in "roomname_long" key it must not be overwritten.
So it should be stay on String 1

You can use isKey to test if the preferences key is already set.
preferences.putString("roomname_long", roomname_long);
preferences.putString("roomname_short", roomname_short);
if (!preferences.isKey("roomname_long")) {
  preferences.putString("roomname_long", roomname_long_test);
}


text:
Arduino port not discovered with bootloader / Did I fry my board?
I have a Arduino Nano 33 BLE that I've been using for a while. I usually upload new programs to the board through USB with the board in a bootloader loop. The other day this stopped working. The board can successfully be put in the bootloader (slow pulsing light), however it does not appear as a TTY device on my computer. The last program I put on my device still works, and successfully outputs serial output (and I can even connect to the bluetooth module).
This leads me to believe my board is working, though I don't understand why I cannot upload via the bootloader. Interestingly the bootloader running makes the board pretty hot (hotter than my program running, is it in an infinite loop or something?).
I thought the bootloader might've been corrupted, so I re-uploaded the board's bootloader via a raspberry pi over OpenOCD (it's possible I did this incorrectly?). Now the device remains in the bootloader no matter what.
I'm wondering if it's possible I fried just the USB part of my board? is that likely? I did hook up the board to a wall adapter that is rated 12V @ 1.5A. The issue seemed to occur after this. Is the board able to handle 1.5A? Do I need to use an additional circuit to properly power the board off of this power adapter?

So I cannot even attempt to upload it, as the board is not available for selection. A ls /dev/tty.* results in no devices.

If you put that 12V to Vin pin, it should be fine, to any other pin it means death.

@KIIV thanks! that's what I expected, I didn't see a max current for that pin, and assumed that shouldn't be a problem (it should just draw the amount it needs, no?)

Yes, I did see that, the detail data sheet says the Vin feeds into a 3.3V power which has a max current of 1A. Is it possible I messed something up there?
I have a new board on the way, my bigger concern is not also bricking that board, if I have indeed bricked my current board.

I'd expect smoke to appear if an Arduino gets fried with 12V and that should most likely have killed the entire controller.

Ya that's what I was thinking as well -- can anything explain the behavior I'm seeing then?

You can try to program it via an ISP programmer (for example using another Arduino). You can also reflash the bootloader that way. If the ISP programming fails, then your controller is dead.

Would that be any different than flashing a bootloader via OpenOCD?

I see Input Voltage (limit)  21V. Flashing over SWT is 'ISP'

you say "The last program I put on my device still works, and successfully outputs serial output". how it there is no port?

Over the TX and RX lines I can get serial output, but the on-board USB does not show up as a port

is the USB cable 'power only'?

It is not, same cable worked previously with the same board (I've tried other cables as well). I think I screwed up the bootloader now, probably used OpenOCD incorrectly. I have a BMP on the way. Maybe I can revive it that way. At this point it's to satisfy my curiosity


text:
Do I need to use resisters and ICes for specific sensors.What if I dont use it,Will it impact my arduino board some how like making it useless &faulty
So I was reading about Simple AutomaticLight Controller using LDR. or with the help of LDRSenso. But I have LM393 Photoresistor (LDR) Sensor I like to know are they same thing or somewhat different. So the way they work is detecting
light intensity and It is associated with both analog output pin and digital output pin labelled as AO and DO respectively on the board.When there is light, the resistance of LDR will become low according to the intensity of light. The greater the intensity of light, the lower the resistance of LDR.
And before that I was reading about Analog Piezoelectricity Ceramic Piezo Vibration Sensor For Arduino
So LDR sensor needs some kind of resister. And Analog Piezoelectricity Ceramic Vibration sensor needs some IC.
Can Anyone be specific to these specific resister and IC for each sensor types. I have them both as module for arduino Uno. I like to code in gcc avr. Thats how I am restricted. And will use C code to control but Can any please be briefly explain this type of resister for LDR sensor and Piezoelectric vibration sensor IC. Just few words to help me relate to some explanation and easily get poped in my mind when ever I hear about these two modules again. So Just some brief on this specific types of resister and IC related to these two modules why they needed how to code, and control through code
These are pictures of two sensors as Chrisl asked

https://www.daraz.pk/products/i140816069-s1300868385.html?urlFlag=true&mp=1
https://www.daraz.pk/products/i162290793-s1329534669.html?urlFlag=true&mp=1

If you need extra circuitry for a sensor depends on the exact sensor. Please provide a link to that exact product, that you have. Or - if there is no product link - then at least a few good photos of the used sensor/board and the part numbers, that might be printed on the boards or components.

@chrisl hi please check the sensor modules pictures I have posted

So you have a product page. Then please include the link to that product page in your question.

Both images, that you included, show breakout boards. They are circuit boards (PCB - Printed Circuit Board), which contain all the components, that are needed to connect the corresponding part (in your case a piezo and an Light Dependent Resistor (LDR)). They are called this way, because they are "breaking out" simple output pins from the sensor circuitry for directly connecting them to the Arduino. So instead of having to build the circuit with the pure components you have a simple board, which gives you standard pin headers for connecting to the your Arduino. They are also often called "modules".
That means, that you don't need any additional circuitry or ICs to connect these boards to the Arduino. For the piezo sensor the image even shows the wiring diagram. You can see there, that you don't need any additional parts besides the breakout board, piezo and the Arduino itself. The same applies for the LDR breakout board.
Connections:
For the piezo sensor you have an analog output. Thus you need to connect that to an analog input on the Arduino (A0 to A7) and read the signal with analogRead().
For the LDR breakout board I cannot be sure without a link to the product page, but it seems, that it has a digital output (DO). You can connect it to a digital input of the Arduino. It will switch between HIGH and LOW at a certain threshold brightness, which you can control by using a small screwdriver to rotate the little potentiometer on the board (the blue box with the hole in the middle).

can u please tell what is meant by breakout board. I have no clue. Are u refering breakout board to my sensor modules?

I have also posted product page link

@user786 I changed the description at the start of my answer to make it more clear.

Can u please tell last thing what is negative and positive electrodes on piezo sensor. Can I use screw driver for this too to control something?

@user786 The black wire of the piezo is ground. And no, you cannot set anything with a screwdriver here. You need to read the analog signal in your Arduino code. Then you can use your code to do a similar thing (doing something, when the read analog value is higher or lower than a specific threshold).

Can u also please tell what is ADC in analogRead that u mentioned. This function is not present in avr gcc. And I see the code from avr core it's very small function can u please add something on that too.

@user786 I'm not sure what you mean by that. The ADC is the Analog Digital Converter, the hardware that enables the Arduino to meaure analog voltages. When you don't want to use the Arduino framework (and thus analogRead()) you need to configure the ADC yourself directly by setting the corresponding registers. Refer to the datasheet of the Atmega328P (the microcontroller on the Arduino).


text:
Can't figure out why what I'm trying to do isn't working. Trying to light up a RGB with buttons with AnalogWrite
DISCLAIMER : I have just started Arduino, like 2 days ago, I've been following some tutorials on YouTube, and I tried to do this myself, but I can't figure out why it isn't working, can't find what I'm doing wrong.
THE SETUP (I've already tested it with some other code that proved me that the setup is working, each buttons and each pin of the RGB LED, I know for sure that this is the code not working)

I am trying to light up the led to RED thanks to second button (from LEFT), Green with third, Blue, with fourth, and the first one to put the LED off . I am aswell trying to make a perfect visual transition between each colors going from 255 to 0 decimal..
Here is my code :
#define BLUE 10
#define GREEN 11
#define RED 5

int buttonBlueOn = 9;
int buttonGreenOn = 8;
int buttonRedOn = 3;
int buttonRgbLedOff = 2;

void setup() {
  // put your setup code here, to run once:
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(buttonRedOn, INPUT_PULLUP);
  pinMode(buttonGreenOn, INPUT_PULLUP);
  pinMode(buttonBlueOn, INPUT_PULLUP);
  pinMode(buttonRgbLedOff, INPUT_PULLUP);

}

int redValue;
int greenValue;
int blueValue;

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

  // -------------------------------- RED ------------------------------ //

#define delayTime 20

  if (digitalRead(buttonRedOn) == LOW)
  {
    digitalWrite(RED, HIGH);
    redValue = 255;
  }

  if (digitalRead(buttonRedOn) == LOW and GREEN == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out green brings red full
    {
      redValue += 1;
      greenValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonRedOn) == LOW and BLUE == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out blue brings red full
    {
      redValue += 1;
      blueValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(BLUE, blueValue);
      delay(delayTime);
    }
  }

  // -------------------------------- GREEN ------------------------------ //

  if (digitalRead(buttonGreenOn) == LOW)
  {
    digitalWrite(GREEN , HIGH);
    greenValue = 255;
  }

  if (digitalRead(buttonGreenOn) == LOW and RED == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out red brings green full
    {
      greenValue += 1;
      redValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonGreenOn) == LOW and BLUE == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out blue brings green full
    {
      greenValue += 1;
      blueValue -= 1;
      analogWrite(BLUE, blueValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  // -------------------------------- BLUE ------------------------------ //

  if (digitalRead(buttonBlueOn) == LOW)
  {
    digitalWrite(BLUE, HIGH);
    blueValue = 255;
  }

  if (digitalRead(buttonBlueOn) == LOW and RED == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out red brings blue full
    {
      blueValue += 1;
      redValue -= 1;
      analogWrite(RED, redValue);
      analogWrite(BLUE, blueValue);
      delay(delayTime);
    }
  }

  if (digitalRead(buttonBlueOn) == LOW and GREEN == HIGH)
  {
    for (int i = 0; i < 255; i += 1) // fades out green brings blue full
    {
      blueValue += 1;
      greenValue -= 1;
      analogWrite(BLUE, blueValue);
      analogWrite(GREEN, greenValue);
      delay(delayTime);
    }
  }

  // -------------------------------- OFF ------------------------------ //

  if (digitalRead (buttonRgbLedOff) == LOW)
  {
    digitalWrite(GREEN, LOW);
    digitalWrite(RED, LOW);
    digitalWrite(BLUE, LOW);
  }

}

WHAT IT DOES : Nothing at all, nothing lights up, nothing happens, I'm a bit confused
I am so new to this, sorry if I'm doing something wrong on this forum

Looks like you did not connect the buttons to ground.

You have connected the buttons to the blue power rail of the breadboard, but you haven't connected that to ground on the Arduino

insert a layer of separation between the detection of a keypress and the resulting change to LED brightness ... do not do if button pressed, set led brightness ... instead do if button pressed set variable deltaRed=1 ... then further in loop() do redValue += deltaRed; light red led

GREEN == HIGH will never be true, that's a comparison between two constants

Your program makes things too complex. You should rethink your whole strategy.
My preferred method is to have a "target" colour and a "current" colour. When you press a button you simply change what your target colour is. And then every iteration through loop() (either slowed down with a short delay() or triggered with millis()) you compare the target and current colours, and if they differ then move the current colour a step closer to the target colour.
That way you remove all the logic of "if this is pressed but not this then fade between these two colours", instead it's just "if this is pressed then I want to go to this colour" and the changing of the colour is completely independent.
I wrote a blog post on the topic some time ago that you might find helpful.


text:
Changing I2C Address on Garmin LidarLite, resets on reboot
I am trying to change the I2C address of multiple Garmin LidarLite-V3. I am able to change them one at a time using the LidarLite C++ library using the setI2Caddr function, and can see the updated I2C address using i2cdetect. The problem is that when the LidarLite loses power and turns back on, the address is reset to the default 0x62. This means when I have multiple LidarLite connected in parallel, they all default to the same I2C address and I am unable to individually change the addresses using the setI2Caddr function. How can I change the I2C address so that it persists through a power cycle, or alternatively change the addresses when multiple LidarLite are connected in parallel?

The manual of the Garmin Lidar Lite tells you about this. From page 5 under "Configurable I2C Address":

This can be used to run multiple devices on a single bus, by enabling one,
changing its address, then enabling the next device and repeating the
process.
The I2C address will be restored to default after a power cycle

So you cannot change the fact, that the I2C addresses will be reset to the default value on power cycle. But on startup you can give each sensor its own address. For that you need to wire the Power Enable pins to digital pins on the Arduino. When the digital pin is HIGH, the sensor is deactivated. So you start with all the Power Enable pins on HIGH. Then you set the first Power Enable pin to LOW, set the sensors I2C address via the corresponding I2C command and then proceed to the next sensor. When finished every sensor has its corresponding address and you don't get any collisions on the bus, since you always have only one sensor with the default address enabled at any time.


text:
MP3-TF-16P only works while connected to serial monitor
I am building a project with Arduino Nano and the component in the subject, which, as far as I understand, can be assimilated to a DFPlayerMini (not sure if it's the same thing or it's just a cheap knockoff).
Following one of the millions of tutorials on the net I managed to make it work, I can correcly play audio files out of an SD card, but the weird thing is, that it only works while I'm connected to the Arduino with the serial monitor open on my IDE: the moment I close the IDE and power everything via Vin or via any other means - including USB power from the PC - it fails to do anything.
If this can be helpful, the wiring is as follows (taken from the instructables website where I found the first tutorial)
And the code running everything is the following
main.cpp
#include <Arduino.h>
#include <modules/Sound.h>

#define BTN 3
#define TX 10
#define RX 11

Sound sound(TX, RX);

void setup() {
  Serial.begin(9600);
  Serial.println("Init");
  pinMode(BTN, INPUT);

  if (!sound.init()) {
    Serial.println("Nope");
  }

  sound.playInitSound();
}

void loop() {
  // unrelated stuff
}

modules/Sound.h
#include <Arduino.h>
#include <DFRobotDFPlayerMini.h>
#ifndef __SOUND__
#define __SOUND__

#define SOUND_POWER_UP   1
#define SOUND_POWER_DOWN 2

class Sound {
    public:
        Sound(uint8_t txPin, uint8_t rxPin);
        boolean init();
        void playInitSound();
    protected:
        DFRobotDFPlayerMini soundboard;
        uint8_t txPin;
        uint8_t rxPin;
};

#endif

modules/Sound.cpp
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
#include "modules/Sound.h"

Sound::Sound(uint8_t txPin, uint8_t rxPin) {
    this->txPin = txPin;
    this->rxPin = rxPin;
}

boolean Sound::init() {
    SoftwareSerial mySerial(txPin, rxPin);
    mySerial.begin(9600);
    boolean working = soundboard.begin(mySerial);
    if (working) {
        soundboard.volume(10);
    }
    return working;
}

void Sound::playInitSound() {
    soundboard.play(SOUND_POWER_UP);
}

As I said, everything works as long as I'm connected to the serial monitor from the IDE (if it's any relevant, I'm using PlatformIO on VSCode, on Linux).
I also tried to use the if (!sound.init()) part to make the arduino LED cyclically blink if there is a failure, and indeed it starts blinking.
Any thought? Any way I can add more info to help troubleshooting?
EDIT:
I tried removing all instances of usage of the Serial but it doesn't help
I started thinking that maybe it was a faulty Arduino, so I switched to another controller and this one behaves a bit differently: the sound module gets initialized (I don't see the blinking led that would mean failure) but no sound is played.
The main difference between the two controllers is that the "faulty" one has the new bootloader, the one that is partially working has the old bootloader instead. Not sure if this is meaningful in the least.
EDIT 2:
The arduino with the old bootloader works just fine, beats me why

@jsotola Sadly, it does not help. I removed all Serial stuff and it still does not work if not plugged to the serial monitor. The situation changes a bit when changing the controller though. I'm updating the post to reflect these last findings.

this part is confusing ... the moment I close the IDE and power everything via Vin or via any other means - including USB power from the PC - it fails to do anything .... does the failure occur simply by closing the IDE program? ... is it the powering by Vin that causes the failure?

@jsotola any way I power it, be it via Vin or via USB the problem occurs. I'm beginning to think that it's the board that's defective, because the other one I have seems to be working just fine

I'm having the same problem. Did you find a way to make it work?

@user86864 sadly, no. I am convinced that the board is defective. Any other board works. I suggest getting a new board, maybe a cheap one, and try it out


text:
ATmega 328 Bootloaded, but Cannot Upload
I have been working on a project that I program using the ATMEGA 328p inserted into an Arduino Uno, and then remove it to put it on my breadboard. I now have realized how inadvisable this is, since I had a pin breakoff. I have spare ATMEGA 328 chips and a borrowed functional Arduino Uno. Starting with the instructions here from the official Arduino site, and then progressing to the instruction set here for using the different device signiture, I eventually gave up on using the IDE and ran avrdude from the command line. Here is my command:
C:\Program Files (x86)\Arduino\hardware\tools\avr\avr\bin>avrdude -v -v -c arduino -p m328p -P com9 -b19200 -F

And the following results:
avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch`

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : com9
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATMEGA328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     5     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9514
avrdude: Expected signature for ATMEGA328P is 1E 95 0F
avrdude: safemode: lfuse reads as 62
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as 7

avrdude: safemode: lfuse reads as 62
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as 7
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

From these results, I want to conclude that the bootloader is now installed onto my ATMEGA 328. However, when I try to upload to it using the Arduino Uno "shell" with its 328p removed,I get the following error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x80

(and the next 10 tries)
Is there something I am missing? I am connecting the reset pin to pin 1 of my ATMEGA 328, and the RX/TX to pins 2 and 3, respectively.
Any help on this one would be greatly appreciated.

Why do you think that you have burned the bootloader? Neither the avrdude commandline, nor its output mention the bootloader hex file or writing to the Atmega. I'm not that firm with the avrdude options, but it seems, that you just read the fuses. You have written nothing (it would have told you if it had written something).

Most people will never have a legitimate reason to use avrdude's -F options. That message you get from avrdude about -F is a not a prescription. I see you mentioning 328P and 328, but it's not clear to me that you understand that these are different devices, which is why they have different signatures.  So what you actually have? Is there a P in your actual chip's part number or not?

chrisl is right, you are not uploading anything. The line to upload in one of my makefiles for an ATmega328 looks like this... avrdude -p m328 -c avrispv2 -P COM4 -U flash:w:hexfile.hex -U lfuse:w:0xe2:m -U hfuse:w:0xdf:m -U efuse:w:0xf9:m -v -B 10 -i 10... if you want to upload, you need to specify both the write target and a hex file (-U flash:w:hexfile.hex)

...you probably have to change the command a little bit if you want to upload a bootloader, I don't quite remember atm... but you definitely need to use the -U option for upload


text:
Which Arduino board would be sufficient for the following simulink project?
I'm trying to run a Fuzzy Logic MPPT Algorithm in Arduino UNO, here's the Simulink File
However when I try to upload the code, I get the following error

Is this project possible with UNO, if yes, what shall I do? Else which Arduino board would be suitable for this project?

We cannot answer about your Simulink program (since this site is only about Arduino). But currently you are using 3 times the RAM an Uno has. You can try to optimize your Simulink program, though I doubt that you will be able to reduce the needed memory that much.
So you should switch to a board with significantly more RAM. There are many to choose from, with different RAM, flash, peripherals, pin numbers. Write down all your requirements and then look for a fitting board


text:
Why is the server.on() function from "ESPAsyncWebServer.h" executed in the setup() side and not on the loop() side?
I'm implementing an example in which 2 ESP32's communicate each other using the HTTP Protocol. One acts as Server the other as Client. In the examples provided, I am curious about the declaration on the server, as its implementation is declared in the setup() function (I am using the standard Arduino IDE), which is supposed to have code that executes only once, rather than the loop() function (at least in this example), which is supposed to refresh the call every cycle, yet it remains empty:
  Complete project details at https://RandomNerdTutorials.com/esp32-client-server-wi-fi/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

// Set your access point network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";

/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String readTemp() {
  return String(bme.readTemperature());
  //return String(1.8 * bme.readTemperature() + 32);
}

String readHumi() {
  return String(bme.readHumidity());
}

String readPres() {
  return String(bme.readPressure() / 100.0F);
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);
  Serial.println();

  // Setting the ESP as an access point
  Serial.print("Setting AP (Access Point)…");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readTemp().c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readHumi().c_str());
  });
  server.on("/pressure", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readPres().c_str());
  });

  bool status;

  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  // Start server
  server.begin();
}

void loop(){

}

You can see the "server.on(....)" declarations in the setup() side of the code, and the empty loop() function in the end.
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readTemp().c_str());
  });

So, my assumption is that the server is already running in the background when executing server.begin() and does not need to be explicitly called, but it still confuses me because there is no explicit declaration on the loop() such as server.loop() or something similar.
Can you explain how this works and why it is not necessary to explicitly declare the function on the loop()?
Thanks
-EZ

Server.on() sets a callback function. That registers a function to be executed when a certain event happens at a later date. In this case it's when a certain URL is requested with a GET method.
Any time a request is made to the web server a list of "on" registered events is examined for one that matches the request, then the associated function (in this case a lambda function) is executed.
And all that is done asynchronously (hence the name) in the background in another thread so you don't need to explicitly do anything.

Thanks, I figured as much, but  I wanted confirmation. The Asynchronous part seems to be doing the trick for the callback operation without the explicit mention.

The construct with a lambda function
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readTemp().c_str());
  });

is same as
server.on("/temperature", HTTP_GET, onGetTemperature);

where onGetTemperature is a function defined before void setup()
void onGetTemperature(AsyncWebServerRequest *request) {
  request->send_P(200, "text/plain", readTemp().c_str());
}

Would you in this case ask why it is "executed in the setup()?"

Well, it seems to me that you are just separating the lambda function outside of the setup() scope and calling it from inside setup(), but my question would not be "why is it executed in the setup" but rather, why the server.on function is not explicitly called from within the loop function? Which I believe Majenko just confirmed it is a callback() and thus not required to be explicitly called, as it is triggered by the server and compared to match one of the multiple "on" functions that could be listed in setup().

Yes, server.on() is a callback function, but that's not the entirety of the story.
You don't see anything related to the server in loop() either, because somewhere in the backend of all that code, probably in server.begin(), the server attaches a callback or ISR of its own to the networking stack of the ESP. Now, when the ESP gets a message across the network of the right type, the networking stack redirects the message into the server's internal callback, at which point the server checks the page that was viewed and executes the appropriate server.on-specified function that you put in setup().
I haven't yet had the chance to look into exactly how the server's callback is attached to the networking stack, but that's how it operates asynchronously. Either it's originally activated by a Wi-Fi hardware ISR (allowing it to temporarily pause your code's execution to run the server) or it's run by a small scheduler-like section of code that is executed outside of loop() (meaning that between iterations of loop(), it might be handling the server. It's probably this case since this is when some parts of the networking stack are handled anyway).
One minor note: this operation has a potential side effect of causing memory use or CPU use by the server when you might have intended to allocate either to your own application code, so if you start seeing odd timing errors or memory corruption on a really large application, you may want to look into this as a potential cause.

it uses SDK callbacks


text:
Arduino Code is slow when running two task

I want pin 11 to give a square wave of once 3 sec

and want pin 12 to act as a switch to glow pin 13 Built in led..

connected pin 12 to GND with 10k resistor

If i fed the switch code alone it is fast(the led turn on instantly), but when i fed this code (the on in picture) it has a 1 sec lag to turn on the led. why?
And also if i connect pin 11 to 12 i assume the builtin led should turn on and off according to the wave form coming out of  but the led is always low.

use this library https://www.arduino.cc/reference/en/libraries/arduino-timer/

Or this https://playground.arduino.cc/Main/FlexiTimer2/  https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers

Just to try to confirm what exactly you're asking about: you've explicitly told it to do something, delay for 3 seconds, do something else, delay for another 3 seconds ... and now you're asking why there's a delay ... ?

No code as image please. Copy and paste the code as text into the question. Then you can format is as code so that it will be displayed correctly

Look at the BlinkWithoutDelay example that comes with the Arduino IDE, and at the millis() function. You can find many tutorials about that online. Basically you should not delay for long periods of time, since the arduino cannot do anything in that time. Use a non-blocking code style

@brhans bro i mean only the switch portion not the wave form..  if i turn on the switch there a 1 sec lag

@chrisl what language is ard ?? C or c++

Arduino code is C++

Your Arduino isn't going to even read the switch until the delay(s) are finished. So you're looking at a delay of up to 6 seconds in every loop where it's not reading the switch.

@brhans so first the blink code execute then only the switch code comes???

Please make sure that you understand the code you have written. From your comments it does not seem so. As chrisl says, look at the blink example without delay, and understand it. We can only give you hints, the learning is your task.

@yuvanm: Re “first the blink code execute then only the switch code comes?”: Indeed: the Arduino executes one statement at a time, in the order they are written. Whatever comes after delay(3000); is only executed once the Arduino is done with the delay.

@EdgarBonet thank you got it

OK everyone. You see the "answer" box below the question? That's where answers go. It is kind-of sad that this box is empty (at the time I write this) and a whole lot of useful answers are given as comments on the question. This is not a forum. Please do not answer in comments.

@yuvanm If you think you understand what the issue is, you can even answer your own question, thus helping future people who are wondering the same thing. Then people can vote on your answer, showing how good it is.

Basically, the code comprises Two Parts

Square Wave with 3-sec delay on and 3-sec delay off
if the pin 12, is high pin 13 will be high and if 12 is low 13 is also low(a simple on/off switch)

The second block of code executes only after the first Block of code is done executing.
That's why when I connected the pin 11 to 12 the led wasn't shining because when the WAVE code(that first block of code which gives a square wave) was running, the second block of code was quiet hence the 12th pin was still not become a switch yet.
And the delay I told was due to this, actually, the delay is 6 sec.
Because after the switch code completes its run, it will take a whole six seconds for the Arduino to come back to switch code in the loop because the wave signal of 3 sec on and 3 sec off should run.
if you want to run two tasks at the same time you need to learn the topics of millis() and protothreading.

You can ask me why I was this dumb to ask a question like this, because the only programming language I have ever snorted is python and in there I learned python is an interpreter and it executes line by line, Since Arduino ide code is built around c++ which is the compiler.
I thought the code won't run line by line instead the code will be compiled but now only I understood that even though the file is compiled there is no chance every code can be run at the same time as the actual meaning of the compiler.

I would suggest you do some research on the delay function so you understand why it is called a blocking function. The compiled code goes line by line as well. If you want to do two things at once you need two threads.  You can get the appearance of doing two things at once with multitasking. I have a feeling your code works as written, it only checks the switch every 6 seconds.

Yeah brother, i got it


text:
How to know the data type of constant in arduino IDE?
For example constant of MSBFIRST, It used to as input in SPI.setBitOrder(MSBFIRST). But sadly i don't know the type data of MSBFIRST. This is applied to like SPI_MODE0 and other.

short and universal answer: look in the .h files of the library for function parameter type

From SPI.h:
#ifndef LSBFIRST
#define LSBFIRST 0
#endif
#ifndef MSBFIRST
#define MSBFIRST 1
#endif

As you can see, there is no type. The compiler merely substitutes literally "1" for "MSBFIRST". So your code would read, after pre-processing:
 SPI.setBitOrder(1)

To know exactly what type "1" is (I'm not sure why you need to know) then you would look up "C++ integer promotion". In other words, how are literal integers handled by the C++ compiler.

From a comment:

In which case it's better to look at the desired type of the destination function not the type of the macro or const.

Quite right. If you look further into the SPI.h file you see this:
  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setBitOrder(uint8_t bitOrder) {

So, ignoring what type MSBFIRST is, you can see that the function expects uint8_t.

Maybe he wants to know what the type is so he can use it as a parameter to some form of wrapper function or another form of abstraction layer? In which case it's better to look at the desired type of the destination function not the type of the macro or const.

@Majenko Indeed. I've amplified my reply to show this.

@Majenko you are right, i want to know type so i can use it as parameter for my abstraction layer. Nevermind, I already know the data type with using Serial.println(MSBFIRST),  it was displaying  1 in serial monitor. So i assume the data type is unsigned integer aka byte.