text:
How to save arduino serial monitor data into excel file
I am looking for the software that can help me to save arduino serial monitor data into excel file. And how to use that with your own code.

copy and paste with a limited amount of data ... otherwise, write a script in Processing to read data from serial and write the data into a csv file .... http://processing.org

use csv file format

Look for a serial terminal software which supports logging to a text file.
There are simpler ones than PuTTy.

Your computer is able to access the serial data and export it to a text file, which can then be converted to an excel file within Excel > Data > From Text. However, the data should be formatted in a way that excel can read it by separating values with a delimiter such as ",".
Once you have done this, simply run your serial data and open up your computer's console and write:
type COM(# here) >> serialdata.txt
Finally, import this text file into excel.
You could also use Excel VBA with MSCOMM to take the serial data directly into excel.
This answer is a regurgitation of a duplicate question asked earlier.


text:
Using the Broadcom AFBR-S50 with Arduino
I'm trying to interface with a Broadcom AFBR-S50MV85G ToF sensor over SPI using an Arduino, which is complicated by the fact that the provided library and reference application is written for Cortex M0-based NXP microcontrollers. The documentation says that implementing the SPI, IRQ, Debug and Timer interfaces would allow use with other platforms, but it doesn't explicitly state which functions require implementations, or if all of them do, and it's not demarcated within the source code either.
The documentation lists the available command words, but no register addresses, which I believe are used by the platform-independent compiled libraries that come with it. This leaves me with no way to interface manually over SPI, meaning that my only choice appears to be to attempt to implement the platform drivers myself, which will probably take me a significant amount of time.
Is there something else I should try before sinking time into something that may not give me results? Has anyone here used this sensor before, and if so, could you point me in the right direction?
P.S.: The documentation I'm referring to is included in the SDK provided in the downloads section of the product page, and I'm not sure I'd be allowed to rehost it somewhere else in order to link it here.

Welcome to the wonderful world of Broadcom. Unless you're a multi-billion dollar global technology giant, you won't get **** out of them.  And then only with multiple layers of NDAs.

@Majenko Yeah, I'm starting to realize that after trying to contact them directly. I couldn't get anything out of them - I tried going through Digi-Key, and even they got stonewalled. :/

Eben Upton had the same problem with the Pi. That's why graphics on the Pi are so crap - Broadcom won't give anyone the information they need to use the GPU. And he works for Broadcom! Everything on the Pi has basically been reverse engineered from other sources.  Broadcom are dicks.

@Majenko Wow, that's incredible, did not know that. Clears up a lot, actually. sigh Hopefully someone else has made the same mistake I did and had better luck.

I recently looked into this again, and it turns out that Broadcom had released a porting guide for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.
I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.
P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.

I switched from Arduino to a Blackpill (STM32F411CE) and was able to get the sensor to work. I had to rebuild a STM32CubeIDE project based on their example, as I couldn't get theirs to work. The HAL tests they provide were particularly useful. The sensor works great, even in direct sunlight, unlike others such as the VL53L0X.

I also have been digging for information about the AFBR-S50MV85G and similar sensors for the past week.
Well, I am trying to port it to ATxmegas (ICs that are similar to those ATmegas used in the Arduino Family), but I decided to post my findings here because this is the first forum topic that I have found about this sensor family.
As Joseph mentioned, Broadcom has released a porting guide to Arm devices, but it does not help at all when it comes to porting to other microcontrollers.
Additionally, the minimum requirements of this lib according to Broadcom's porting guide are:

Minimum memory requirements:
RAM: 8kByte (4kByte Heap + 4kByte Stack)
ROM/Flash: 128 kByte

Because of that and other facts, I also conclude that it is not possible to port the available libraries to 8-bit microcontrollers nor develop a new one due to the lack of description about the SPI register structure.

source: Stack Exchange

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

sort: votes


text:
I am working on a thermometer and humidity why am i getting this error
Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
In file included from C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:
C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This indicates your IDE is missing the "Adafruit Unified Sensor" library as outlined here.
To install it, select "Tools" -> "Manage Libraries" and search for "Adafruit Unified Sensor". You can install the library by selecting it and pressing "Install".

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


text:
Programming ESP32 MCUs for production
Before committing to learning about the ESP32 and how to program it, I would like to know if the ESP can be programme the same way for production as it can on évaluation boards (with the Arduino IDE).
Since it obviusly much easier than most for microcontrollers, I was wondering if a product is eventually mass produced, if the code used to program the evaluation board (such as this one https://makeradvisor.com/tools/esp32-dev-board-wi-fi-bluetooth/) could be used on the final product.

Yes. Most manufacturers would just require a binary (or HEX depending on MCU) file of your compiled code. If it's not a system they already know how to handle you will also need to provide a procedure for them to follow to program the device. What form that takes depends on the manufacturer.
You can also generally order pre-programmed MCUs and modules direct from the manufacturer where they (for a small fee) will program the chips for you before they are then sent to the board manufacturer for population.
If there is no facility on the MCU manufacturer's website then just email their sales department and I am sure they would be happy to quote you. Again, all they will require is a HEX or BIN file (depending on manufacturer) for programming.

Perfect Answer, thank you! To follow up, I'm assumant this means that using VSC, Atom, or the Arduino IDE, there is a procédure to build the code into a binary for the ESP32. Could you point me in the direction of such a procedure ? (research so far has gotten me to annexe articles such as 'how to make the binary smaller' etc...)\

Just compile your code as normal - then you just need to grab the binary from wherever it ends up (turn on verbose compiling to find where that is).


text:
Using ESP32 to measure vbat
I'm using ESP32 to read an analog value of a liPo battery (3.7v-4.2v).
Since ESP32 DAC's is 3.3v I'm using a voltage divider ( 2x10K resistors ), to split bat's voltage into ESP's GPIO36. So far nothing new or not well documented on the web.
Using the voltage divider, splits the 4.0v into 1.97v (measured using a volt-meter). Battery's negative pole is connected to ESP's Gnd to get a common ground. GPIO36 is connected to the 1.97v line ( and this value is tested using a volt-meter also on ESP's pin to make sure ).
I was expecting to get a digital value of 1.97 (2444 )
BUT NO!,
when using analogRead(36) I'm getting a digital value of 2180 which correlates to 2180/4095*3.3 = 1.75v.
1) I tried to make a 100 samples over time - to make sure it is not a power up issue. No change.
2) I tried to read its value during loop() and not setup(). No change.
Is DAC's resolution is that poor ( roughly 12% off ), or am I doing something wrong ?

Did you measure the actual supply voltage of the ESP32? It's not necessarily exactly 3.3V. Also, the ADC in the ESP32 can be off by + or - 6%, IIRC, and it isn't linear either; it needs calibrating before using.

@ocrdu - Yes, it measures 3.29v on ESP (close enough ). Do you think 12% is a calibrations error ? seems to me a bit too much ( 5% sounds reasonable ).

try connecting the GPIO pin to the supply voltage of the ESP32 (3.3V) through a resistor and see if it becomes the maximum value. Maybe there is some flux left on the pin or something that affects it's response to voltage.

@Coder_fox - Did already connect directly 3.3v pin directly to 36 pin (not using a resistor though ), and got 4095 as expected.

it looks like it should be about 2200 to hit 1.97v: https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2018/08/ADC-non-linear-768x474.png?resize=768%2C474&ssl=1  The absolute accuracy actually doesn't much matter, you just have to figure out what your MCU spits out. feed the ADC 1.00v and 2.50v, take the readings, then calc the code/volt slope. you can then read any battery voltages quite accurately between 2 and 5 volts: it's pretty linear in the middle range like that.


text:
Combining code for multiple sensors in one program (Arduino)
I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.
Here are the sketches:
Gas sensor MQ2 code :
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);

This is the DHT11 code :
#include <SimpleDHT.h>

int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
    // start working...
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Data");
}

void loop() {

  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared.  Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
  Serial.println("Starting");
}

void loop() {
  int analogSensor = analogRead(smokeA0);
  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop().  This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      Serial.begin(9600);
      Serial.println("Starting");
    }

void loop1(){
   int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

void loop2(){
  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

void loop() {
  loop1();
  loop2();
}


text:
Addresible led delay for 24 hours with arduino uno
Im working on a project with my addresible led strip and arduino uno
I need 3 leds on the strip to light for 24 hours and then the next 3 leds on the strip should light up for 24 hours and so on.
Can somone help me with the code

Can you show us the code you've written so far?

Im new to arduino if someone can just start me off with the code it will be a big help
Thanks

I know how to turn on and off.

@user57550 - Start with the BlinkWithoutDelay example that comes with the IDE. Once you have that sketch turning the LED on and off every 24 hours, edit your question and add the sketch.

@VE7JRO thanks for your jelp

turn on 3 .. wait 5 seconds ... turn on next 3 ... wait 5 seconds ... repeat .... when you get that going, increase the wait time

Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named How to Ask. You might also want to learn about minimal reproducible example and how to format your question.


text:
Timer 1 Arduino - Create 2 Timers
I’m trying to output 2 separate frequencies using 2 output pins from an Arduino using the Timer 1 library. A snippet of the code is show below.
void setup()
{
 Serial.begin(9600);
 pinMode(button,INPUT_PULLUP);
 pinMode(button2,INPUT_PULLUP);
 pinMode(sig_out, OUTPUT);
 pinMode(sig_out2, OUTPUT);
Timer1.initialize(1000);
Timer1.pwm(sig_out,512,period);
Timer1.pwm(sig_out2,512,period2);
}

The issue is the way I’ve wrote this makes sense as I’ve initialised 2 outputs and 2 inputs but the ‘period’ is getting overwritten as there’s 1 timer and I’m not sure how to stop this. I was thinking about storing them in variables (like 'T1=' 'T2=') but it would still use the same timer.
I just wanted to know if there’s a way to use 2 timers so the Arduino outputs the frequencies separately.

@Jack B How would I use the other ones?

The Timer1 library only supports... Timer 1! So you only have one
hardware timer available. If you are using an Arduino Uno or anything
similar, you have a couple of other timers. However, unlike
Timer 1, which is a 16-bit timer, the others are 8-bit only. This
means they are very limited in the range and precision of the
frequencies they can generate. If you have an Arduino Mega, then you
have a few other 16-bit timers available. You may want to search for a
library called Timer3, which should work just like Timer1, while using
the 16-bit Timer 3.
If you don't find any suitable library, you may still be able to
generate your two signals using only Timer 1. Here is the trick:

set both PWM outputs to “toggle on compare match”
enable both compare match interrupts
in each of these ISRs, advance the compare match register by half a
period of the corresponding signal.

For doing this you will need to dig into the low-level details of how a
timer actually works. I recommend you start by reading the
Timers and counters tutorial by Nick Gammon.
Take the time to read and
study this. It's not a topic you will be able to master in just a
couple of hours.


text:
Frequency Doesn't increase when Button Is Pressed
I’m trying to output a frequency that can be increased and decreased by using 2 buttons.  I’m trying to first of all configure the first button (which increases the frequency). I’m trying to also add button denouncing to not get incorrect button states. I’ve commented out anything that relates to button 2.
#include <TimerOne.h>
//Button States
boolean buttonState = LOW;
//boolean buttonState2 = LOW;

 boolean oldbutton1state = LOW;
//boolean oldbutton2state = LOW;

boolean newbutton1state = LOW;
//boolean newbutton2state = LOW;

//Time period in ms (T)
int period = 1000;
//int period2 = 1000;
float period_float = 1000.0;

//Output pins
int sig_out = 9;
//int sig_out2 = 10;

//Input Pins
int button =2;
//int button2 =3;

void setup()
{
  Serial.begin(9600);
  pinMode(button,INPUT_PULLUP);
  //pinMode(button2,INPUT_PULLUP);
  pinMode(sig_out, OUTPUT);
  //pinMode(sig_out2, OUTPUT);
  Timer1.initialize(1000);
  Timer1.pwm(sig_out,512,period);
  //Timer1.pwm(sig_out2,512,period2);
 }

void loop()
{
   buttonState = digitalRead(button);
   //buttonState2 = digitalRead(button2);
   newbutton1state = debounceButton(buttonState);

    if ((newbutton1state != oldbutton1state) && (newbutton1state == HIGH))
 {
       oldbutton1state = newbutton1state;

     float freq_change = 100.0/1000000.0;
  Serial.println(freq_change);

  period_float = (period_float)/(1+(period_float*freq_change));
  Timer1.setPeriod(period_float);
  Serial.println(period_float);

  Timer1.pwm(9, 512);
  buttonState=LOW;
  Serial.print("Signal 1 Frequency: ");
  float freq = 1000000.0/(period_float);
  Serial.print(freq);
  Serial.println("Hz");

  delay(100);
   }
}

boolean debounceButton(boolean state)
{
  boolean stateNow = digitalRead(button);
  if(state!=stateNow)
  {
    delay(50);
    stateNow = digitalRead(button);
  }
  return stateNow;
}

The issue is, when I load the code onto the Arduino, a 1KHz signal is being outputted, but every time I press button, nothing happens. I just wanted to know if anyone could shed light onto this issue. I think it may be due to the debouncing function (that it doesn’t work properly).

Did you try using a debouncing library?

why do you compare to HIGH? you have INPUT_PULLUP. the input should be always HIGH unless the button grounds the pin

Should i compare to LOW?

how did you wire the buttons? do hey have pull-up or pull-down or do you want to use the internal pull-up?

I have used the pull up formation for the button. So one button pin to ground and a pull up resistor at the other pin

You should use INPUT_PULLUP mode, or add a pull-up resistor, but not both. (INPUT_PULLUP mode internally connects a weak pull-up resistor to the pin, so when you use that mode you don't need an external pull-up resistor. You could probably use both, but then you draw more current than you need to when the button is pressed.)

then pin is LOW if button is pushed


text:
ArduinoJSON v6 - return a StaticJsonDocument from a function
I'm reading a stored JSON file from an ESP8266. I wish to return it as a StaticJsonDocument for further use.
return it at the end of function was done OK, but I need to assign it for document.
#include <ArduinoJson.h>
#include "FS.h"
#define filename "file.json"

StaticJsonDocument<200> doc;

void createJSON() {
        doc["sensor"] = "gps";
        doc["time"] = 1351824120;

        JsonArray data = doc.createNestedArray("data");
        data.add(48.756080);
        data.add(2.302038);
}

StaticJsonDocument<512> readJSON_file(){
        StaticJsonDocument<512> read_doc;
        File readFile = SPIFFS.open(filename, "r");
        DeserializationError error = deserializeJson(read_doc, readFile);
        if (error)
                Serial.println(F("Failed to read file, using default configuration"));

        serializeJson(read_doc, Serial);

        return read_doc;
}

void setup() {
        Serial.begin(9600);
        if (!SPIFFS.begin()) {
                Serial.println("Failed to mount file system");
        }

serializeJsonPretty(readJSON_file(),Serial);
}

void loop() {
        // not used in this example
}

try StaticJsonDocument<512> doc = readJSON_file(); serializeJsonPretty(doc,Serial); (= will copy the object)

but your serializeJsonPretty(readJSON_file(),Serial); works too. a temporary object will be created for the parameter

yes, that I checked.

I would avoid a copy and supply the buffer as parameter to readJSON_file

I need to update values in json files stored in ESP8266, and then saving it again...

why not readJSON_file(JsonDocument& doc)?

@Juraj - you ROCK!

@Juraj can you please post your answer ?


text:
AttachInterrupt - fail to initiate inside a class
I'm trying to create a class that uses attachInterrupt, but get this error msg:
 In member function 'void ledDoor::attach()':
ClosetLedStrip:31:82: error: invalid use of non-static member function
         attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
                                                                                ^
exit status 1
invalid use of non-static member function

I found few answers regarding static member, but it was not clear for my needs.
Appreciate help,
#define USE_SLEEP true

#if USE_SLEEP
#include <avr/sleep.h>
#endif

#define sensorPin_1 2
#define sensorPin_2 3
#define RelayON HIGH
#define doorOpen HIGH

#define pwrdown_timeOut 10*(1000*60) // mins to powerdown

// volatile boolean detectDoor_1_Open = false;
//volatile boolean detectDoor_2_Open = false;
const int relayPin1 = 4;
const int relayPin2 = 5;

class ledDoor {

private:
int _sensorPin;
int _interruptPin;
int _relPin;

void  attach(){
        attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
}

void detection_door(){
    #if USE_SLEEP
        sleep_disable();
    #endif

        detachInterrupt(digitalPinToInterrupt(_sensorPin));
        if (digitalRead(_sensorPin) == doorOpen) {
                _doorOpen = true;
        }
        else {// trun off
                _doorOpen = false;
        }
        attach();
}

public:
bool volatile _doorOpen;
ledDoor(int sensorPin, int relPin){
        _sensorPin=sensorPin;
        _relPin=relPin;

        pinMode(_relPin, OUTPUT);
        pinMode(_sensorPin, INPUT); // sensor io
        attach();
}
void go2sleep() {
  #if USE_SLEEP
        sleep_enable();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_cpu();
  #endif

}
void switchLeds(){
        if (_doorOpen == true) {
                digitalWrite(_relPin, RelayON);
        }
        else{
                digitalWrite(_relPin, !RelayON);
        }
}

};

ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void setup() {
        Serial.begin(9600);
        Serial.println("UP");
}

void loop() {
        door1.switchLeds();
        door2.switchLeds();

  #if USE_SLEEP
        door1.go2sleep();
        door2.go2sleep();
  #endif
}

perhaps the reason that you cannot find a satisfactory answer is because you do not ask a question

Firstly, if detection_door is a non-static member function, then C++ simply has no such expression syntax as just detection_door. Such functions have to either be called (with () operator) or be taken address of (with & operator). You can't just say detection_door. That's meaningless, which is what the compiler is telling you.
Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.
I see that you have multiple ledDoor objects that you want to attach to interrupts independently.
At the level of attachInterrupt and void (void) handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level attachInterrupt mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way Servo.h handles multiple servos, but it is more complicated.)
For this reason, in your case, as long as you want to stay at attachInterrupt level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects
ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}

and then just attach these handlers to your desired pins in a regular way.
static in this case can only change things in a purely cosmetic way.

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows
constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};

And somewhere in one of the .cpp files
// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};

This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of digitalPinToInterrupt) for indexing instead of pin number.
The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of ledDoor::handler<> template and instead initialize the HANDLERS array as
void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};

Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described here.

Where do you write ‘AttachInterrupt’?

@Guy . D: Wherever you are ready to do that. In setup(), for example.


text:
Fail to obtain Sizeof Array
I have a nested array, but I get only the correct size of the first one.
I use this as a reference Arduino sizeOf
int clockOn_0 [] = {19,0,0};
int clockOn_1 [] = {20,0,0};

int clockOff_0[] = {6,0,0};
int clockOff_1[] = {22,0,0};

int clock_flag_0[] = {0};
int clock_flag_1[] = {0};

int *dailyTO0[] = {clockOn_0,clockOff_0, clock_flag_0};
int *dailyTO1[] = {clockOn_1,clockOff_1, clock_flag_1};
int **test[] = {dailyTO0,dailyTO1};

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

  Serial.println("\n");

  for (int m=0; m<sizeof(test)/sizeof(test[0]);m++){
    for (int n=0; n<(sizeof(test[m])/sizeof(test[m][0]));n++){
      for (int i=0; i<(sizeof(test[m][n])/sizeof(test[m][n][0]));i++){
        Serial.println(test[m][n][i]);
      }
    }
  }

}

void loop() {
  // put your main code here, to run repeatedly:
}
This is the result:
⸮Hpxy⸮ $08⸮x$:⸮⸮
23:29:40.059 ->
23:29:40.059 -> 19
23:29:40.059 -> 20

sizeof(test[m]) is sizeof of the pointer. because you have an array of pointers, not an array of arrays. this is where array is not like pointer

but flag field consists only 1 item- I can’t use always with size of first element

the element is a pointer, not an array. (sorry, I edited the first comment, while you wrote yours)

In case of pointers- how can it be done?

you can use nested static initialized arrays like {{},{}}, or use defines or costants for the sizes

I think you are looking for a record, struct. Something like struct clock_t { int on[3]; int off[3]; bool flag; }; and then a vector clock_t clock[2] = { .... };


text:
Read the value of a register in arduino
I want to read the value of the register (8-bit). In particular I want to read the values of:

The Timer/Counter - TCNT0 ( Adress 0x26 (0x46) )
The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?

How about just using them in your program? You can use the register names directly

@chrisl So is the output of Serial.print(TCNT0, BIN) the current value (in binary) of the register?

Yes, that should work. You see much code on the web, where timers are configured by directly writing to the registers. You can try it. Write a value to a register and read it back. Though, if you are using the Arduino core, the timer0 counter will change, because it is used for millis() and siblings. You can try it with a currently disabled timer.

To convert my comments to an answer:
You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: TCNT0 = 0;). Be sure to look into the datasheet, to check the behavior of that register.

As noted, do check the datasheet -- some register flags are cleared (zeroed) by writing a 1 to them.


text:
Why is Arduino I2C so sensitive to RFI/EMI?
I have a 2-motor robot project that uses a MP6050 for relative heading (yaw) measurements, and I'm having problems with the I2C bus when the motors are running.  I have done most of the things suggested here and elsewhere; 2.2K pullups vs default, shortest possible (3cm) I2C wires, MPU6050 as far away from the motor drivers as possible, reduced I2C clock speed to 100KHz, etc, etc (for additional details, see my blog post on the subject).
So, my question is, why is the I2C bus so sensitive to RFI/EMI, especially with 2.2K pullups to +5V?  Looking at the levels with my O'scope shows a 0-4.6V swing, so it's hard to believe that EMI-induced currents could be high enough across 2.2K to pull the 'high' level low enough to be considered a '0', so something else must be going on.  Maybe the EMI is getting into the MPU6050 output driver circuit, causing it to turn off?  If so, maybe capacitive bypasses on the I2C lines would help.  Any ideas?  Are other IMU modules less susceptible to motor driver EMI?
TIA,
Frank

Is it an original arduino? Have you considered ESP8266/32 as an alternative? These have shielded chips.

I had not considered this at all.  I ordered a development board from Adafruit and will give it a try ;-)

Put a ground plate between your data lines and the power+signal lines used to drive the motor. A GPS ground plate is fine, see link below. You can just cut a piece of metal sheet to fit, or even use folded metal foil connected to ground. Motors are just noisy, and I2C is sensitive. Even updating a I2C LCD can cause noise. I like to use shielded wire (like for headphone- or HDMI cable) if my data lines are more than an inch long. You can shield lines with metal foil and heatshrink, but that’s a mess.
Use an opto-isolator to turn on your motors if a ground plate is not enough. If they only drive in one direction, add a catch diode and a 330pF cap to trim the noise. But they are probably most noisy when running. Good luck with that.
https://www.imnasa.com/en/ground-plate-200x64x12mm-for-gps-etc.html


text:
give a class's function name as a parameter
I'm trying code using FastLed library to have a 3 state ( color or brightness ) led strip, using a physical input switch, while each press will change leds color, using a predefined list.
code below demonstrate  1) create a colorPallete of two colors 2) try to use it in loop with no success.
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 1

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 3
//#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];
int colorSelctor = 0;
int birughtSelector = 25;
int inputPin = 13;
char *colorPallete[2] = {"Red","Blue"};

void setup() {
  // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  pinMode(inputPin, INPUT_PULLUP);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::colorPallete[0];
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

I don't see the color palette being used in your loop function and I wonder how a string based name could work as color definition. The only way I can interpret this question is "I need to do something, can you do it for me?" which is not the intention of StackExchange

CRGB::Red, etc, are just numbers. You need to treat them as such.
uint32_t colorPallette[2] = { CRGB::Red, CRGB::Blue };

And then:
leds[0] = colorPallete[0];

From pixeltypes.h:
/// Predefined RGB colors
typedef enum {
    AliceBlue=0xF0F8FF,
    Amethyst=0x9966CC,
    AntiqueWhite=0xFAEBD7,
    Aqua=0x00FFFF,
    Aquamarine=0x7FFFD4,
    Azure=0xF0FFFF,
    Beige=0xF5F5DC,
    Bisque=0xFFE4C4,
    Black=0x000000,
      ... etc ...
} HTMLColorCode;

It's a great workaround! (especially since I didn't understand the solution above). TNX!!!


text:
Getting different values inside vs. outside a function while using global array
function splitter is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.
for example : input string 1,2,3,4 would fill parameters array with values {"1","2","3","4"}, but  if input string is 1,2, parameters={"1","2","20","0"} while parameters[3] and parameters[2] were given its default values.
BUT
when assigning default values, inside splitter the correct values are stored in parameters but when using print_output function to show parameters values - different values are shown.
in output supplied, when input is 1,2,  default values should be pasted, to parameters[2], and parameters[3] , while input is 1,2,3,4 no need to use defaults.
OUTPUT:
Running string 1,2
param_2 was set to default value:20
param_3 was set to default value:0
output:
1
2
0
0
Running string 1,2,3,4
output:
1
2
3
4

CODE:
#define PARAM_AMOUNT 4
#define COLOR 1
#define LED_DELAY 20
#define BRIGHTNESS  50
#define LED_DIRECTION 0

char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

void setup() {
  Serial.begin(9600);
  Serial.println("Running string 1,2");
  splitter("1,2");
  print_output();

  Serial.println("Running string 1,2,3,4");
  splitter("1,2,3,4");
  print_output();
}

void splitter(char *inputstr) {
  char * pch;
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    parameters[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }

  //  update default values
  for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
    sprintf(parameters[n], "%d", param_def[n]);
    Serial.print("param_");
    Serial.print(n);
    Serial.print(" was set to default value:");
    Serial.println(parameters[n]);
    delay(50);
  }
}

void print_output() {
  Serial.println("output:");
  for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
    Serial.println(parameters[n]);
  }
}

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

not an error, but strange n <= PARAM_AMOUNT - 1. write n < PARAM_AMOUNT

Create a 2-dimensional array that has enough bytes or use an array with pointers so you can set the pointers to default strings. You have now a mix of those two and it is not well defined. At least write in comments what the maximum values are (how many decimal digits).

@jot - you are write for not commenting, but each parameter in range [0,100]. integer only

It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:
char parameters[PARAM_AMOUNT][PARAM_LEN];

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.
Then in splitter function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.
strcpy(parameters[i], pch); will copy the token returned by strtok into your array. pch points into inputstr and the delimiters in inputstr are replaced by 'strtok' with zeros

Thank you. But but when parameters is not a pointer array, it can't get pch value... ( I guess I'm still newbie here :( )

paramaters[i]=pch; was changed to sprintf(parameters[i],"%s",pch); now all is OK


text:
What is the minimal possible latency between arduino and PC
Case specifications:

PC OS: Debian 9, x64 arch
Starting time point: i have a 1kb buffer on arduino that i want to send to host PC
Ending time point: i have recieved the buffer in a custom written C\C++ app running on a host PC
I want to send such a buffer once a second

What is the minimal possible latency - time passed between starting and ending points? and with what communication type? (serial?)

Depends on what Arduino.

Best chance would be via Serial (i.e. USB-UART bridge) and the highest possible baud-rate (about 1 Megabit). If your MCU has WiFi or LAN maybe that's even faster, but we can't tell because you didn't tell us what MCU you are running on.

We would also need to know exactly what you mean by serial. USB->USB? TTL->RS232?

i have none by hand, otherwise i could write simple ping test and measure it by myself

RubberDuck, yes we would need to know what type of serial connection works better for realtime reaction/response. And it seems it's better known to owners/users of the platform

Someone managed to send debugging info at 5.3 Mb/s through a custom software serial implementation. At that rate a 1 KiB buffer should go through in less than 2 ms.

Isochronous USB transfers have the lowest latency. I don't, though, think latency is the term you are after.

Seems you are actually asking about transfer speeds not latency.

There is more to low-latency communication than just squirting data as fast as you can (though that is an important part of it).
One thing people often forget is that the Arduino can only (easily) do one thing at a time. While you're sending your buffer to the PC it can't be sampling and filling your buffer.  If you have a buffer which fills up over the period of 1 second and you want to send that buffer to the PC when full, what happens during the subsequent second while you're sending the buffer? The buffer can't be being filled while it's being sent.
Using a normal UART to USB connection as most of the normal Arduino boards (Uno, Mega, etc) use the fastest you can reasonably expect is around 1MBaud. That's about 100kB/s.  Less if you use a cheap Chinese clone with a CH340G.  Even at 100kB/s your 1kB buffer, if sent completely raw and in binary, would take around 10ms to transfer. But getting the computer to make any sense of that raw data would be hard. So you'd need to wrap it in some form of protocol (up to you to design that...) so you may get half that speed (or worse depending on your protocol design).
And during that time not much else can happen.
For smooth low-latency communication of data it is much more preferable to use "ping-pong" buffers and interrupt- or DMA-driven sampling of your data. That means that one buffer is receiving your data from whatever source, and the other is being sent to the PC. Once the first buffer is filled up they reverse roles. However, the little 8-bit Arduinos aren't really suited for that kind of thing:

They don't have much RAM to waste on two buffers
They don't have interrupts with priorities to allow samples to occur while sending
They don't have DMA to do background transfers of data to/from peripherals

If latency is really that critical you would be better using one of the ARM-based Arduinos, such as the Due, where you can also then take advantage of a high-speed native USB interface which can give much higher throughput than a UART connection. Your choice of USB endpoint can also influence the latency of your design:

Isochronous - Lowest latency, small packets, not guaranteed to be delivered
Interrupt - Medium latency, small packets, delivery guaranteed
Bulk - High latency, large packets, delivery guaranteed

Isochronous is used mainly for audio where you would notice the slightest delay in sound, but wouldn't necessarily notice or worry about a slight glitch in the quality. Interrupt is used for things like HID where you need it to respond to you pressing the keys on your keyboard nice and fast, but you're never sending much data (64 byte packet limit on interrupt transfers).  Bulk is used for things like CDC/ACM (Serial over USB) where you may want to tranfer lots of data but wouldn't notice if it's pausing for a few ms every now and then (HS USB has a 512 byte packet limit on bulk transfers, FS USB has a 64 byte limit).
One of the great things with a direct USB connection is that underneath it is all packet-based, so you can use that as your transfer protocol if you know what you're doing. Don't just rely on the CDC/ACM "pipe", but instead make use of the underlying USB protocol to send individual packets which the receiving program can then understand and break apart into the right data without adding any extra protocol overheads.
For more advanced USB programming the Teensy and chipKIT cores have far more sophisticated USB support than the Arduino core, so you may fancy taking a look at their offerings in the way of boards that may suit your needs better.

Thanks for such a great academic answer. Now i can formulate thing in a correct terms. I am interested in measuring USB RTT (or ping time) when operating with bidirectional Isochronous design in mind. For example, i can send like 8-byte packets with timestamp inside from host pc, and recieve it back to measure RTT, just like in ICMP echo. I bought MEGA 2560 board yesterday for that purpose. I was quite interested - what numbers could i see and is it suitable for realtime operations where decision logic is offloaded from arduino to more powerful PCs\GPUs?

it is not exactly what you ask, but yesterday I tested the speed with this sketch:
void setup() {
  Serial.begin(460800);
  delay(5000);
}

void loop() {
  Serial.println();
  unsigned long start = millis();
  for (unsigned long i = 0; i < 1000000L; i++) {
    Serial.write('A');
  }
  Serial.flush();
  Serial.println();
  Serial.println(millis() - start);
  while(true);
}

to receive on linux to file:
stty -F /dev/ttyACM0 460800
(stty raw; cat > received.txt) < /dev/ttyACM0

the sketch measured 20000 ms to push that 1MB over Serial. the Arduino is Mega 2560. at 921600 baud not all data were transfered.
EDIT: Nano 328p clone with CH340 complete only at 230400 baud in 45000 ms

could you run some simple ping (RTT) test for me please? i have no platform by hands. test is the following: 1) arduino must send back just what it recieves, and 2) host runs clock_gettime() to get its current 64-bit timestamp and sends it to arduino, and 3) when it recieves timestamp difference (RTT) and displays it.

clock_gettime() has near microseconds precision so its would be good estimate of RTT for realtime application


text:
How to bridge free-running multichannel adc to serial?
I want to get meteo sensors values, and turn avr based 16mhz arduino (i have mega, but that seems not matter alot vs uno) into multichannel oscilloscope.
Task details. Desired data rate is 8(uno) to 16(mega) analog channels divide by 4 to 16 reads per second. Extra adc "speed capacity" must be spent on summing up on arduino. Prescale is almost not needed. Each reading is 32bit, lsb is always zeroed. Plus there is 0xffffffff between packets (easiest binary proto, i really hate those ascii low-quality slow shit, but this is personal and offtopic). So now you got the setup and purpose, lest get down to my simple sketch
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// packet starts after indicator and goes before next such indicator.
const long packetStartIndicator = 0xFFFFFFFFl;

// values are fixed point ints 0..65534 (with LSB always cleared)
// such descision is made because least significant bit almast always == noise;
// also its just easist pck splitting scheme
const long packetValueMask = 0xFFFFFFFEl;

const int numPins = 8;

long sensorValues[numPins+1];

// TODO: configure this from host via serial (inside setup)
int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8};
//int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15};

// 1 reading is 10 bit. we can make 2^6==64 readings and sum them up (to top up to full 16 bit, to make kind of digital expoure)
// upd. 1 reading is counted as 16 bit, for host convenience (no matter or real adc)
// sum up like 256 of 16-bit readings to get 24bit value. send as 32bit long variable.
const int adcOrder = 10;
const int readingsOrder = 8;
const int targetOrder = 24;
const int numReadings = 1 << readingsOrder; //64;

void setup() {
  // TODO: reset ADCSRA, or it would not work. Also: get clue on free run mode
// sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
// for Arduino Uno ADC clock is 16 MHz and a conversion takes 13 clock cycles
//ADCSRA |= (1 << ADPS2) | (1 << ADPS0);    // 32 prescaler for 38.5 KHz
//ADCSRA |= (1 << ADPS2);                     // 16 prescaler for 76.9 KHz
//ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz

//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 32 for 38.5 KHz
//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); cbi(ADCSRA,ADPS0); // set prescale to 16 for 76.9 KHz
//cbi(ADCSRA,ADPS2); sbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 8 for 153.8 KHz

  sensorValues[numPins] = packetStartIndicator;
  //analogReadResolution(10);
  Serial.begin(115200, SERIAL_8N1);
  //Serial.begin(250000, SERIAL_8N1);
  //Serial.begin(500000, SERIAL_8N1);
}

void zero_values() {
  int i;
  for(i=0; i<numPins; i++) {
    sensorValues[i] = 0;
  }
}

void clear_lsb() {
  int i;
  int shiftOrder = targetOrder - (adcOrder + readingsOrder);
  for(i=0; i<numPins; i++) {
    sensorValues[i] <<= shiftOrder;
    sensorValues[i] &= packetValueMask;
  }
}

void serial_write() {
  Serial.write( (uint8_t*)sensorValues, sizeof(long)*(numPins+1) );
}

void loop() {
  int i, j;
  zero_values();
  for(i=0; i<numPins; i++) {
    for (j=0;j<numReadings; j++) {
      sensorValues[i] += analogRead(pinNumbers[i]);
    }
  }
  clear_lsb();
  serial_write();
}

I am weak with reading avr datasheets and lacking of knowledge on internals. My question is tied with my desire to switch it to freerun mode. I really dislike analogRead, seems it was written by real juniors, and is real slow. AFAIK free run mode is something when you have interrupt function running when conversion is done. I feel (dont know but really feel) that working with serial inside interrupt is a bad idea. How, in somple words, this can be reworked to event-based ISR with sending over serial when you would encounter inside your interrupt following: currentPin == lastPin && currentReading == numReading means you have summed up desired bumber of readings, and this is last pin, so its time to post it over serial.

Can you elucidate for us which parts of analogRead you feel are "junior".

In the Arduino environment sending data over serial inside an interrupt is seldom a good idea. That's not to say it's impossible, you just need to keep certain caveats in mind.
The chief of which is that when the TX buffer fills up everything will lock up.
So with that in mind, if you can guarantee that all your data from one interrupt will be completely sent out before the next interrupt occurs then sending serial in an interrupt can be used.
And yes, analogRead(), like many things in the Arduino API, is not fast. It's not intended to be fast. It is, though, intended to be simple.  And also like many things in the Arduino API it's easy to out-grow them.
I am not familiar with the Atmel ADC registers (preferring PIC32 to AVR any day...) but looking at the datasheet I can see a few points of interest.

First set the trigger source to "free running" (ADCSRB):

Bit 2:0 – ADTS2:0: ADC Auto Trigger Source

If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion will be triggered by the rising edge of
  the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching
  to Free Running mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set.

Then set it to use the trigger source for starting conversions (ADCSRA):

Bit 5 – ADATE: ADC Auto Trigger Enable

When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive
  edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in
  ADCSRB.

And enable interrupts (ADCSRA):

Bit 3 – ADIE: ADC Interrupt Enable

When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated

Alternatively you could set it to use a timer for the trigger source so you have finer control over when a conversion is performed. That will help you to ensure that all of the previous data set has been sent over serial before the next interrupt occurs.

"if you can guarantee that all your data from one interrupt will be completely sent out before the next interrupt occurs" I can just gurantee that for 11500 baud/s == 359.375 longs/second. I can send each long when it's adc is fired, and i need to swotch to another send accumulated A0->send A1->..->send A7->send 0xffffffff->send A0 So ITS BEST and most lightweight, if i could send inside interrupt.

So i can fire 39.93 of those (8+1)xlong readings per seconds. I just need 4 to 16 times per second. So it's guranteed that serial bus is free 30% to 90% of time to send whatever I want. I cant gurantee implementation, and I dont know it, and.. (I dont want to know it, i want just to use it efficiently) So I asked how to fire something from inside ISR without breaking arduino to hell..

The serial code is pretty efficient. There's a TX circular buffer and the sending from that buffer is all interrupt driven. write() blocks if there is no room in the buffer, and if that happens in an interrupt then you're screwed. As long as you make sure that can't happen (less than 64 bytes written between each ADC interrupt that writes data to serial) then you'll be fine.

So ARE you making me sure that writing send.serial.tx from some isr is just straightforward and fine enough? (if i gurantee that data send rate is low enoughh? (to wat degree should it be fine? 0.9 bandwith == fine? 0.3 == fine? or wat? how fast must i send to be fine and not dig into datashit? i dont want to, i just know that its right away and i go with it!))

If it will work i'll accept. Here is just prattical impl question to theoretical knowers, so to what degree is it guranteed to send serial from isr, or should i make some timer, sync and another loop shitcode? (felt like not. i send serial from interrupt, no need for any other kind of loop, pretty straight tast!) Also if this is a loopless ADC solution, could you please post to arduino beginners, what should they post in their main? sleep? why? could you post some code plxz!?

If you have nothing to do in loop() then do nothing in loop(). You don't need to do anything special, just leave it empty.  There is a slight delay between each byte sending as the ISR retrieves and queues the next byte, so at 115200 baud you can send maybe 11000 bytes per second. If you're sending 8 bytes then 1375 sendings is your absolute limit. But you want to give yourself a bit of leeway to be safe. So running no more than 1000 samples per second would be about right.

Does atmega has some kind of sleep operation? In a regular pc if you "do nothing in a loop" it consumes 100% core and wastes power. its far more complex and you have to give os sheduler a hint to put core to "sleep until interrupt happens". Is here something like this?

@xakepp35 It does have "sleep" modes, but they are for a different purpose. There is no concept of "do nothing". It always does something, unless the chip is put to sleep, where nothing (or very little) happens until some external stimulus wakes it up.


text:
FastLed LED Strip Output Checksum
I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.
I am using the FastLed library and it doesn't appear that this has been done.
The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.
I am using an Arduino Due with WS2812B LED strip.

here is the data sheet .... http://www.seeedstudio.com/document/pdf/WS2812B%20Datasheet.pdf .... if you have 20 LEDs, you have to start to load the 21st LED before you see the output from the last one (20th) .... i do not think that you actually have to send 24 bits to the non-existent 21st LED

the timings are very fast and might be hard to read to inspect for bugs. a CDS on the last LED could detect erratic flashing, ands easy to consume w/MCUs, or maybe even an IC like a 555 missing edge detector.

another thought .... maybe use this for the 21st LED (see my previous post).... https://cdn-shop.adafruit.com/datasheets/WS2811.pdf ..... use three optocouplers instead of LEDs .... always send black to the 21st LED ... if any other values other than zero are received, then one or more of the optocouplers will conduct and cause a reset ............. you could also use a microcontroller to monitor the output of the LED string

Maybe the simplest solution would be to always set the last LED to black and place a photo resistor on top of it. If there is ever light output, I will know that the LED strip is malfunctioning.

Look at timing on sheet 4 of the datasheet, and the times on sheet 3
A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High
A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.
To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.
A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.
Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.

I don't think LED strips support this feature, however, probably there is a voltage reduction depending on how many LEDs are on. So you could check the voltage at the end of the strip, based on the LEDs which are on (assuming you store this) and compare the values.

WS2812 strips have a data out pin that outputs a copy of every input bit past the (24×n)-th, where n is the number of LEDs in the strip.


text:
What is the output of A0 - A5?
I'm new to Arduino Uno, When I run this piece of code, I get numbers 340 to 370.
This is my question, why it returns 340 to 370 which correspond to 1.66 to 1.80 actual voltage? since I don't have any input equipment plugged into these pins so it must return zero voltage if i'm right in other words why default values in these pins are in this range of numbers ?
void loop() {
int val = analogRead(A0) ; //A1, A2 ...
Serial.println(val) ;

}

You will get varying values on each read. A pin’s input is said to be floating if nothing is connected, which in simple terms can be explained as it just acting as an antenna for whatever electric noise is present in your environment. Its state is unknown, and utterly meaningless. If you hold a spinning electric motor close to the pin, you can see the values rise and fall more clearly.
Use a high value (10K or more) pull-down or pull-up resistor to partially mitigate this jitter. A pull-down would bring the read value down to around 0, and a pull-up would bring it up to around 1023.
Furthermore, it’s a good idea to always smoothen out analogRead (5-10 reads, ~25-50ms apart, average the values out) to get a good reading if precision is important. This is especially valid if you use longer wires, have an unshielded case, or use a switched mode power supply. Twisting the wires (GND and wiper IIRC, otherwise correct me) to a potentiometer helps.
Edit: You can use pinMode( A0, INPUT_PULLUP ); - it provides a 20-50Kohm pull-up, though I don’t trust this and always use 1/4W resistors instead. It saves space though, and is quite handy.

Thanks for your clear explanation, however as I said I'm new to electronic fields, and I have another question, what does happen when I use a 1 mega ohm resistors. On my case I wanna use knock sensor and I found it in every tutorial to use a 1 m ohm resistor to work properly. but I use 6k ohm resistor and that does not work correctly. and signals are falling up and down accidently and when I plug my 6k resistor to the ground and A0 its voltage goes to 0

@shahingh Get a 1Mohm resistor

@shahingh ... or connect 167 6Kohm resistors in series:/

I think I got : )

Please note that INPUT_PULLDOWN is not available on AVR-based boards. INPUT_PULLUP works both on AVR and SAMD boards.


text:
Read both battery voltage and analog sensor value with NodeMCU ESP8266
I have a soil sensor that reports value once every 5 minutes, deepsleep in between.
Is there a way to also report battery voltage (with ESP.getVcc())?
To get the battery voltage reading to work I need to set ADC_MODE(ADC_VCC); but that disables the reading of the sensor.

does the ADC_VCC use the same channel on the ADC that your sensor is using? Can you use another channel?

can you set the mode to vcc after you take a sample and before you sleep?

that disables the reading of the sensor ... so enable it after you read the voltage ... what is the problem?

@ChadG esp8266 has only one analog pin

you can use a digital pin and RC circuit to precisely
measure voltage as a function of time

to read VCC voltage, ADC pin must be kept unconnected. Additionally, the following line has to be added to the sketch:
  ADC_MODE(ADC_VCC);

The setting of a purpose of the analog pin of esp8266 is at low level and must be projected into the compiled binary. It can't be changed at runtime.
On esp8266 if you want to use the power sensing or to have more ADC you must use an external I2C ADC.
reference

Was afraid of that, but thanks for confirming.

I found a solution that I believe works great.
Although the ADC_MODE macro cannot be modified after the board is started, we can actually set its integer input as the output of a function and then use RTC memory to trigger different modes, depending for example on how many times the board has been started.
#include "ESP8266WiFi.h"
#define QUERY_VCC_INTERVAL  10

int adc_selection;
ADC_MODE(get_adc());

int get_adc(){

  typedef struct {
  uint32_t adc_mode;
  uint32_t count;
  } rtcStore;

  rtcStore rtcMem;

  system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));

  if ((rtcMem.adc_mode != ADC_VCC) && (rtcMem.adc_mode != ADC_TOUT)) return ADC_TOUT;

  return rtcMem.adc_mode;
}

int get_adc_and_write_change(){

  typedef struct {
  uint32_t adc_mode;
  uint32_t count;
  } rtcStore;

  int a;
  rtcStore rtcMem;

  system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));
  a = rtcMem.adc_mode;

  Serial.print("CYCLE NUMBER: ");
  Serial.println(rtcMem.count);

  if (rtcMem.count > QUERY_VCC_INTERVAL){
        rtcMem.adc_mode = ADC_VCC;
        rtcMem.count = 0;
  } else {
        rtcMem.adc_mode = ADC_TOUT;
        rtcMem.count++;
  }

  system_rtc_mem_write(100, &rtcMem, sizeof(rtcMem));

  return a;

}

void setup() {

  int vcc;

  Serial.begin(9600);
  Serial.println(" ---------- ");
  delay(1000);

  adc_selection = get_adc_and_write_change();
  Serial.print("VALUE FOR ADC MODE WAS: ");
  Serial.println(adc_selection);

  vcc = ESP.getVcc();
  Serial.print("VALUE WHEN READING VCC: ");
  Serial.println(vcc);

  if (adc_selection == ADC_TOUT){
    Serial.println("VCC SHOULD BE 65535");
   } else {
    Serial.println("VCC SHOULD NOT BE 65535");
   }

  Serial.println("RESET BOARD TO CONTINUE");
  delay(1000);

}

void loop() {
}

Note that the function gets executed very early on the board startup, so we cannot even count on using or writing to global variable definitions of the script's code. This is why all structures are defined within the get_adc function.
The above code triggers ADC_MODE(ADC_VCC) for every 10 times that ADC_MODE(ADC_TOUT) is triggered. This allows me to read analogue sensors for 10 times after the board is woken up from deep sleep and then read the VCC level to gauge the battery voltage once every 10 times.
Note also that to have VCC readings work correctly I need to connect analogue sensor power to a digital pin and use that to power the sensors ON/OFF as needed.
I have tested the above code with a NodeMCU v3, on the Arduino IDE.

Great solution from Danielfp. Idon't think the typedef struct needs to be defined twice though. It works for me when above the code.


text:
Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader
I am making a mechanical keyboard using Atmel's pro micro as the controller.  I decided I would try to replace it's bootloader, as the one it ships with doesn't seem compatible with QMK's RESET keycode (which is supposed to put the controller into DFU mode).
Clearly I didn't know what I was doing, as the controller no longer seems to be recognized when I plug it in via USB - MicroUSB.
If I recall correctly, this is the command I used to attempt to flash the bootloader:
"sudo avrdude -p atmega32u4 -P /dev/ttyACM0 -c avr109 -U flash:w:Caterina-promicro16.hex"
At this time, it seems likely to me that the issue is that I over-wrote the bootloader (or some portion of it) and failed to replace it with an appropriate alternative.  Is this correct?  Is there any way to correct my error through a USB-MicroUSB connection at this point, or will I need to buy some sort of programmer?  All the leds light up.

sometimes the USB freaks out and gives up, try rebooting the PC.

You cannot load the bootloader over USB, that job needs to be done with an in-serial-programmer (ISP).  You could have stopped the board working if you wrote the wrong fuses, e.g. different clock frequency.
Flashing the bootloader via ISP can be done with the Arduino IDE and there are lots of tutorials on the web.  Try it, will probably work for you.


text:
How to create array of references?
I have a class named timeOut dealing with timeout tasks.
I'm to write a sketch, common for Sonoff basic and Sonoff Dual, meaning that I may have 1 task for Basic and 2 tasks for Dual.
Declaring instances looks like:
timeOUT timeOut_SW0("SW0",TIMEOUT_SW0);
timeOUT timeOut_SW0("SW1",TIMEOUT_SW1);

for code simplicity I'd rather create an array of references and call it using a for loop:
timeOUT TO[]={timeOut_SW0,timeOut_SW1};

is it the right way to call it as a reference ?

a few questions back I answered a similar question with example https://arduino.stackexchange.com/questions/67170/hardwareserial-indexing-array

is this a school assignment?

@jsotola No it is not

You can't. The C++ language doesn't support arrays of
references. You have the choice to either create an array of
objects:
timeOUT TO[] = {timeOUT("SW0",TIMEOUT_SW0), timeOUT("SW1",TIMEOUT_SW1);}

or an array of pointers:
timeOUT *TO[] = { &timeOut_SW0, &timeOut_SW1 };

timeout_Switch:243:34: error: request for member 'remain' in 'TO[i]', which is of pointer type 'timeOUT*' (maybe you meant to use '->' ?)                          if(TO[i].remain()>0) {                                   ^

I upvoted this answer, and going to delete mine since it's wrong.

I chose 2nd option you offered


text:
2 instanced of ESP8266Ping
I'm using ESP8266Ping lib inside my iot lib which hanldes Wifi connectivity and MQTT messages. Since it create its own instance called Ping when calling #include <ESP8266Ping.h>- it had to be place in iot.cpp.
I writing another library, IPmonitor which checks clients on the network (using pings), I wanted to use ESP8266Ping again.
My sketch file, create an instance of iot and IPmonitor for check/ log errors on monitored clients.
But I get error of using the same library twice.
I guess that since ESP8366Ping.h library is defined it creates an instance of the class ( see mark below ):
class PingClass {
  public:
    PingClass();

    bool ping(IPAddress dest,   byte count = 5);
    bool ping(const char* host, byte count = 5);

    int averageTime();

  protected:
    static void _ping_sent_cb(void *opt, void *pdata);
    static void _ping_recv_cb(void *opt, void *pdata);

    IPAddress _dest;
    ping_option _options;

    static byte _expected_count, _errors, _success;
    static int _avg_time;
};

#include "ESP8266Ping.impl.h"
PingClass Ping;                     // <----- This

#endif

How can it be solved ?

With that library... you can't. All the code is in one big monolithic .h file. As you well know by now that is a big no-no. The author should be given a big slap on the wrists.
The closest you could do without re-writing the whole library is to just copy the class definition from the outer .h file and create an extern to the existing object - maybe make your own copy of the ESP8266Ping.h file without the #include "ESP8266Ping.impl.h" and PingClass Ping; (the latter of which you change to an extern).

Thank you. Since I don’t any future mishappens after lib update, I’ll probably use calling external function in ‘IPmonitor’ to call the relevant function from ‘iot’ class. And slapping

@Guy.D I have submitted a pull request with the required changes. You may like to test with my fork: https://github.com/majenkotech/ESP8266Ping

Well... this is very nice of you! Cheers


text:
Serial Communication between ESP8266 and Arduino ( Sofware and Hardware )
I wish to connect an Arduino ( any of 328P family ) which its 5v, with ESP8266 (ESP-01, or even NodeMCU or Wemos D1 mini ) which is 3v3 logic. My goal is that ESP8266 will be in-charge of MQTT messages and other remote abilities, while Arduino board will be in charge of UP/Off/Down rocker switch and 2 relays ( For reliability I rather have this setup ). Both MCU's code is written by me using Arduino
I Know of 2 main ways: voltage divider and level shifter ( and 3rd will be to use a 3v3 logic as pro-mini - but let's leave for now ).
My questions are:
A) Does Rx Tx need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?
B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?
C) Does SofwareSerial library is recommended (again - reliability ).

A) Does Rx Tx need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?

The point is, that often 3.3V MCUs cannot tolerate voltages significantly above that. So connecting 5V can hurt it. I've seen quite a bit of discussion online, if ESP boards are 5V tolerant or not, but I haven't seen a real investigation in this. Often you can very well get away with connecting them directly, but nobody will give you any guarantees about this. If you want to be safe, you need to add some kind of voltage transition from Arduino TX to ESP RX. The other line (ESP TX to arduino RX) is driven by the ESP with 3.3V, which is ok for the Arduino (3.3V is enough for the Arduino to see it as HIGH), so you don't need anything on this line.

B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

Since a voltage divider is passive, you get extra effects (parasitic capacitance and inductance), which limits the baudrate. Though I still got communication without errors with baudrates up to 115200 (I did not do a thorough investigation, this is just subjective experience). Electronically better would be proper level shifting (which uses transistors), but in most cases a voltage divider also works well. So I would say unless you want to use really high baudrates you are good with a voltage divider. Others can of course also provide their experience on this site.

Does SofwareSerial library is recommended (again - reliability ).

Generally a Hardware Serial interface is always better, since the communication protocol is completely handled in hardware. The code just needs to read and write the individual bytes from/to hardware registers. SoftwareSerial is used, when there is no free to use Hardware Serial interface. And it imposes some extra limits: You can only listen to one SoftwareSerial interface at any give time and you cannot use high baudrates with it (I think 115200 is already too high for it, depending on the used Arduino). Also it depends on the rest of your code (depends on your use of ISRs). So, if you have an unused hardware Serial interface on your Arduino board, you should use that. Otherwise you can use SoftwareSerial.

Just adding a little flesh to @chrisl's excellent answer with some added technical detail:

B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

The problem here is that the resistors and the input pin's capacitance form a low-pass filter. Too high a resistance and you deform the nice clean square wave of the serial data. This limits the baud rate you can reliably use. Reduce the resistor values and you increase the frequency of the filtering, thus allowing higher baud rates, but at the cost of increased current draw from the TX pin.

Does SofwareSerial library is recommended (again - reliability ).

The problem of SoftwareSerial is twofold: it's very much a "blocking" system, whereby the MCU can't be doing anything else when a byte is being either received or transmitted, and it's very picky about timing, partly because of that blocking.  There are two factors that affect the maximum speed you can use: how fast the MCU can process the incoming signal to work out what it is, and how fast the MCU can process that decoded signal to get it stored in the buffer.
While it's possible to receive reliably a byte at 115200 baud the problem comes when receiving multiple bytes rapidly. The Arduino is not always able to take that received byte and store it in the RX ringbuffer fast enough before the start bit of the next byte arrives, so it misses it. This causes corruption in the data stream.
For this reason I never recommend more than 9600 baud (or maybe 38400 at a pinch) to give the Arduino more time to process the bytes as they arrive. However that then means that more time is spent doing the sending or receiving, which blocks the rest of your program during that time for longer.
Also SoftwareSerial is strictly half duplex: when you're receiving you can't send, and when you're sending you can't receive. It's only really of any use in a "call-response" style protocol where switching between sending and receiving is predictable.

Thank you. Setting speed as 9600 is good enough for me, since esp sends AUX numeric commands to Arduino, in form of 2 digit, and acknowledged message back. So I do not expect nothing fancy.

Regarding softwareSerial, as I said- reliability at top


text:
ESP32, NTP and SW reset
After HW reset (button or power reconnect) I get the correct NTP shift, but when I use ESP.restart() via MQTT I get the correct time without 3 3 HRS shift due to Tz. What happens after SW reset that behaves in such manner and how to fix it?
bool myIOT2::_startNTP(const char *ntpServer, const char *ntpServer2)
{
    unsigned long startLoop = millis();
    while (!_NTP_updated() && (millis() - startLoop < 20000))
    {
#if defined(ESP8266)
        configTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); // configuring time offset and an NTP server
#elif defined(ESP32)
        configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
#endif
        delay(1000);
    }
    if (!_NTP_updated())
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
bool myIOT2::_NTP_updated()
{
    return now() > 1640803233;
}

Would you please add in the (relevant bits of the) application code as well?

Apparently, time in ESP32 survives a sw reset, while in ESP8266 doesn't.
So in code, which is same for both  - if clock is updated (a rough criteria that time is greater than some day in 2020 ), it skipped TZ update  configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
So after a crash and/or sending a MQTT message to reboot, time was missing TZ update.
Hope it'll help someone.
Guy


text:
Calling functions between 2 classes
Class myIOT2 contains a function that need to be called from class IPmonitoring:
bool myIOT2::checkInternet(char *externalSite, byte pings)
{
    return Ping.ping(externalSite, pings);
}

This function is needed as a pinger in IPmonitor:
void IPmonitoring::start(cb_func ping)
{

        _ping_cb = ping;
}

and this cb_func is defined by (inside IPmonitor.h):
typedef bool (*cb_func)(char *externalSite, byte pings);
cb_func _ping_cb;

inside my sketch (relevant parts only) I fail when iot.checkInternet is passed, while using a function test that calls iot.checkInternet succeeds:
myIOT2 iot;
IPmonitoring WiFi_service(ROUTER_IP, "Router");

bool test(char *a, byte b)
{
        bool x = iot.checkInternet(ROUTER_IP);
        return x;
}

void setup()
{
WiFi_service.start(iot.checkInternet); // <---- Trial a)fails
WiFi_service.start(test);              // <-----Trail b)succeeds
}

error is :
home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino: In function 'void setup()':
IPmonitor:436:45: error: no matching function for call to 'IPmonitoring::start(<unresolved overloaded function type>)'
         WiFi_service.start(iot.checkInternet);//
                                             ^
/home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:436:45: note: candidate is:
In file included from /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:2:0:
/home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note: void IPmonitoring::start(IPmonitoring::cb_func)
     void start(cb_func ping);
          ^
/home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'IPmonitoring::cb_func {aka bool (*)(char*, unsigned char)}'
Multiple libraries were found

What is done wrong ? and why test succeeds ?

Does this answer your question? Passing a method pointer

@Juraj No :( I didn't

@Juraj - mostly because Passing test succeeds

did you read that answer to the end?

@Juraj yes, but almost from start I fail to understand

the core of the problem is that a class method compiled has the object as first parameter so the parameters of the callback function don't match for cb_func

There is a fundamental difference between a simple function and a function that is a member of a class.  You can't use a function pointer to point to a member function of a class: simply because that member function also includes information about the class instance that it belongs to.
The proper C++ way to handle it is to use std::function, but the Arduino AVR compiler lacks the full STL (Standard Template Library), so that can't be used on normal Arduinos. Other cores do have it, so you may well be able to use it on the ESP8266.
If you want to make your code portable between systems that may not have the full STL then there's other tricks you have to do:

Use a wrapper function (which as you have found works), or
Make a polymorphic class and store a pointer to the instance cast to the parent class - the parent class defines the functions that are allowed to be called from the pointer.

Thank you very much for a comprehensive explanation. A) it is an ESP8366. B) wrapper function is needed for which one my member functions? C) can you please write or direct for such example ? I must say it is a bit vague for me.

The "wrapper function" is a simple function that calls the function in the object you want. Your "test" function from your example. Something like void test() { myObject.someFunction(); } - I use something similar here


text:
Fail uploading any sketch to ATtiny85 USB
I have a Digistump's ATtiny85 (probably a clone ), which fails uploading any sketch, saying: Warning: device with unknown new version of Micronucleus detected. This tool doesn't know how to upload to this new device. Updates may be available. I'm using Ubuntu 20.04 and Arduino IDE 1.8.13.
I used these guides:

Digistump's troubleshooting for linux

Kovo's blog

After using these guides, finally I stop getting this error, but when trying to upload the firmware ( last line at Kovo's ), I get this error:
`guy@desktop:~/tmp/micronucleus/upgrade$ ~/.arduino15/packages/digistump/tools/micronucleus/2.0a4/launcher -cdigispark  --timeout 60 -Uflash:w:~/tmp/micronucleus/upgrade/t85_default.hex:i
Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
> Please plug in the device (will time out in 60 seconds) ...
> Device is found!
connecting: 16% complete
connecting: 22% complete
connecting: 28% complete
connecting: 33% complete
> Device has firmware version 2.4
> Device signature: 0x1e930b
> Available space for user applications: 6522 bytes
> Suggested sleep time between sending pages: 7ms
> Whole page count: 102  page size: 64
> Erase function sleep duration: 714ms
parsing: 50% complete
> Program file is 1594 bytes too big for the bootloader!

Did someone encounter this ?

I'd probably start here: https://github.com/micronucleus/micronucleus/issues/148

from Daves Comment
need to download upgrade-t85.hex (which is not t85_default.hex) from link


text:
Power down NRF24 to conserve battery life using MOSFET
I'm using a Pro-Micro to send messages using NRF24 module from a remote location, using batteries (later on, will be recharged using solar panel).
To conserve power, Pro-Micro wakes up every 30 minutes, sends its data. My goal is to power up NRF24 module only when needed, in order to conserve power as much as possible.
For that I tried 3 ways:

Using a Relay to cut off 5V input to the NRF24 module.

Using a MOSFET FQP30N06 , connected to GND of NRF24 module.

Using NRF24's powerDown() function reduce consumption.

These are the current draw results:
a) During sleep, power consumption of Pro-Micro only is 3.4 mA ( due to LED remains ON ).
b) Pro-Micro + NRF24 module, both normal operation ~70mA.
c) Using a relay + entering Pro-Micro to Sleep mode: 6mA.
d) Using powerDown() + entering Pro-Micro to Sleep mode: 30mA.
e) Using a MOSFET + entering Pro-Micro to Sleep mode: 180mA. (yes, MOSFET turns off power to NRF24 ).
Questions:
** I have to say that my first go was for using a MOSFET, but I was amazed by the result! What is the reason for that? Can it be the when MOSFET in its OFF state consumes so much power ?
** I would like to hear from other's experience for better ways to do such.
Guy

No, MOSFET does not power off the whole NRF when it only switches the GND. There are other connections like e.g. the SPI pins that can act as grounds when they are low.

For switching the power for such a device, you should use a high side switch, meaning a P channel MOSFET for switching Vcc.

Those 70mA and 30mA look way too high to high to me. I was able to run my setup on an average of around 0.5mA, with the MCU waking up every 250µs to do a measurement and occasionally sending data via the NRF24. Putting the NRF24 in power-down mode should be sufficient bring it's power usage to almost nothing. It might be a counterfeit NRF24L01. Is the chip on your module a QFN chip, or is it under a blob of epoxy?

@PeterPaulKiefer, Yes - it was understood eventually. I also tried to put all SPI pins LOW on power off procedure, but change was not that big. Thank you!\

@chrisl - After using a relay, I was thinking just abput what you wrote, but since I've never practiced such MOSFET, I was not sure. Thank you.

@Gerben - I'm using a NRF24 ( the one with antenna. -for longer range ) and a power adapter ( example: https://www.ebay.com/itm/2Pcs-NRF24L01-Transceiver-External-Antenna-PA-LNA-Arduino-5V-Breakout-Adapter/292424165202?epid=13013735675&hash=item4415d6a752:g:fIoAAOSw8i9aamZK ).. So it is not only the NRF24 module. Does it more reasonable ?

In that case, those values sound a lot more plausible. Those have an additional amplifier, so they will probably use more power. The power adapter boards have a linear regulator, which has around 5mA of quiescent current.

@Guy.D you can't set SPI pins to LOW. You have to disable SPI first, before you can change them.

Setting the SPI pins to LOW should increase the current when only GND is off. Perhaps setting them to high could help or (much better) use it as an input to set it into a high impedance state. -- Switching off only the VCC did help in your case. But, a connected pin could also act as a fake VCC. E.g. You set it to high or an input with the internal Pull UP active. So the best way is to switch off VCC or GND or both and set all connected data and clock pins as inputs. The quality of the module does not matter. If you stop current flow with the Arduino, the module can not waste power. ;-)


text:
Fail getting readings from Radar sensor HW-MS03
I try to work with a new sensor - HW-MS03 v.06 sensor. Connecting it pin to pin (v+ to 5v, Sig to digital-input, and GND to GND ), both to Arduino Uno and ESP8266 Wemos mini, and got same results:
Only once on every port I got proper readings ( 1 for detection for 2 sec, and 0 for no- detection). Most of the time it was a solid 1.
Code was very simple , just printing its digitalRead of the designated pin.
When tried to pull-down the signal, using a 1K resistor, It never got 1 again.
To be sure it is not a malfunctioned sensor I tried with the other one I have, but again- same results.
link to purchased product
Appreciate any help.
Guy

Wow, that is some quality documentation: "Recommended qualified power supply, ie output voltage, current and ripple factor are standard power supplies, otherwise it is a movie" And the specifications link doesn't provide any info about voltage or current requirements. I think you're on your own figuring that one out.

"it is a movie....." this is the best spec I've encountered

What do you suppose the writer is trying to say? It was word salad to me.


text:
Store & retrieve parameters after sketch update
I have a Generic code for some IOT devices which vary in some parameters ( lets say it is only its MQTT name and subscriptions).
Since I use OTA to update sketch, I'm looking for a way to A) write those parameters into the ESP32/ ESP8266 FS, and B) They will survive an update.
My only solution come into mind is using an SD card which does not get erased after OTA, and I'm looking for a way doing it not involving SD or external memory.
Guy

You say "not involving ... external memory".  Does that include (adding another) I2C devices such as EEPROMs?

@st2000 some are flashed Sonoff’s and some are nodeMcu’s so I rather keep it simple and not change hardware.

There are tutorials on this which infer they are using this library.  But that library's readme says the library has been depreciated. Further, it is not clear how or if the emulated EEPROM storage remains in the same location after updating the application (aka sketch). This is an interesting question.  Does Sonoff already do this?  Maybe looking into that project will provide answers.

@st2000 perhaps writing to a certain location...?

FS is not erased by sketch OTA. and EEPROM emulation library is OK too.

Checking, people have been telling me they have been updating sketches using the eeprom library and it continues to work across updates.  @Guy.D, I think the eeprom library uses address starting from zero or 1.  So likely relative, not absolute addressing.  But I only looked at some example code.

There is no need for an SD card.
You can write all relevant parameters into a file in SPIFFS (e.g. json if you like) before starting the OTA update. During initialization you read the file and set the parameters accordingly.
SPIFFS does not get erased when doing an update (at least that's true for the OTA library that I'm using). If it does get erased in your case, there probably is an option in the OTA lib to disable flash erase, just like there is the same option when uploading a sketch via serial.

Can I upload a data file using OTA, once for each device and after uploading the sketch especially after OTA’s, will it remain?

@Guy.D You probably only need to upload the file once when you initially upload the sketch (you can use the data upload tool in the arduino IDE for this purpose). After that, the file remains in spiffs for ever and can be updated whenever you make an OTA update. Otherwise, there are many ways how you can upload this file: you can download it from your server and save it in SPIFFS, you could also send it to the ESP (which then would be a server) and write it to SPIFFS. The file really doesn't have much to do with the OTA, because it is stored in a completely different flash partition.

@Guy.D ...but yes, it will remain there. That's how I deal with persistent user data, which obviously must not be overwritten by a firmware update.


text:
Error in defining Ticker in ESP32 library
I'm using the exact piece of code in my ESP8266 library (which works OK ), but when used in a ESP32 library- I got an error:
This is the relevant code snip:
void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

and this is the error:
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp: In member function 'void myIOT32::_startWDT()':
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:333:55: error: no matching function for call to 'Ticker::attach(int, std::_Bind_helper<false, void (myIOT32::*)(), myIOT32*>::type)'
   wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
                                                       ^

ESP32 ticker attach functions take pure function pointers with at max one argument type -- not a std::function/ std::_Bind_helper that std::bind produces.
See code and types at https://github.com/espressif/arduino-esp32/blob/master/libraries/Ticker/src/Ticker.h#L38.
For the ESP8266 however, they do use a std::function:
https://github.com/esp8266/Arduino/blob/master/libraries/Ticker/src/Ticker.h#L36
And that's why it works on ESP8266 and not on ESP32 -- either adapt the Ticker library or rework your own code to not use member functions of classes.
Edit: You can easily rewrite your code to use a static helper function with one argument (the watchdog object itself) which then just calls the member function of that object. For this to work, the called function must be public. So a rewrite like
static void watchdog_timer_triggered_helper(myIOT32* watchdog) {
   //needs to be public!
   watchdog->_feedTheDog();
}

void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, &watchdog_timer_triggered_helper, this); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

Since both the ESP32 and ESP8266 versions implement the
    template<typename TArg>
    void attach(float seconds, void (*callback)(TArg), TArg arg)

templated function this should work on both platforms now.

Thank you for explaining. Can you share an example how to rework ?

@Guy.D see update.

@Maximillian  - thank you for you answer. I'm afraid your it a bit more than I understand :( , and I do not like to copy an answer without fully understand. Can you please explain more, or perhaps a more simple answer ( sorry... )

@Guy.D didn't you write the initial code with std::bind, which is more complex than the function pointer used in the answer? Anyways I suggest reading up on C++ templates (attach() is a templated function), pure function pointers and std::function in C++. I'd take some quiet lengthy text to explain that fully in my answer o_o.

to be honest, when I found that answer for 8266, I just took it as a given solution without knowing how bind work for every detail.... ( shame me :) )....

@Maximillian - Well, after a long look up ( from almost a month ) I couldn't find any exaplining example to understand your solution ( not the template part ). Can you please refer ?


text:
Minimum value of a pull-down resistor
I've just started working with the Arduino UNO SMD edition and I'm also quiet new to electronics in general. Recently I wanted to try out this tutorial https://www.arduino.cc/en/Tutorial/Button and I ran into a problem with the pull-down resistor. In the tutorial they recommend a 10kOhm resistor but I've got only 460Ohms laying around. Obviously I could link dozens of them in series but I was wondering if it is possible to replace this 10k resistor with 460 Ohms. Would that be enough? I'm assuming, that the 5V Output can supply up to 500mA (datasheet) and the ground can take up to 500mA. Following Ohms Law I = U/R given 460Ohms there should be a current of 11mA flowing. Is it correct that the ground can take this amount of current?
Hope you can answer my question and may point out mistakes i made.
Greetings Tmirror

11mA is within the limits of an Arduino pin (which is 20mA). The only problem is that it wastes more electricity while the button is pressed. This is more of a issue when running of a battery.

You are talking about an I/O pin I think. I'm talking about the 5V power supply pin, which is directly connected to the power source. This one can supply up to 500mA not 20mA. Or do I missunderstood something?

Sorry, you’re right. Disregard my first sentence. Second part is still valid. An alternative would be to use internal pull-up resistor that is in the ATMega328. That way you don’t need to add any resistor.

Thank you for your answer. So my assumption and math was correct? It's not dangerous for the Arduino (or me laugh) to only use 460 Ohms?

Your calculation was correct. No danger. Power dissipation is 50mW, so assuming you are using a regular quarter watt throughhole resistor, there is also no danger of the resistor overheating.

Why are you messing with pulldown resistors at all? Use the internal pullup resistor instead.  Connect your button between the pin and Gnd so the pin goes low when pressed.
Here's a simple code example:
byte inputPin = 2;

void setup(){
    pinMode (inputPin, INPUT_PULLUP); // turns on internal pullup
    Serial.begin(9600);
}

void loop(){
    if (digitalRead(inputPin) == LOW){
        Serial.print ("button pressed");
    }

    else {
        Serial.print ("button open");
    }

    delay(200);  // limits reading to 5 times a second to avoid flooding the PC with messages

}

i corrected the formatting of your example code .... please do not post improperly formatted code. .... correct indentation is the first thing that beginners need to learn.

How do you get the code box? When I edit the post, I don't what was added to create the code box.