text:
Arduino ESP8266 - wifi evt: 3 and wifi evt: 7 meaning?
I'm getting these in my serial port, but what does wifi evt 3 and 7 mean?
I am trying to complete this tutorial. https://youtu.be/4Z0gBG8dkqw
The PHP file is on my hosting, and the ESP reads out the temperature and humidity from the sensor so that's fine.
The serial code:
Connecting
wifi evt: 3
Connected
Temperature:
24.10
Humidity:
39.70
[hostByName] request IP for: lucasdebelder.be
[hostByName] Host: lucasdebelder.be IP: 185.182.57.81
connected
HTTP/1.1 200 OK
Date: Fri, 11 May 2018 13:14:17 GMT
Server: Apache/2
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 0
Content-Type: text/html; charset=UTF-8

�
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7

The code that I am running in Arduino.

#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_email.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

The codes are explained in this forum thread. The wifi event types are  described here (and also duplicated here, which are ultimately coming from the Espressif Non-RTOS SDK, chapter 6.2.4):
typedef enum WiFiEvent
{
    WIFI_EVENT_STAMODE_CONNECTED = 0,
    WIFI_EVENT_STAMODE_DISCONNECTED,
    WIFI_EVENT_STAMODE_AUTHMODE_CHANGE,
    WIFI_EVENT_STAMODE_GOT_IP,
    WIFI_EVENT_STAMODE_DHCP_TIMEOUT,
    WIFI_EVENT_SOFTAPMODE_STACONNECTED,
    WIFI_EVENT_SOFTAPMODE_STADISCONNECTED,
    WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED,
    WIFI_EVENT_MAX,
    WIFI_EVENT_ANY = WIFI_EVENT_MAX,
    WIFI_EVENT_MODE_CHANGE
} WiFiEvent_t;

The enum's values are increasing downwards, meaning that 7 is WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED. Receiving a probe request means that some other device has scanned the surrounding WiFi networks and your ESP answered. This indicates that your ESP is in the Software Access Point (AP) + Station (SoftAP + STA) mode. But you only want to be a station in your own WiFi network, not an access point yourself.
The output is triggered by this function.
This comment on an issue suggests that you add WiFi.mode(WIFI_STA); to your setup, like
void setup() {
  WiFi.mode(WIFI_STA);
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

Subsequently, a WiFi event 3 indicates WIFI_EVENT_STAMODE_GOT_IP. Which also makes sense because you're telling the module to connect to the WiFi, it acquires an IP over DHCP and is then fully connected. This message is harmless since it doesn't indicate an error.
You should investigate on why these debug messages are thrown in the first place. The messages are only printed if two macros are set: DEBUG_ESP_WIFI and DEBUG_ESP_PORT (see here). So something must do #define DEBUG_ESP_WIFI and #define DEBUG_ESP_PORT Serial somewhere.
This is either done in some compiler settings which you are not aware of or because you modified a header file to include this change. Either way, you can try to use the #undef pre-processor macro to remove these definitions again before including the library. Change your first line to the following:
//Try to kill the DEBUG defines
#undef DEBUG_ESP_WIFI
#undef DEBUG_ESP_PORT
#undef DEBUG_WIFI
#include <ESP8266WiFi.h>

Thanks a lot for the answer. On the second line I still get a wifi evt :3  ->Connecting
wifi evt: 3
Connected. Same as in the post I made (check the third line)

@Panic I've addressed this in an edit of my answer.

from core package 2.4.1 the debug defines can be turned on in Tools menu

@MaximilianGerhardt, SDK is the primary source of the enum

You see the "wifi" debug messages because you set in Tools menu Debug Level "WiFi". SetDebug Level "None"


text:
How can I loop my code? For example after 30 minutes?
So I have this code which records the temperature and humidity using a DHT22 sensor. After it get's the values it then sends it to a webpage using PHP $_GET method, where that gets imported into a DB and emails (using PHP). But this only happens when I upload the code to my ESP8266; how can I know build in a loop function that it sends it every 30 mins or given time?
#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_temperature.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

see BlinkWithoutDelay example

@Juraj Thanks for the answer, can you explain it a bit further? What code should I look at?

this tutorial and code ... https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

As stated in the previous answer. Code that needs to run more than one time should be called in the loop. But in this case the following solution will work as well.
You can end your setup with a call to the deepsleep(time_us) function which can be found in the ESP library. This will shutdown everything except for the on board RTC(Real Time Clock). So the circuit only draws a very little current (20 uA). This can be very useful if the circuit is powered by a battery.
The RTC has a signal on GPIO 16 (D0 on NodeMcu) which will be held HIGH while the given time is not reached. If the given time is reached the signal will be LOW.
If you connect GPIO 16 to the RST(reset) pin, this will make the ESP8266 start-up again. And thus the setup() will be executed again.

You execute the corresponding function only in the setup() function, which is called once on startup of the ESP. After that the loop() function is called repeatedly. The setup() function is meant to "setup" your code for it's functionality, which is then executed in the loop() function. For example you are begin the Wifi connection and connect to a network in there, because you need the network for your main functionality.
So you have to put the code from readSensor() until (and including) sendDataToServer() into the loop() function. This will execute this code repeatedly.
Then you have to introduce some concept of time, else your code will be executed very fast, effectively flooding your webserver. The easiest way would be to add a call to delay(30000), which would delay the code for 30s. But using delay is not considered good coding style, since it is basically busy waiting and you cannot do anything else during that time.
So to be able to add other functionalities in the future you can implement the time concept with non-blocking code. Take the BlinkWithoutDelay example from the Arduino IDE as reference. It uses the millis() function, which counts the milliseconds since the startup. You save a timestamp of the last execution of your code and wait until the difference between the current time (given by millis()) and your timestamp is greater than 30s. In this time the ESP can do other things, since it still goes through the loop() function undisrupted. Then after the timespan you execute the code and reset the timestamp to the current time.

Thanks a lot for this answer @chrisl but how can I implement something like this in my code? I can read and understand the code, but writing is something different for me. Could you try to have a look at my code? Thanks

Do you really understand, what the code does? The first part I mentioned is just cut and paste the measurement and send code from setup() to loop(). The second part is just the BlinkWithoutDelay example. You have to put the code you now have in loop() into an if(millis() - timestamp > interval) clause. This is described in the Arduino Documentation.

You really have to understand both concepts I tried to explain, or you will not be able to write your own code. Read the documentation. Do some starter tutorial for Arduino, where the setup() and loop() functions are explained. We cannot write your code for you. If something about my explanation isn't clear, I will try to explain it further.

source: Stack Exchange

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

sort: votes


text:
ESP8266 in AP Mode -determining if a station is connected
I have an ESP8266 running in AP mode using softAP and i want to conserve battery life.
I am wanting to turn on wifi and advertise SSID for 20 seconds. If no station connects to the ssid within the 20 seconds, I want to go to sleep for 1 minute, otherwise I do not sleep.
My problem is that I cannot get "WiFi.softAPgetStationNum()" working. when I build i get a message that this is not part of ESP8266WiFi class. I have attached simplified code.
Can someone help me to achieve this please?
#include <ESP8266WiFi.h>

//WIFI Access point setup
const char* Ssid = "SSID";
const char* Password = "Password";
IPAddress ip(10,0,0,10);
IPAddress gateway(10,0,0,1);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);                    // Set web server port number to
80

// GPIO pins
const int output_set = 5;
int delay_loop=0;

void setup()
{
  // Data Direction
  pinMode(output_set, OUTPUT);

  // Output initial Values
  digitalWrite(output_set, LOW);

  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(Ssid,Password);
  server.begin();

// check to see if a station is connected to this AP. If no station
connected within 20 sec timeframe, go to sleep.

while (WiFi.softAPgetStationNum()==0)              //loop here while no AP is connected to this station
{
    delay(1);
    delay_loop++;
    if (delay_loop>=20000)
    {

        ESP.deepSleep(60e6);                          //go to sleep for 60 sec -wake pin externally connected to reset pin
    }
}
}

void loop()
{
   digitalWrite(output_set, HIGH);      //Flash led once station is connected
   delay(200);
   digitalWrite(output_set, LOW);
   delay(400);
}

Cannot reproduce. Above code builds fine for me in PlatformIO and in Arduino IDE 1.8.3 using Arduino-ESP8266 version 2.4.1 and ESP8266WiFi library version 1.0.0. What version are you using?

Hi, thanks for your response, Arduino IDE Ver:1.8.5, ESP8266WiFi library Ver: 1.0.0.  I am unsure what Arduino-ESP8266 v2.4.1 is? are you able to clarify this?

I have: http://arduino.esp8266.com/stable/package_esp8266com_index.json added to my additional boards manager URL in preferences

That URL is correct. What version does boardmanager say you have for esp8266? (Tools->Board->Board manager)

it said 2.0.0, and I have now changed it to 2.4.1. My problem has now been solved. Thank you for your help with this. I continue to learn. Kudos.

Followup answer from comments:
The issue was an outdated version of the ESP8266-Arduino framework. The function WiFi.softAPgetStationNum() is available in 2.4.1
For the sake of completeness: The function itself is simply a wrapper for the Espressif non-os SDK function:
/**
 * Get the count of the Station / client that are connected to the softAP interface
 * @return Stations count
 */
uint8_t ESP8266WiFiAPClass::softAPgetStationNum() {
    return wifi_softap_get_station_num();
}

See Espressif Non-OS SDK API reference chapter 3.5.36.
That function should also be available on older framework versions. However, upgrading is the recommended way to use that function.

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


text:
Semantics of local PROGMEM
I want to create a class to better use strings in flash. At its core is the following
template<size_t N>
struct progstr
{
    constexpr progstr(const char (&str)[N])
        : progstr(str, make_index_sequence<N> {}) {}

    template<size_t... Is>
    constexpr progstr(const char (&str)[N], index_sequence<Is...>)
        : _str{str[Is]...} {}

    constexpr operator const char*() const {
        return _str;
    }

    const char _str[N] PROGMEM;
};

Where make_index_sequence and index_sequence are the same as those from <utility>.
The problem arises when I try to emulate PSTR
template<size_t N>
constexpr const char* pstr(const char (&str)[N])
{
    return progstr<N>{str};  // huh?
}

It even compiles. However

The returned pointer is "dangling", but it is pointing into flash memory. Will this work?
A constexpr function may be called with an array with runtime values, and that cannot possibly create the string in flash can it?

the operator keyword is missing in () operator

I tested with 100 chars string
const char*
Sketch uses 1566 bytes
Global variables use 288 bytes

with F macro
Sketch uses 1594 bytes
Global variables use 188 bytes

progstr <101> ps(...
Sketch uses 1618 bytes
Global variables use 288 bytes

const char* ps = pstr("...
Sketch uses 1502 bytes
Global variables use 188 bytes

the pstr version string has errors at the end, when printed.
sorry, the pstr function works only if previous sketch version put the string into flash memory. it is not in hex file.

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


text:
Traffic light light system with sensors
I'm trying to make a traffic light system with a ultrasonic range sensor as well as a light dependant resistor. I'm trying to make it so that the default setting is 2 seconds red light 1 second yellow 2 seconds green then 1 second yellow, this will then repeat until something else happens - I've got this working fine.
Then I want 2 different states.
One where if something comes with 10cm of the sensor then the buzzer will beep and the yellow light must blink on and off 10x with intervals of 0.1ms. When the object moves away it must then return to the default setting.
Secondly I want it when the LDR detects that the light has dropped below a level the red light will turn on and stay on until a object approaches the sensor. When an object is near the sensor it must then turn the red light off and turn the Green light on.
Here is all the code i have so far and i cant figure out why its not working.
Any help would be appreciated
Thanks
    #define ECHOPIN 3
    #define TRIGPIN 2
    float distance;
    long distancecm;

    int RED = 13;
    int YELLOW = 12;
    int GREEN = 11;

    int piezoPin = 8;

    int sensorpin = A0;
    int sensorvalue = 0;

    void setup() {
      pinMode(RED, OUTPUT);
      pinMode(YELLOW, OUTPUT);
      pinMode(GREEN, OUTPUT);
      Serial.begin(9600);
      pinMode(ECHOPIN, INPUT);
      pinMode(TRIGPIN, OUTPUT);
      }

    void distancesensor()
      {
      digitalWrite(TRIGPIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGPIN,HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGPIN,LOW);
      distance = pulseIn(ECHOPIN, HIGH);
      distancecm = distance/29.1/2;
      if (distancecm <=10);
        for (int j=1; j<=5; j=j+1)
        {
         tone(piezoPin, 1, 500);
         digitalWrite(YELLOW, HIGH);
         delay(100);
         break;
         }
    }

    void lightsensor()
      {
      sensorvalue = analogRead(sensorpin);
      if (sensorvalue > 500)
        digitalWrite(RED,HIGH);
        digitalWrite(TRIGPIN, LOW);
        delayMicroseconds(2);
        digitalWrite(TRIGPIN,HIGH);
        delayMicroseconds(10);
        digitalWrite(TRIGPIN,LOW);
        distance = pulseIn(ECHOPIN, HIGH);
        distance = distance/58;
        while (distance >10)
          digitalWrite(RED,LOW);
          digitalWrite(GREEN,HIGH);
          digitalWrite(TRIGPIN, LOW);
          delayMicroseconds(2);
          digitalWrite(TRIGPIN,HIGH);
          delayMicroseconds(10);
          digitalWrite(TRIGPIN,LOW);
          distance = pulseIn(ECHOPIN, HIGH);
          distance = distance/58;

       }

    void loop() {
      distancesensor;
      lightsensor;
      digitalWrite(RED, HIGH);          //RED ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(RED, LOW);           //RED OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(GREEN, HIGH);        //GREEN ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(GREEN, LOW);         //GREEN OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      //REPEAT
      }

How is it not working? Describe the problem further? Is it not reacting on your sensors? Do you get a compile error?

Try not to use delay for other things than really simple test code. Instead use non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. And this kind of project I would program it as a state machine, which also would make things simpler when using non-blocking code

this exact question has been asked before, and i think that it was a different OP,  which tells me that this may be a school assignment. .... is it a school assignment? .... did you write the code?

Chrisl, The problem is that the sensors don't seem to be reacting to anything. i don't get any compile errors.

jsotola ill have a look then. thanks, its a uni project and yes i wrote all the code myself.

Kingduken i don't understand what you mean?

It is likely, that the circuit doesn't seem to react, because the code is busy waiting in the delay function. You have up to 2,8 s delay between the measurements. Show us your schematic/wiring, so that we can check that the delays are really the problem

Chrisl ive updated the post with the picture of what the wiring looks like.

The photo of your circuit doesn't really show, how all the components are wired. For this you should either draw a schematic (which you can do with the schematic tool directly in the question editor) or provide a good visible wiring diagram like from Fritzing (though a proper schematic would be better).
For now I cannot see any wrong wiring, though you definitely should recheck it and add a proper diagram to your question.
For your code I will shortly sketch the functionality of non-blocking code and a state machine:

Non-blocking code: Task, that require a long amount of time (this means long for a microcontoller; seconds are long in this context), you should not use code, which blocks the whole program execution, until the task is completed. Instead you should only shortly check, if there is an action to be taken. If not, quickly proceed with other code. This enables you to do, which seems to be multitasking. For timed sequences you can use the millis() function. It returns the number of milliseconds since the program has started and overflows after 50 days. The following code saves the timestamp, when the LED was toggled the last time and checks, if enough milliseconds have passed since the last time. This way you can do something else in the meantime (like checking the state of your sensors). Also refer to the BlinkWithoutDelay example of the Arduino IDE.

unsigned long timestamp = 0;
unsigned long interval = 500;
...
void loop(){
  if(millis() - timestamp > interval){
    digitalWrite(led_pin, !digitalRead(led_pin));
    timestamp = millis();
  }
}

State machine: A state machine is code, that holds it's current state in a variable, thats mostly numeric. This variable is read at every loop cycle and used to determine, which piece of code is to be executed. In your case you would have states for "red light on", "yellow light on", "green light on", "distance lower than 10cm" and "LDR reports low light condition". Each on this gets it's own number. For convenience you should use an enum. Now on every loop cycle we use a switch case to go to the right code depending on the state. For your case you would set the state code with non-blocking behavior as described above. Then you only need transitions between the states, by setting the state variable.

enum STATE {STATE1, STATE2, STATE3};
STATE state = STATE1;
...
void loop(){
  switch(state){
    case STATE1:
      digitalWrite(led1_pin, HIGH);
      if(millis() - timestamp > interval){
        digitalWrite(led1_pin, LOW);
        state = STATE2;
      }
      break;
    case STATE2:
      // doing whatever this state needs to do and then do transition with setting state variable
      break;
    case STATE3:
      // doing whatever this state needs to do and then do transition with setting state variable
  }
}

For designing the states and transitions it sometimes makes sense to sketch them on paper. A bubble with a names is a state and then you connect these states with arrows.
Since you want to check the sensors in every state, you should do this outside of the switch statement. The measurement functions then do nothing else but the measurement and setting the state variable accordingly (so no digitalWrite() or delay() in there).


text:
Unable to convert string read from bluetooth to int
I am using a HC-06 and i want to read a number ending with f as a delimiter, the first three numbers as my servo position, however converting the string into int is giving an endless series of 0s. I added the Serial.print(servopos) to see that its a never ending series of 0s, and nothing seems to fix this problem. What am I doing wrong? (I tried using long for servopos instead of int, it didn't fix the issue)
#include <SoftwareSerial.h>
#include <Servo.h>

Servo myservo; // servo name

int bluetoothTx = 10;
int bluetoothRx = 11;
int fwd = 12;
int bwd = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
String content = "";
char character;

void setup()
{
  myservo.attach(9); // attach servo signal wire to pin 9
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);

  pinMode(fwd, OUTPUT);
  pinMode(bwd, OUTPUT);

}

void loop()
  {
  if(bluetooth.available()> 0 ) // receive number from bluetooth

    character = bluetooth.read();

    if (character!='f'){
        content += (char) character;
        delay(10);
      }

    else{
      int servopos = content.substring(0,3).toInt();
      Serial.print(servopos);
     // myservo.write(servopos);

      String directMvt = content.substring(3);
      if (directMvt == "00"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, LOW);
      }
      else if (directMvt == "10"){
            digitalWrite(fwd, HIGH);
            digitalWrite(bwd, LOW);
      }
      else if (directMvt == "01"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, HIGH);
      }
      else if (directMvt == "11"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, LOW);
      }
      content = "";
  }
}

Have you tried examining the contents of directMvt yet?

Don't post code as picture. Use copy paste

Instead of printing the converted number, try printing the substring, that you try to convert in the line above. Most likely the substring doesn't contain only numbers

Don't put delays in serial receiving code!

I printed the directMvt and the substring, they give the right answer, the problem seems to be in the toInt() function @IgnacioVazquez-Abrams

I printed the content of the substring before converting, it contains only the number i entered, for example if I enter 18000f, the first substring contains 180 and the second 00, I posted the code instead of the pic @chrisl

I had to put delays because I had the issue that the same characters arrives many times, because the sender sends slower than the loop, I had things like 1118888000000 for 18000f @ChrisStratton

That can only happen with a logic bug.  Fix the logic bug.  Do not use a delay, it a proof of misunderstanding.

the thing I believe the loop in the arduino code is faster than rate at which the cellphone sends the data thats why it happens and stops with delay, but I'll try to remove it again and see if I had a logical problem with my previous code @ChrisStratton

Of course the loop is faster; but that's not a problem with a proper program.

Do you think the android code is causing the issue with the delay ? The arduino code doesnt have any bug no? @ChrisStratton

Do you have any idea about the toInt() issue ? @ChrisStratton

I've found your problem: You have a missing pair of { }, that should enclose the if(bluetooth.available()>0) statement. Without the parenthesis it only encloses the following statement, which is the serial reading.
Now follow the logic: Before you are sending something over serial, the global variable character should be zero. So then, since the NULL character is not equal to f, the NULL characters are added to the string. Then you send a string like 18000f via bluetooth serial. The code is adding the characters to the string variable, until it find the f character. Now it goes directly in the else-statement, printing the value of servopos and then resetting the string variable. On the next loop iteration, there isn't something available at the SoftwareSerial, so it goes to the if(character !='f') statement. The character variable is global and it is still filled with the f value, that it got in the last loop iteration. So the else statement is executed forever very fast. But since you reseted the content of the string variable in the last iteration, there is nothing to convert to integer here. So this gives you a forever lasting series of zeros.
Enclosing the code in the first if statement solves your problem, since then, it only does something, when data is available at the serial interface. Also you should consider using a local variable for character, since you only need it there and your problem would have been obvious (through a compiler error), if you used a local variable here. Using global variables, when there is no need to, can make things more complex and error-prone.


text:
Firmware gets stuck at obj.printto(client) in esp32
I am using an ESP32 to capture some data and then sending it over using ArduinoJson. However, sometimes, the firmware gets stuck at the line where it is transmitting data at obj.printTo(client). I have the logs for the same. Do you have any idea as to what might be making it freeze? And any way to avoid it in the future.
Logs:
12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:47:11.229 -> [E][ssl_client.cpp:33] handle_error(): UNKNOWN ERROR CODE (004E)  12:47:11.229 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code:-78
12:47:11.229 -> [V][ssl_client.cpp:245] stop_ssl_socket(): Cleaning SSL connection.
12:47:11.229 -> request sent
12:47:12.217 -> esp32/Arduino CI has failed
12:47:12.217 -> reply was:
12:47:12.217-> ==========
12:47:12.217 ->
12:47:12.217 -> ==========
12:47:12.217 -> closing connection
The send code:
jsonBuffer.clear();
JsonObject &rootObject = jsonBuffer.createObject();
JsonObject &dataObject = rootObject.createNestedObject("data");
JsonArray &X1dataObject = dataObject.createNestedArray("X1");
JsonArray &Y1dataObject = dataObject.createNestedArray("Y1");
JsonArray &Z1dataObject = dataObject.createNestedArray("Z1");
JsonArray &T1dataObject = dataObject.createNestedArray("T1");

vTaskDelay(10);

if (send_flag) {
  digitalWrite(2,0);
  send_flag = false;
  int connection_iterator = 0;
  int connection_iterator2 = 0;
  for (int iterator = 0; iterator < SAMPLE_SIZE; iterator++) {
    X1dataObject.add(X1dataArray[iterator]);
    Y1dataObject.add(Y1dataArray[iterator]);
    Z1dataObject.add(Z1dataArray[iterator]);
  }
  T1dataObject.add((float)(analogRead(NTC)*0.0244));

  rootObject["coreid"] = String(low, HEX) + String(high, HEX);
  //rootObject["coreid_high"] = String(high, HEX);
  rootObject["sample_time"] = int(time_taken);
  rootObject["firmware_version"] = FIRMWARE_UPDATE_VERSION;
  rootObject.prettyPrintTo(Serial);
  Serial.print("connecting to ");
  Serial.println(host);
  while ((!client.connect(host, httpsPort)) && !setup_mode) {
    connection_iterator++;
    Serial.println("connection failed! Retrying..");
    delay(5000);
    if (connection_iterator >= 10)
      ESP.restart();
  }
  if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
  }
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.print("requesting URL: ");
  Serial.println(url);
  client.println(String("POST ") + url + " HTTP/1.0");
  client.println(String("Host: ") + host);
  client.println("Cache-Control: no-cache");
  client.println("Content-Type: application/json");
  client.print("Content-Length: ");
  client.println(rootObject.measureLength());
  client.println();
  rootObject.printTo(client);
  Serial.println("NUMBER OF INTERRUPTS:");
  Serial.println(interruptCounter);
  Serial.println("request sent");
  while ((client.connected()) && !setup_mode) {
    connection_iterator2++;

    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
    Serial.println("Waiting for response");
    delay(500);
    if (connection_iterator2 >= 40)
      break;
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{")) {
    Serial.println("esp32/Arduino CI successfull!");
  } else {
    Serial.println("esp32/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
  digitalWrite(LED_BUILTIN, LOW);
  // readRegister(INT_SOURCE, 1, &dummy_read);
}

I see that you are using SSL. SSL uses a lot of RAM and it is possible that the stack and the heap are colliding which will corrupt the running sketch. I recommend you add the amount of free heap to your log statements so that you can see how it changes, which will help you see if this is what is happening.
To obtain the free heap you can use esp_get_free_heap_size() - there's more documentation about this function in the espressif online documentation.

I will surely log the heap size but this doesn't seem to be happening as the code is not getting corrupted or even crashing. Just that after some time it throws a handle_error and resumes to what it should be doing. However, I will still log the heap size and watch the deviations.

I did the testing and the heap doesn't seem to be the issue. After a successful transfer, there is still about 75% of the heap memory available.

@peeyushtekriwal I think you'll need to post your code for anybody to be able to help you further.

Understandable. I will add the code above

So I have found out that apparently there is some issue working with WiFiClientSecure to send large data packets. The secure line sends data in small packets which take up a lot of time and also if the server gets unavailable at any moment, the program will get stuck there. This problem, however, was not this prominent when I used the same mechanism in esp8266.  Nevertheless, the solution would be to use a buffer to send the data.
Also, this version of code was written with ArduinoJson V5. But, even after migrating to ArduinoJson V6 the problem persists. It seems that whatever new JsonDocument feature has been implemented in the new version is still far from providing the efficiency of a buffer and it recoils back.
However still, if anyone else finds a better solution, please do update.

Latest development: I picked up this issue after a long time after not being able to solve it and still cannot find any leads. The chip seems to establish a connection with the server but somehow, it gets stuck and is unable to continue. The point to be noted is that the same mechanism is working with ESP8266.

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


text:
Watchdog problem
I am using Maniacbug Mighyty-1284p 16MHz in my project.
Here I used watchdog for safety.I used three command for watchdog.
1. wdt_enable(WDTO_8S);
2. wdt_reset();
3. wdt_disable();

Is it create any problem if I use "wdt_enable(WDTO_8S);" command two times (one after another without using wdt_disable();)

no. it only sets the registers. and the reason for setting it twice is?

@Juraj besides setting the registers, it also resets the watchdog timer if it is running. Still not an issue for the OP. Calling it twice is fine.


text:
GPS showing incorrect speed
I am using Arduino ATmega 2560.
When i am using "AT+CGNSINF" command to get GPS value, sometimes it showing incorrect speed.
The correct speed should be (50-60)km/h but sometimes it showing (200-300)km/h.
How can I fix the problem or avoid/ignore the unexpected speed.
here is my code
void get_GPS()
{
    sendATCommand("AT+CGNSINF","OK", 1000);

    // condition for valid response
    while (strstr(AT_Buffer, "+CGNSINF: 1,1") != NULL)
    {
        delay(3000);
        strtok(AT_Buffer, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        Serial.println("\n");
        Serial.println(strtok(NULL, ","));

        //sendATCommand("AT+CGNSINF", "OK", 1000);
    }
}
uint8_t sendATCommand(char* ATcommand, const char *expectedResponse, unsigned long timeout)
{
    uint8_t x = 0, answer = 0;

    memset(AT_Buffer, '\0', AT_BufferLength);    // Initialice the string
    delay(100);
    while (Serial1.available() > 0) Serial1.read();    // Clean the input buffer
    if (ATcommand[0] != '\0')
    {
        Serial1.println(ATcommand);    // Send the AT command
    }

    unsigned long previous = millis();

    // this loop waits for the answer
    do {

        if (Serial1.available() != 0) {    // if there are data in the UART input buffer, reads it and checks for the asnwer
            AT_Buffer[x] = Serial1.read();
            //Serial.print(AT_Buffer[x]);
            x++;
            if (strstr(AT_Buffer, expectedResponse) != NULL)    // check if the desired answer (OK) is in the response of the module
            {
                answer = 1;
                break;
            }

        }
    } while ((millis() - previous < timeout));    // Waits for the asnwer with time out

    return answer;
}

Need to check your code, May you need to correct something there...

here is my code https://pastebin.com/Rzc1qXTF

Edit your question, put the code into it. Select it and press Ctrl+K to format it as code.

ERR_CONNECTION_TIMED_OUT link is not opening..

Speed calculation in most GPS systems is very crude. It consists of simply "Where was I then? Where am I now?". Many will also add "How long has passed between then and now?", but many also don't - they assume a fixed time between points (1 second, for example). It doesn't know it's supposed to move, all it knows is the coordinates it has at the moment.
With the latter, if you don't get a reading for a couple of seconds (buildings in the way, for example) the position can suddenly jump a long way.  You can see the effect in your phone's GPS in built-up areas - your position may jump long distances and then pause for a bit.
To visualise it in 1-dimension, you can think of a simple number sequence 0-9 and the difference between each value:
Value:        0 1 2 3 4 5 6 7 8 9
Difference:     1 1 1 1 1 1 1 1 1

The difference equates to the "speed" of the sequence.
Now if the numbers don't get updated smoothly, but all at once at the end, you get something like:
Value:        0 1 2 2 2 2 2 7 8 9
Difference:     1 1 0 0 0 0 5 1 1

The end results is the same, but you get a "dead" period with no "movement" and then a big jump with an unusually high speed.
It's up to you to filter out such anomalies. It's simple enough to say "5 is too much - ignore it". You could also average the past 10 seconds worth of data (for example) and use that as your average speed over that time period, which would smooth out such peaks and troughs.


text:
Need to cycle through LED brightness
So this is pretty much explanatory.  I am new to arduino, and i am learning the best i can.  I need to sketch a code in which will cycle through 5 different brightness settings of an led.  One push will cycle through the five, another push of the button will turn the led off, and another push will restart the cycle.
const int led =11;
const int BUTTON = 7;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup()
{
  pinMode(led,OUTPUT);
  pinMode(BUTTON,INPUT);
}
boolean debounce(boolean last)
{
  boolean current = digitalRead(BUTTON);
  if (last != current)
{
  delay(5);
  current = digitalRead(BUTTON);
}
return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledLevel = ledLevel + 51;
  }
  lastButton = currentButton;
  if (ledLevel > 255) ledLevel = 0;
  analogWrite(led, ledLevel);
  analogWrite(led, ledLevel + 51);
  delay(200);
  analogWrite(led, ledLevel + 102);
  delay(200);
  analogWrite(led, ledLevel + 153);
  delay(200);
  analogWrite(led, ledLevel + 204);
  delay(200);
  analogWrite(led, ledLevel + 255);
}

The code above turns the led on and cycles brightness, like it should it however for some reason it does disable the button.  Take the analogWrites out except for the first one, and the button will cycle the led. any suggestions on what i could do?  Im very new at this.

When you are not sure how to continue, split the problem into smaller problems and confirm that a part is working before using it with the other parts. You can split your sketch into different parts. I can see four parts: read button with debounce, notify that a button has been pressed, process that information for the three states (brightness, turn off, restart), and set the brightness for the led. If you show clearly the four parts in your sketch, then it is easy to print a message when a button has been pressed. That makes it easier to test that part.

Something like this, with variable declarations & setup() left to you.  All time elements are of type unsigned long.
pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}

Ive managed to write the declarations and the setup.    int pwmValue[] = {51, 102, 153, 204, 255};
const int ledPin = 13;
int startButton = 2;
int pwmCycling;
int startTime = 0;
int elapsedTime;
int currentTime;
int eventDuration;
int brightNumber;
void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(startButton, INPUT);
  startButton = millis();    I am not getting an errors when compiling the sketch.  However the button does not turn on the led at all.  Im assuming the problem is within the setup().  what should i be looking for?

also dont know why the 4 space thing doesnt work for me.  I tried keeping the lastbutton and currentbutton lines of code, still no errors, still not working.

changed to unsigned long and still nothing.  Not sure what im missing.

I can't do much more until I get home to try it myself.

All the delay(200) lines keep the sketch from reading button presses.
You need to learn about Blink Without Delay so your sketch can do things other than sit there blindly letting time pass.

So I am now reading up on blink without delay.  If i were to remove the additional analogWrite(led, ledLevel) portions of the code, how would I implement it.  First press of button will turn the led on, and cycle through the following PWMs (51, 102, 153, 204, 255) continously.  Second push of the button will turn the led off no matter what PWM the led is in.  while a third push of the button will restart the process.  If it were to implement millis() how could i do that with analogWrite() to be able to phase through the led brightness? only examples I get is with digitalWrite.

What you are doing is checking how much time is elapsed, and when enough has gone by you do another something. Just like watching a clock on the wall when baking a cake. Capture the time now to start, then capture the time every pass thru loop() after that, and see if enough time has elapsed to do something.


text:
Wake Huzzah Feather ESP8266 With Reed Switch
Forgive me if this is a really dumb question but I am new to IOT and hardware in general.
I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor.  I am using a standard reed switch door sensor (example here).
Ultimately what I want this device to do is:

The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.
Once awoken check the reed switch and send a message to Azure IoT hub that says the bathroom is occupied if door is closed.
Put the device into deep sleep, waking every 30 seconds.
Every time the device wakes check the switch, once the door is opened I send a message to Azure that the bathroom is not occupied and then put into deepSleep(0) (i.e asleep until the door is closed again, then the process repeats)

Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.
From my super limited understanding of this it seems like what I want to do should be possible.  I imagine I am missing something very simple, but I have hit a wall here.
I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

GPIO 16: Door sensor wire #2
RST: GPIO 16
GND: Door sensor wire #2

Simplified code sample:
void setup()
{
    initSerial(); //inits serial
    initWifi(); //initis wifi
    door_open(); //sends message
}

void door_open() {
  IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

  if (iotHubClientHandle == NULL)
  {
    Serial.print("Failed on IoTHubClient_LL_Create\r\n");
  }
  else
  {
    // Because it can poll "after 9 seconds" polls will happen
    // effectively at ~10 seconds.
    // Note that for scalabilty, the default value of minimumPollingTime
    // is 25 minutes. For more information, see:
    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
    unsigned int minimumPollingTime = 9;

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
      Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
    }

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
    {
      Serial.printf("failure to set option \"TrustedCerts\"\r\n");
    }

    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
    {
      Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
    }

    IOTHUB_MESSAGE_HANDLE messageHandle;
    if(digitalRead(DOOR) == LOW)
    {
      messageHandle = IoTHubMessage_CreateFromString("closed");
      Serial.println("Door closed");
    }
    else
    {
      messageHandle = IoTHubMessage_CreateFromString("open");
      Serial.println("Door Open");
    }

    if (messageHandle == NULL)
    {
      Serial.print("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
      MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

      if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
      {
        Serial.print("failed to hand over the message to IoTHubClient");
      }
      else
      {
        Serial.print("IoTHubClient accepted the message for delivery\r\n");
      }
      IoTHubMessage_Destroy(messageHandle);
    }

    while (1)
    {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(100);
    }
  }
}

To clarify:  Right now my device will wake when the door sensors magnetic parts are separated.  I want the device to wake when the circuit is complete (i.e the sensors are together).

Your code IS important here. It is most likely the cause of your problem. So show us your code (as text and properly formatted). Also: what do you mean with "AND RST"?

@chrisl added code sample, although the code is what I am most comfortable with (.NET developer).  The problem currently is that it wakes when the sensors are apart (door opened), I want it to wake when sensors are together (door closed)

@chrisl I tried to clarify my wire diagram in the edit too, One of the door sensor wires is in GPIO16, then RST has a wire to GPIO16, then the other door sensor wire is in GND

Why are you connecting the Reset pin of your ESP to the reed switch? This will hold it in a reset state, until you open the door

@chrisl I thought I was supposed to do that to get the device to reset.  I want the device to be turned on/woken from deep sleep when the door is closed.  According to what I have read about the ESP8266 to "wake" from deep sleep a signal needs to be sent to RST (from the docs: "GPIO16 needs to be tied to RST to wake from deepSleep").  This was just how I thought it worked.

I would get an NC or NO reed switch, the opposite of whatever you have now that's backwards. I would then get rid of all the sleep wakeup stuff and turn the unit on through the reed switch, so it has power when the door is closed, if that's more common than it being open. When closed (powered), the MCU sends a ping on boot to a server that says "hey i closed", and go to deep sleep for 10 seconds.
Once re-awaking, send out a ping that says "I'm still busy". The server needs a tiny bit of smarts, a time-out feature that sets the door state as open 12 seconds after the last ping (10s + some accounting for wifi delays).
This setup uses NO standby power, and only a tiny amount of battery-killing on-time, so it should last a lot longer than trying to sleep and externally wakeup.
For added efficiency, consider building an ESPNOW router with two more ESP8266s. Once you have that ESPNOW router up and running, you can fire off a ping in about 200ms (from a cold/warm boot) instead of 2000ms with wifi, and go back to sleep. This extends your battery life ~10x, at the cost of running two more ESPs 24/7 where power is easily available.

The RST (reset) pin of the ESP works as the reset pin of any other microcontroller. If you pull it to LOW long enough (the threshold is surely listed in the datasheet), the whole microcontroller will reset as if you had cut and reestablished the power supply. So it will not wake it from sleep, but reset it completely.
It is correct, that you can use GPIO16 connected to RST, to let the ESP reset itself from a deep sleep. This seems to be an internal hardware functionality, that is distinct from the normal IO hardware. But you cannot use the same pin for some other functionality at the same time. Your reed switch is closed, if the door is closed. So it gives a LOW level to GPIO16 and RST, holding it in reset state. In this state no code is executed, thus you never get a message, that the door is closed. When you then open the door, the switch opens too. Since the RST pin isn't pulled to LOW anymore, the ESP can boot and execute your code. The door is open, so you get the corresponding message.
So you have to use a different pin for the reed switch.

Is it possible to include a very straightforward "wiring diagram" to achieve what I want to do, I am very new to this haha

Just connect the one wire from the reed switch to an unused pin of the Feather and set your code to the corresponding pin. I don't have a Feather and cannot be sure, what a good choice would be. But how about GPIO4 or 5. You don't seem to need the I2C hardware on them.

So one wire from the reed switch into GPIO5 lets say, then where would the other go, RST?  Doe's the switch need to be grounded?

Do you know how detecting the state of a switch works? It doesn't seem so. The other wire from the reed switch has to go to ground, so that the pin is pulled to LOW, when the switch is closed. Also you should activate the internal pullup resistor with pinMode(DOOR, INPUT_PULLUP), else the pin will be floating when the door is open and will randomly change it's state. You should study a tutorial for switches/buttons, so that you really understand, whats happening there

Like I said in the post, I am an absolute beginner in hardware.  I have zero electrical engineering experience.  I want to make sure I am understanding you right, thats why I am asking supplemental questions.  Are you saying that my exact setup will work if I switch from GPIO16 to GPIO5?  So Reed switch 1 to GPIO5, GPIO5 to RST and Reed Switch 2 to GND

No, Reed switch 1 to GPIO5, RST to GPIO16 and Reed Switch 2 to GND. The whole point of my answer was to NOT use the same pin for reed switch and wake up simultaneously. Waking up from deep sleep is a hardware function, that can only be used on GPIO16. So you have to move the switch to another pin.

Ok so with that setup my switch will not wake the device up at all right?  Since nothing is attached to RST.  This is why I was confused with your comments.  As far as I can tell that setup would move me further from my goal.

Let us continue this discussion in chat.


text:
Need help optimizing snake game code for Arduino Nano
Here's the code:
https://pastebin.com/ypWe4NZw
This is the output when I compile:
Sketch uses 13086 bytes (42%) of program storage space. Maximum is 30720 bytes.
Global variables use 1456 bytes (71%) of dynamic memory, leaving 592 bytes for local variables. Maximum is 2048 bytes.
Everything runs smoothly until getNextFood(), Line 194.  I try to make a LinkedList of integers from 0 to 255 (since I am using a 16x16 LED grid).  However, my list only fills up to about 39, then the rest are set to zero.  I suspected that I was out of memory, so I tried optimizing a few things and was able to get to 42.  I changed all the ints to bytes in the getNextFood function and got up to 61, but that broke my program somehow (inf loop).
Any suggestions on how to fix this?  If I can get this list to fit, the program is basically done, I have nothing else to add assuming it works as intended.
Also, why I am running out of RAM in the first place?  Can someone explain which parts of the program are gobbling up those bytes during runtime (because I would expect the integer list to take up around 512 bytes leaving 80 bytes left, so why I am getting cut off around 40 integers or 80 bytes?)
Thanks.
Edit1:  People have pointed out that linked lists take up a lot of space.  I am using this library because the way the program is designed, I needed to make an array that could change size.  I needed to be able to add and remove elements.  Maybe there is a better way to do it, I don't know.  I thought about making a single 16x16 array for the whole thing and using a different number for each type of piece.  I don't know how I would do the snake movement in that case though, because each piece is "connected" to the one in front of it.
If anyone knows of a similar library that would save space I'd be happy to try it.  Also there might be a way for me to avoid using the tempSnake list.
Edit2:  Per Paul's suggestion, I rewrote the code using a single 16x16 array to represent the entire game board, removing the need for LinkedList.  However, it seems I am still falling short, unless there is something else wrong with my code.  The program resets when I try to generate the food tiles.
https://pastebin.com/ZU4hX477

Stack Exchange sites are really reserved for problems that can be concisely stated on the question page itself.  You'll need to reduce your scope to something you can present without relying on a link.  Why are you using a linked list in the first place?  That will be extraordinarily costly on a system like this.  You should use a simple array - but unless you have brightness control even that is excessive, probably you want a bit-mapped array with only 1 bit per pixel.  You may also want to consider a more suitable platform like an ARM MCU with more memory, some work with the Arduino IDE.

If you are short on RAM, you should try to avoid making full copies of the lined lists. Also, you wrote //implement modulus for position: this operator is already implemented in C++, and you can write newRow = (newRow+1)%16, etc. But note that the numbers should be unsigned in order to get the desired behavior.

Do you really need the complexity and bloat of linked lists?

Using the F macro for Serial.print would shave off a few bytes. Serial.println(F(“example”));

You don't need a linked list to determine the neighbors of grid squares; that's a fairly simple math operation with some limits at the edges.  Crudely speaking left is index-1, right is index+1, up is index-16, down is index+16, etc then you check the edge limits.  Having a linked list for the snake itself is vaguely reasonable, though instead of an actual linked list perhaps what you should have is a fixed-length array of the index-differences to the next segment.

16x16 = 256
So there are 256 possible places to put a piece of snake.
The max length of the snake will be 256 (fill the board completely).
So if we take an array of bytes (0-255) that is 256 bytes long we could completely map the snake.
Every step you move (unless if the snake just ate some food) you put it's head forward one step, and remove the last part.
So if we make the new head the value of "snakeLength" and do each piece of the body -1 every round. We will get this "decaying" effect.
For example:
[ 6][5][4] (all -1, head down) [ 5][4][3]
[ 0][0][3]                     [ 6][0][2]
[ 0][1][2]                     [ 0][0][1]

This probably isn't the most efficient method (especially not if you scale it up), but in this case the logic would be very easy.
If the head collides with a position that is not 0, it'll be game over. For the food/apple you could use an x/y value.
If a space is not 0, do it -1.
The upside of this is that you don't allocate memory runtime and you know exactly how many you use.
This setup should also make it easier for you to avoid "copying" the whole list all the time, you can basically loop through the array and do -1 for all but those who are 0.

I like this idea, for the food what do you mean by x/y value?  Like just storing the row and column of the food somewhere? I was thinking to use some negative number like -1.

Great idea. You could reserve the value 255 for fruit, and add a check to see that it’s not 255 before decrementing. Maybe reserve 254 for walls. 253 for a teleport q-;

Still running out of RAM, LOL!  225 bytes available at compile time, crashes when generating new food tiles...
https://pastebin.com/ZU4hX477

Hmm, you should use bytes (8bit/1byte values), if you do -1, you'll either use an integer (2bytes) or have a range of -128 to +128

Hmm, check the variable 'int foodSquares[numZeros] = { 0 };' which uses 255x 2bytes. As well as your gameboard is using int instead of byte (which is half the size).

Also the LEDs take quite some space, if you use an SPI based ledstrip instead of neopixels, you can runtime calculate the values (since you're not bound to the clockspeed of neopixels), so they do not have to be saved.


text:
CT Sensors with Arduino and ESP32
there. I am following this tutorial to build an energy monitor system.
The link is https://learn.openenergymonitor.org/electricity-monitoring/ct-sensors/interface-with-arduino
Everything works fine with an Arduino UNO on ADC A1, but I need to send the data to a WebServer, so I decided to do the same setup with ESP-WROOM-32 which has a wifi module. I read the value from pin 34, the code I am using is following
// EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3

#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance

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

  emon1.current(34, 111.1);             // Current: input pin, calibration.
}

void loop()
{
  double Irms = emon1.calcIrms(1480);  // Calculate Irms only
  Serial.println(Irms);            // Irms
}

The current is always 0, when I add a println(analogRead(34)), it always gives me back the maximum number 4095. I am confused when it is not working with the ESP32 but with Arduino UNO, the power supply for both is 3.3V.

Can someone help me, please? Thank you so much!

it looks like you're feeding the orange ADC wire with 3.3v from the white wire. measure from row 60?

Your R2 doesn't seems to be connect to the mid-point. Also the library you are using EmoLib doesn't work for ESP32 as the formula and assumptions it used in the library is wrong for ESP32. Try EmonLib-ESP32 which fix the library and make it works for ESP32.

@hcheung Hi, the circuit on the breadboard working fine with the Arduino UNO, I don't think there are any connection issues, but I will try to use that library, thank you so much!

@hcheung If you zoom in on the 33R load resistor you can just see a tiny bit of yellow peeking through that looks like it might be the "missing link" on the R2 midpoint resistor.

@Majenko Hi, Can you see the answer I posted? I took the picture with a different angle this time

Since you did not post a link to the hardware I will take a SWAG. Many of the ESP32s have a max of 1 volt on the analog to digital converter. You will need to check your data sheet for that. I would also be sure you limit the current into the A/D so you do not blow it.


text:
Interrupt takes longer than expected
I am trying to write a delay function in C, which should take 0.5 seonds then carry on. I am aware that there are libraries for this purpouse, I want to make it myself.
#include <avr/interrupt.h>
#include <avr/io.h>
#define bitset(var,bitno) ((var) |= (1 << (bitno)))

int volatile time_unit;

ISR(TIMER0_COMPA_vect) {

  time_unit += 1;
}

void wait_func(){
  TCNT0 = 0;
  time_unit = 0;
  while (time_unit < 31);
}

int main(void){
  DDRD = 1;
   cli();
  bitset(TCCR0A, WGM01);
  bitset(TCCR0B, CS00);
  bitset(TCCR0B, CS02);
  OCR0A = 0xFF;
  bitset(TIMSK0, OCIE0A);
  sei();

  while(1){
    PIND = 0;
    wait_func();
    PIND = 1;
    wait_func();
  };
}

The timer is in CTC- Mode 1024 prescaler, counting 31*255 (OCR0A = 0xFF) times should give about 0.5 seconds at a base clockrate of 16MHz of the Arduino Atmega328p. The code works, but it turns the LED on and of at a rate of 1 second, (1 sec on 1 sec off). I do not understand why.

PIND = 1; toggles the state of bit 0 of PORTD.
PIND = 0; does nothing at all; no toggling of any pins.

So you're simply just not toggling as often as you think.  Your delay itself is otherwise fine.  Change PIND = 0; to  PIND = 1; and it will work as expected.  Having done that you can get rid of one set of PIND = 1; and wait_func(); call.
Alternately, if you want to follow the current form of the code, set and clear the bit on PORTD directly:
while(1){
  PORTD &= ~1; // or &= 0xFE
  wait_func();
  PORTD |=  1;
  wait_func();
}

For what it's worth:

The semicolon after your while loop does nothing.
The time_unit should probably be an unsigned char / uint8_t.
Unless you're running really tight on code space, it's probably best not to rely on the prior state of the timer hardware registers.

Sorry for the maybe trivial question but I always thought that PIND=1 loads the bit 0b00000001 to register PIND , why does it toggle?

That's just how the AVR GPIO registers are designed.  It allows for a single write to flip a bit rather than doing a set of read, modify, and write instructions.  PIND's naming in in the spirit of reading from the port.

Is this true for every GPIO register?

I think yes, if I understand what you're asking.  For the other GPIO ports on the ATMege328P, writng a  1 in a PINx bit index causes the bit at that same index to toggle in the associated PORTx register.  Many (not all) other AVR parts follow this same scheme for their ports.

See Page 60 in the ATMega328P datasheet.


text:
Arduino Uno freezes for unknown reason during code execution
I am struggeling with a behaviour of my Arduino I do not fully understand.
Long story short:
When starting the communication over I2C the Arduino freezes. In my opinion during the "Wire.write()" command.
Long story and background:
I want to connect my Arduino Uno to an Arduino MKR Wifi 1010 via I2C. I implemented the code for the communication step by step, so I started with the code below.
Code for the Master Arduino Uno:
#include <Wire.h>
#include <Arduino.h>

#define SLAVE_ADRESS                            2

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

void setup() {
  Serial.begin(38400);
  while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
  Serial.setTimeout(2000);
  Serial.println(F("Serial Connection ready"));
  Wire.begin(); // join i2c bus (address optional for master)
}

void loop() {
  static int LedStatus = 0;
  if (LedStatus == 0)
  {
      LedStatus = 1;
  }
  else
  {
      LedStatus = 0;
  }
  Serial.print(F("Master LED status: "));
  Serial.println(LedStatus);
  Send_Data(SLAVE_ADRESS,LedStatus);
  delay(500);
}n

Code for the Slave Arduino MKR Wifi 1010:

#include <Wire.h>
#include <Arduino.h>

#define NODE_ADDRESS 2

int led = 0;

void setup()
{
  Serial.begin(38400);
  while (!Serial)
  {
        ; /* Wait for serial interface to be connected and ready for use. */
  }
  Serial.setTimeout(1000);

  Wire.begin(NODE_ADDRESS);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes)
{
  led = Wire.read();
  Serial.println("Data reveived!");
  Serial.print("Slave Value led: ");
  Serial.println(led);

}

void loop()
{

}

This piece of code works fine as expected.
So I implemented the very same functionality for the master into my projekt.
/****************************************************************************/
/*-------------------------------Description--------------------------------*/
/****************************************************************************/

/*
Used board: Arduino Uno

>>> Pin usage overview <<<
0:
1:
2: waterlevel tank sensor low (black sensor wires)
3: waterlevel tank sensor high (red sensor wires)
4: waterlevel reservoir sensor low (not used yet)
5: waterlevel reservoir sensor high (not used yet)
6: pump level tank
7: pump level reservoir
8: water temperature sensor
9: water temperature sensor
10:
11:
12:
13:
A0: EC sensor
A1: pH sensor
A2:
A3:
A4:
A5:
/*

/****************************************************************************/
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/

#include <Arduino.h>
#include <RTClib.h>
#include <TimerOne.h>
#include <Wire.h>
#include "WaterCondition.h"
#include "WaterFlow.h"
#include "Serial.h"

/****************************************************************************/
/*----------------------------------Macros----------------------------------*/
/****************************************************************************/

#define TIMER_INTERVAL                          2000000 // 5sec (timer in microsec)

#define RTC_INIT_TIME_SECOND                    0
#define RTC_INIT_TIME_MINUTE                    0
#define RTC_INIT_TIME_HOUR                      0
#define RTC_INIT_TIME_DAY                       0
#define RTC_INIT_TIME_MONTH                     0
#define RTC_INIT_TIME_YEAR                      0

#define OPERATING_MODE_AUTO                     0
#define OPERATING_MODE_TEST_TEMP_SENSOR         1
#define OPERATING_MODE_TEST_EC_SENSOR           2
#define OPERATING_MODE_TEST_PH_SENSOR           3
#define OPERATING_MODE_TEST_RTC                 4
#define OPERATING_MODE_TEST_WATERLEVEL          5
#define OPERATING_MODE_TEST_COMMUNICATION       6

#define SLAVE_ADRESS                            2 // adress of the slave for communication

/****************************************************************************/
/*-----------------------------Global Variables-----------------------------*/
/****************************************************************************/

/*
OPERATING_MODE 0: Automatic
OPERATING_MODE 1: Testing / Calibration
*/
uint8_t OperatingMode = 0;

/* Used for Serial.h to read the input from serial connection */
extern char StringBuffer[STRING_BUFFER_SIZE];
extern float WaterConPhVolt, WaterConEcVolt, WaterConPhVal, WaterConEcVal, WaterConTempVal;

/****************************************************************************/
/*------------------------------Initialization------------------------------*/
/****************************************************************************/

RTC_DS3231 rtc;
DateTime now;

int freeRam()
{
    extern int __heap_start, *__brkval;
    int v;
    return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/* standard operations */
void ISR_Task(void)
{
    if (OperatingMode == OPERATING_MODE_AUTO) // Automatic
    {
        Serial.println(F("Running in automatic mode"));

        uint8_t min;
        min = now.second(),DEC;
        if ((min == PUMP_TANK_ON_INTERVALL_1) || (min == PUMP_TANK_ON_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 0 or 30");
            //Activate pump
            //Function tbd
        }
        else if ((min == PUMP_TANK_OFF_INTERVALL_1) || (min == PUMP_TANK_OFF_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 20 or 50");
            //Deactivate pump
            //Function tbd
        }
        WaterConTempVal = WaterCon_Sensor_TEMP(0);
        WaterConEcVal = WaterCon_Sensor_EC();
        WaterConPhVal = WaterCon_Sensor_PH();
        if (Waterflow_Tank() == 99)
        {
            // tbd
        }

    }
    else // Testing
    {
        /* >>> Test the temperature sensor <<< */
        if (OperatingMode == OPERATING_MODE_TEST_TEMP_SENSOR)
        {
            Serial.print(F("Water temperature filtered: "));
            Serial.println(WaterCon_Sensor_TEMP(0));
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_PH_SENSOR)
        {
            float test_ph = 0;
            test_ph = WaterCon_Analog_Read(PH_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_PH);
            Serial.print(F("PH-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ph);
            Serial.print(F("PH-Value from 0 - 14: "));
            Serial.println(WaterCon_Sensor_PH());
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_EC_SENSOR)
        {
            float test_ec = 0;
            test_ec = WaterCon_Analog_Read(EC_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_EC);
            Serial.print(F("EC-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ec);
            Serial.print(F("EC-Value from 0 - 2000uS: "));
            Serial.println(WaterCon_Sensor_EC());
        }

        /* >>> Test the RTC clock <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_RTC)
        {
            Serial.print(F("\nRTC-Time: "));
            Serial.println(now.second(),DEC);
        }

        /* >>> Test the waterlevel sensors <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_WATERLEVEL)
        {
            int WaterLvlSensorLow = 0;
            int WaterLvlSensorHigh = 0;
            WaterLvlSensorLow = digitalRead(TANK_LVL_LOW_PIN);
            WaterLvlSensorHigh = digitalRead(TANK_LVL_HIGH_PIN);

            Serial.print(F("Waterlevel Sensor Low: "));
            Serial.println(WaterLvlSensorLow);
            Serial.print(F("Waterlevel Sensor High: "));
            Serial.println(WaterLvlSensorHigh);
        }

        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

/****************************************************************************/
/*-------------------------Function Implementations-------------------------*/
/****************************************************************************/

void setup() {
    Serial.begin(38400);
    while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
    Serial.setTimeout(2000);
    Serial.println(F("Serial Connection ready"));

    /* Initialize sensors */
    Serial.println(F("Setup Sensors"));
    WaterCon_Sensor_Init();
    Waterflow_Sensor_Init();

    /* Initialize RTC */
    Serial.println(F("Setup RTC"));
    rtc.begin();
    Serial.println(F("Test"));

    /* Initialize timers */
    Serial.println(F("Setup Timers"));
    Timer1.initialize(TIMER_INTERVAL);
    Timer1.attachInterrupt(ISR_Task);
    Serial.println(F("Setting the time for the RTC..."));
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

    /* Initialize I2C Master-Slave */
    Wire.begin();
}

void loop()
{
    now = rtc.now();

    delay(200);
    Serial_Read(1);
    /* Change operating mode to automatic */
    if (strcmp("opauto",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to automatic"));
        OperatingMode = 0;
    }
    /* Change operating mode to testing */
    else if (strcmp("optest1",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: temperature sensor"));
        OperatingMode = 1;
    }
    else if (strcmp("optest2",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: EC sensor"));
        OperatingMode = 2;
    }
    else if (strcmp("optest3",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: pH sensor"));
        OperatingMode = 3;
    }
    else if (strcmp("optest4",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: RTC clock"));
        OperatingMode = 4;
    }
    else if (strcmp("optest5",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Waterlevel Sensors"));
        OperatingMode = 5;
    }
    else if (strcmp("optest6",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Communication via I2C Master-Slave"));
        OperatingMode = 6;
    }
}

Some explanation for you to understand what I am trying to do:
Above you can see the code from the Main.ino file for a hydroponic project. I wanted to realize different operating modes for automatic and testing. So if I encounter a fault, I want to be able to plug the laptop on the USB port and start to read out some information over the serial port. Later this should be accomplished over the air but for the beginning this should be fine.
To achieve this, I put string compare into the loop to notice if the user did some input and respond to it.
I tested that functionality a lot and it worked fine. I am able to jump from any operating mode to another.
There is an external real time clock running for using interrupts and run code at specific times.
During this interrupt I check what operating mode is active and run the respective code. With the string compare I mentioned above I can jumo into the respective code with the next interrupt.
ISSUE:
Now I can describe the actual issue. Everytime I enter the "operating mode 6" to test the I2C connection, the Arduino freezes. As you can see I used the very same code inside the "else if" as tested before.
This is the relevant part of the code:
        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

In the following picture it looks like the Board freezes during the serial communication when it prints out "Master LED status: ". I testet this by commenting out the serial.print commands and insert a print command between Wire.begin and Wire.write in the code.

I think the main problem is caused by the Wire.write function, but I am not able to debug it other than using serial.print commands. But the printed commands do not correlate with the line of code when the board actually freezes. I think I would need real debugger that stops the processor and gives me the possibility to go through the code step by step.
At first I thought this issue was caused because the SRAM got filled. So I put the Serial.print commands in the flash memory and inserted some lines of code for checking the usage of the SRAM and the Stack. You can see the "freeRam()" function in the code, but I removed them for better readability.
Did anyone have a similar issue or do you know what could cause this issue?
Thanks a lot in advance!

In addition to @chrisl's answer, please read Nick Gammon write-up on Interrupts.

The program most likely hangs at Wire.endTransmission();, because that's where the actual I2C communication happens. Wire.write() does nothing but placing the data into the internal buffer of the Wire library.
You experience problems because you are calling interrupt-dependent code inside an ISR, where interrupts are deactivated by default.
The Wire library uses the I2C hardware of the Uno. This hardware generated interrupts for the different stages in the communication (for example generating an interrupt so that the library can place the next data byte in the hardware buffer). That means that the Wire library will not work if interrupts are turned of for some reason. It will wait forever for an interrupt that will never come.
When entering an ISR (in this case of the Timer1 interrupt) other interrupts are deactivated by default. At the end of the ISR the compiler will again turn on interrupts. Any interrupts which happen during the execution of the current ISR will be executed after it has exited.
With Wire.endTransmission() you currently have a function call in your Timer1 ISR, which will wait for its corresponding I2C ISRs to run, which cannot happen inside the Timer1 ISR.
What to do now: You need to restructure your code. You shouldn't do that much stuff in an ISR either way. It needs to be as short as possible to not disturb other interrupt based functions. In the ISR just set a simple 1-byte flag variable. Then in loop() check this flag variable. If it is set, you can do the stuff, which currently is in your ISR. And then you reset the flag to be ready for the next ISR setting it again. For this to work correctly you need to ditch the delay() call in loop(). If you want to do timed things, you can use millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE. Make sure that nothing can block the loop() function for a long period of time (meaning longer than the interval between 2 interrupts or longer than the minimal time resolution, that you want in your system).

Note: You thought of the wrong line while debugging, because of your Serial output. But Serial output is only helping to a certain extent with debugging, since it too needs interrupts to work correctly. All the data that gets printed in your ISR will only be send once the ISR exits. Serial.print() and its siblings only fill the buffer of the library, while the actual sending is done in the background via ISRs. So the sending stopped when it got stuck at the ISR, but that doesn't mean that this actually was what you printed directly before that line. Even when not having interrupts involved this might not be the case. Just keep that in mind when using Serial prints for debugging.

Thank you so so much for taking your time to give me such a detailed insight into the topic of ISR and I2C. I appreciate every comment that helps me writing better code :). I will restructure my code and give a feedback!

Restructuring the code, as you mentioned above, solved the issue. I created a flag for the ISR and only change that value inside the ISR. The other stuff was put inside the loop().