text:
Connecting Multi MPU6050 using I2C on ESP32 Wroom 32D
I want to connect two MPU6050 sensor on Esp32 using the I2C protocol.
ESP32 to MPU6050 connection, I'm using -
VCC(ESP32) - VCC(MPU6050_1) - VCC(MPU6050_2)
GND(ESP32) - GND(MPU6050_1) - GND(MPU6050_2)
G21(ESP32) - SDA(MPU6050_1) - SDA(MPU6050_2)
G22(ESP32) - SCL(MPU6050_1) - SCL(MPU6050_2)

3V (ESP32) - AD0 (MPU6050_2)

and both the MPU6050 device are also detected by the I2C scanner program
0x68 , 0x69
but when the basic reading program to read for MPU6050 data , one MPU6050 is giving zero value for all accelerate axis and gyro axis.
// Basic demo for accelerometer readings from Adafruit MPU6050
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_MPU6050 mpu1;
Adafruit_MPU6050 mpu2;

void setup(void) {
  Serial.begin(115200);
  while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit MPU6050 test!");

  // Try to initialize!
  if (!mpu1.begin(0x68)) {
    Serial.println("Failed to find MPU6050 chip1");
    while (1) {
      delay(10);
    }
  }

  if (!mpu2.begin(0x69)) {
    Serial.println("Failed to find MPU6050 chip2");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");

  mpu1.setAccelerometerRange(MPU6050_RANGE_8_G);

  mpu1.setGyroRange(MPU6050_RANGE_500_DEG);

  mpu1.setFilterBandwidth(MPU6050_BAND_21_HZ);

  mpu2.setAccelerometerRange(MPU6050_RANGE_8_G);

  mpu2.setGyroRange(MPU6050_RANGE_500_DEG);

  mpu2.setFilterBandwidth(MPU6050_BAND_21_HZ);

  Serial.println("");
  delay(100);
}

void first() {

  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu1.getEvent(&a, &g, &temp);

  Serial.println("Sensor 1");

  /* Print out the values */
  Serial.print("Acceleration X: ");
  Serial.print(a.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(a.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(a.acceleration.z);
  Serial.println(" m/s^2");

  Serial.print("Rotation X: ");
  Serial.print(g.gyro.x);
  Serial.print(", Y: ");
  Serial.print(g.gyro.y);
  Serial.print(", Z: ");
  Serial.print(g.gyro.z);
  Serial.println(" rad/s");

  Serial.print("Temperature: ");
  Serial.print(temp.temperature);
  Serial.println(" degC");

  Serial.println("");
  delay(500);
}

void second() {

  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu2.getEvent(&a, &g, &temp);

  Serial.println("Sensor 2");

  /* Print out the values */
  Serial.print("Acceleration X: ");
  Serial.print(a.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(a.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(a.acceleration.z);
  Serial.println(" m/s^2");

  Serial.print("Rotation X: ");
  Serial.print(g.gyro.x);
  Serial.print(", Y: ");
  Serial.print(g.gyro.y);
  Serial.print(", Z: ");
  Serial.print(g.gyro.z);
  Serial.println(" rad/s");

  Serial.print("Temperature: ");
  Serial.print(temp.temperature);
  Serial.println(" degC");

  Serial.println("");
  delay(500);
}

void loop(){

  first();

  delay(1000);

  second();

}

All connection and config are correct both still MPU6050 sensor two not giving the correct data.
I request you to please check and see, what wrong I'm doing in it.
Serial Monitor -
Adafruit MPU6050 test!
MPU6050 Found!

Sensor 1
Acceleration X: -2.18, Y: 1.27, Z: 9.20 m/s^2
Rotation X: 0.23, Y: 8.34, Z: 2.97 rad/s
Temperature: 31.69 degC

Sensor 2
Acceleration X: 0.00, Y: 0.00, Z: 0.00 m/s^2
Rotation X: 0.00, Y: 0.00, Z: 0.00 rad/s
Temperature: 36.53 degC

Sensor 1
Acceleration X: -2.21, Y: 1.29, Z: 9.17 m/s^2
Rotation X: 0.06, Y: 8.29, Z: 2.96 rad/s
Temperature: 31.70 degC

Sensor 2
Acceleration X: 0.00, Y: 0.00, Z: 0.00 m/s^2
Rotation X: 0.00, Y: 0.00, Z: 0.00 rad/s
Temperature: 36.53 degC

please add the content of the serial monitor ... copy and paste, then format same as code ... NO pictures please

@jsotola , I added the serial monitor data in the question lower sections, please check above.
actually, the Sensor 1 (MPU6050) data is correct but the sensor 2 (MPU6050) data is showing zero only.

you forgot to format as code ... did it for you

swap the modules ... what is the resulting data?

Same results as previous , sensor which AD0 pin connected to 3.3V is giving Zero values.


text:
Water pump relay switching too fast
I'm using a water level sensor with two outputs, a 5V fan and a water pump. Here's the wiring .
What I want to do with this project is:

When the water reaches 2 cm, then the water pump is on while the fan is off.
When the water is less than 2 cm, then the water pump is off and fan is on.

The problem is, when the water is below the threshold, the sensor reading is quite unstable, thus making the relay switching too fast (see the video).
How to eliminate this problem?
#include <Wire.h>
#include <Blynk.h>
#include <LiquidCrystal_I2C.h>
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

//Initialize the LCD display
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "xxx";//Enter your Auth token
char ssid[] = "xxx";//Enter your WIFI name
char pass[] = "xxx";//Enter your WIFI password
BlynkTimer timer;

#define pinSensor A0
#define PIN_RELAY_1  D3
#define PIN_RELAY_2  D4
const int startThreshold = 2; // pumping shall start at startThreshold [cm] and above
const int stopThreshold  = 1; // pumping shall start at stopThreshold  [cm] and below

int sensorValue = 0; // sensor reading integer
float tinggiAir = 0; // height of water
float sensorVoltage = 0; // voltage sensor
int nilaiMax = 686; // max value of sensor after fully drowning it in water
float panjangSensor = 4.0 ; // sensor's height in cm

enum StatusType {CHECKLEVEL, LEVELHIGH, PUMPING};
StatusType status = LEVELHIGH;   // Let's start with LEVELHIGH to check level and set the display correctly

void setup() {
  Serial.begin(115200);
  lcd.begin();
  Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
  lcd.backlight();
  pinMode(PIN_RELAY_1, OUTPUT);
  pinMode(PIN_RELAY_2, OUTPUT);
  digitalWrite(PIN_RELAY_1, LOW);
  digitalWrite(PIN_RELAY_2, LOW);
  lcd.setCursor(0, 0);
  lcd.print("Water level");
  lcd.setCursor(4, 1);
  lcd.print("Monitoring");
  delay(1000);
  lcd.clear();
  timer.setInterval(100L, wLevel);
}
void wLevel() {
   sensorValue = analogRead(pinSensor);
  tinggiAir = sensorValue*panjangSensor/nilaiMax;
  sensorVoltage = sensorValue*5.0/686;
}

void loop() {
      Blynk.run();
     timer.run();
     handleStatus();
}

void handleStatus() {
  switch (status) {
    case CHECKLEVEL:
      // Wait for level above threshold
      if (tinggiAir >= startThreshold) { // if wlevel more than startThreshold [cm], then
        status = LEVELHIGH;
        Serial.println("LEVELHIGH");
      }
      break;
    case LEVELHIGH:
      levelIsHigh();
      break;
    case PUMPING:
      if (tinggiAir < stopThreshold) { // if wlevel less than stopThreshold [cm] (use hysteresis!) then
        levelIsLowAgain();
        status = CHECKLEVEL;
        Serial.println("CHECKLEVEL");
      }
      break;
  }
  displayValues();
}

void displayValues() {
  static int oldSensorValue = -1; // variable untuk menampung nilai baca dari sensor dalam bentuk integer
  float oldTinggiAir = -1; // variabel untuk menampung ketinggian air
  float oldSensorVoltage = -1; // untuk menampung nilai ketinggian air

  if (oldSensorValue != sensorValue ||
      oldTinggiAir   != tinggiAir   ||
      oldSensorVoltage != sensorVoltage) {
    Serial.print("Sensor Value = ");
    Serial.println(sensorValue);
    Serial.print("Sensor Voltage = ");
    Serial.println(sensorVoltage);
    Serial.print("Tinggi Air = ");
    Serial.println(tinggiAir);
    Serial.println();
    // Display ke LCD
    lcd.setCursor(0, 0);
    lcd.print("WLevel:");
    lcd.print(tinggiAir);
    lcd.setCursor(12, 0);
    lcd.print("cm");
    oldSensorValue = sensorValue;
    oldTinggiAir   = tinggiAir;
    oldSensorVoltage = sensorVoltage;
    Blynk.virtualWrite(V0, tinggiAir);
  }
}
void levelIsHigh() {
  digitalWrite(PIN_RELAY_1, HIGH);
  digitalWrite(PIN_RELAY_2, LOW);
  lcd.setCursor(0, 1);
  lcd.print("F:OFF P:ON");
  Blynk.logEvent("wlevel", "wLevel more than 2cm");
  status = PUMPING;
  Serial.println("PUMPING");
}

void levelIsLowAgain() {
  digitalWrite(PIN_RELAY_1, LOW);
  digitalWrite(PIN_RELAY_2, HIGH);
  lcd.setCursor(0, 1);
  lcd.print("F:ON P:OFF");
  status = CHECKLEVEL;
  Serial.println("CHECKLEVEL");
}

You could read multiple values from the level sensor and average them to get a more stable reading.

And add some hysteresis

Try de-bouncing the sensor for several seconds unless you need a faster response.

Do you prefer a software solution - or  hardware solution?  If hardware, you need to find a comparator (or op-amp) - perhaps on your ESP8266, or a stand-alone hardware item. REF1, REF2.

The problem lies in the specification itself. According to your rules,
what should the pump do if the water level is exactly 2 cm?
Granted, there is no such thing as an exact physical measurement. But
you have to realize that every measurement system is noisy. Noise is a
fact of life you have to cope with when playing with hardware. You may
try to make it smaller (by filtering), but it will always be there. Now
the question is: what should the pump do if the difference between the
water level and the required 2 cm is less than the noise amplitude?
The standard solution, as suggested by KIIV, is to implement some
hysteresis. You define two thresholds: one for turning the pump on
and another, lower threshold for turning it off. When the readings are
in between these two thresholds, you live the pump alone, in whatever
state it was before.
In pseudo-code:
const float low_threshold = 1.9;
const float high_threshold = 2.1;

void loop() {
    float water_level = get_level_reading();
    if (water_level < low_threshold)
        turn_pump_off();
    if (water_level > high_threshold)
        turn_pump_on();
}

If the difference between these thresholds is larger than the noise
amplitude, noise will not disturb your system.

source: Stack Exchange

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

sort: votes


text:
Create PWM pulses by comparing the cosine wave with AnalogRead potenciometer
I need generate 4 pulses, for the digital outputs, for example 8,9 and 10,11, at this moment I am using an Arduino Mega.
The pulses have these characteristics:
1) 8 and 9 are the same pulses, but I need them to be each going through a digital output. In the same way, 10 and 11 are another equal pair of pulses but different from 8 and 9. Therefore, they are altogether two pulses, only that each one will duplicate it and send it independently in a digital output.
Here is the bulk of the matter with which I need your experiences:
2) The pulses that I need to generate are with the cut of an analog input of a potentiometer that is produced with a trigonometric wave that I generate with a sweep in degrees with the help of a for cycle.
That is to say that the signals Vc and Vd (trigonometric signals) I must compare them with a control signal (Potentiometer) called Vx. That is, for each signal Vc and Vd, it would have a pair of pulses associated each in this way, in 8,9 and 10,11.
I think that this comparison of the signals with respect to the signal status of the potentiometer can be done with an IF arrangement, so I ask for your help because I have already tried it and it has not worked correctly.
3) Something important is that I only need to generate a rising edge that is with the first cut with the cosine wave, the second one that would be the lowering flank is not important, I do not know how I could limit this.

float V1,V2;
float Vc,Vd,Vcc;
float Vx;

void setup() {

    Serial.begin(9600);
    pinMode(A0,INPUT);
}

void loop() {

    Vx = 2.0 * analogRead(A0)/1023.0;      // analog input from potentiometer, range 0 to 2.0

    for (float j = 0; j <= 360; j++) {
        V1 = 1.0 * cos(j * (PI / 180.0));  // cosine wave

        Vd = 1.0 + V1;                     // Signals Vd and Vc
        Vc = 1.0 - V1;

        Serial.print(Vx);
        Serial.print(" ");
        Serial.print(Vd);Serial.print(" "); Serial.println(Vc);
    }
}

Thanks

your question is simple, but the description that you used is too complicated.  i think that all you want is to generate two pulses. each pulse starts when the rising edge of a waveform crosses a preset point. each of the pulses is output through two pins (4 pins are used in total)  .... it is difficult to write the program when the description in your head is complicated. once you make it simple in your head, then it becomes easier to write the program.

one thing that i do not understand:   this is the kind of program that you would use to produce a pulse from an external waveform. ... what is the point of calculating the sine wave internally? ... just calculate time delay to set the outputs to their values .... you will get better PW control when you use the potentiometer value to set a delay value

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


text:
How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?
I'm trying to understand this circuit found here.

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

Your confusion lies in what can "supply" power.
Your assumptions are all correct for an IO pin. However the Arduino has more than just IO pins. It has power pins.
These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.
So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.
The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).

I thought that even the power supply circuit provides 40 mA. I guess I'm wrong there. I tried connecting the DC motor and the Arduino directly at first across the 5V and my Arduino got disconnected from the PC. I thought that this was some kind of current protection inside the Arduino which caused the disconnect and I didn't push it further,  which finally brought me to the article I linked. I understand my mistake now. Thanks!

Official Arduinos and most clones have a "polyfuse" in series with USB bus voltage.  Typical USB hubs including root hubs also have over-current protection as well; something usually more sophisticated than a polyfuse.  It's entirely possible that your motor uses more than the current Majenko states above, particularly when spinning up or stalled.  You may be tripping one or the other or both.  The instinct to not tax Arduino and USB port is a good one.

BTW, the 500mA for usb I quoted in my answer is the nominal rating of the polyfuse.

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


text:
Need help with Arduino Love-O-Meter
not sure if this is the right place to post, but basically I am trying to make a Love-O-Meter, similar to the Arduino project example.
However, my method of determining the score is different. Instead of basing it on temperature, I am basing it on capacitance instead (Let me know if you think there are better ways to determine the score. I have tried body resistance, but it is too insensitive and I have also tried making it random but it doesnt make sense and its not as fun)
Another difference is that I want to make it only measure when both people place 1 of their hands on the foil and their other hand holding onto each other. However, the issue I have is Im not sure how to start measuring when the condition I mention happens.
Link to code: https://pastebin.com/bWyiDtfB (Using reference from here: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) (The code starts measuring the capacitance when it detects that both foils have their hands placed on it, i.e.  when it detects that the capacitance exceeds a certain threshold, 200 for my case. It will then measure 100 samples and the score will be from the median of the 100 samples)
Link to fritzing diagram: https://i.sstatic.net/cOb7h.jpg (Ignore the black wire from A5)

I don't think you are going to get an answer here about a better way to measure "Love"   So then your whole question boils down to wating to  measure a connection between the two pads, as the two people would be completing the circuit between the two pads.  Do a little research, build a small test program for this "Sensor" only and post that code if you have any other questions about the specific problem you are having.

Basically the biggest problem I have now is to find a way to perform the measurement only when they hold hands and their other hand touch the foils.

that is simply a continuity test. Is there an electrical path from pad1 to pad2.  It will be very high resistance, but there will be an electrical path between them

I thought of trying to do that. Like connecting a 5V to 1 of the foil and the  analog pin to the other, but it will interfere with the capacitance measurement. Should I maybe make 2 more foils (1 connected to 5V and the other to the analog pin) so each person have to touch 2 foils with 1 hand?

Should be able to do both.  Can switch pin modes after deciding it us ready to start taking the reading. But them being joined could already effect the capacitance test

So what you are saying is that I dont code it to keep measuring the capacitance, but only start the measurement under the condition that the analogpin receives a signal right? Unlike what I am doing now, whereby I keep measuring the capacitance and only properly start the measurement when the capacitance exceeds the threshold.

@ChadG hmm I was thinking of adding a relay, so that when the hands are placed, the 5V will change to 1 of the digital pins instead.

The digital pins can be either output(5v) or input to measure capacitance.   So need to change which pin it's using, just change the pins mode

@ChadG so instead of using 5V, I use the digital pin to output a 5V. If so, then there shouldnt be any problem with the capacitance test right? I cant test it now but I will do so tomorrow.

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


text:
Timer Interrupt Default Settings
so I am testing out the PulseSensor code from here: https://github.com/WorldFamousElectronics/PulseSensorAmped_2_Sensors/tree/master/PulseSensorAmped_2_Sensors_1.5.0
In the interrupt.ino file, there is a function interruptSetup() which initializes the timer settings. However, I want to undo these settings first, as I have found out that this function is affecting my other readings. What is the default settings for the timer?

Unless you are using PWM, you can just set all these registers to zero. Otherwise, see Arduino's init() function.

Is the init() function the default settings for the timer?


text:
LED Strip Effect without delay
so a brief introduction about the project which I am working on before I go onto my issue.
I am working on a love-o-meter project (Not similar to the arduino example), whereby 2 people place 1 of their hands on a pad and with their other hand holding each other. Making use of a pulse sensor, I measure the BPM for 10s and then indicate the score on a LED strip.
Apart from indicating the compatibility score, I also plan to use the LED strip (cylon/fire effect) to indicate that the arduino is in the progress of calculating (when it is measuring the BPM for 10s) and also to indicate idling (rainbow cycle effect, when there is no one is using the love-o-meter).
However, here comes my issue: Performing the BPM measurement and displaying the cylon/fire effect function at the same time. I know that I cannot use the delay function and instead use millis(). However, the functions in the NeoPixel library already uses the delay effect and it seems like a tough job to edit the function to it using millis(). Is there another way to do so?

How do you take your BPM measurements? You could hack it work on a hardware timer interrupt and/or ADC 'conversion finished' interrupts and periodacally check for "BPM result ready" in the main loop. Hard to say without knowing your code.

@MaximilianGerhardt I am using the code from this link: https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/tree/master/PulseSensorAmped_Arduino_1.5.0 though I have tweaked it to perform the measurement for 10s. If you would like my entire code, I can send you the paste bin link

That code already uses timer interrupts to run 'concurrently' to your normal code, so you should be able to display whatever you want with delay. It does not affect interrupts.

Measuring BPM with a hardware timer will be tricky unless your input is bounce-free.

@ChrisStratton So does that mean my BPM measured will be inaccurate the first few readings? If so, what do you recommend? Because my code is from taken from the pulse sensor example which I assume to be the best way to measure BPM.

If your sensors is a switch with contact bounce, a hardware counter would be wildly inaccurate.  To use that approach you either need a bounce-free sensor or a hardware debounce circuit - or to count in software after a software debounce delay, rather than with a hardware counter.

it is unclear how you are doing the measurement ... the PulseSensor uses optical measurement and detects the heartbeat of only one person at a time .... are you using two sensors for simultaneous measurement of two people?

@ChrisStratton I am using the Pulse Sensor which I doubt requires debounce.

@jsotola I apologise. I am using the code from this link instead: https://github.com/WorldFamousElectronics/PulseSensorAmped_2_Sensors/tree/master/PulseSensorAmped_2_Sensors_1.5.0

@MaximilianGerhardt I apologise. I provided the wrong link. It is this link instead: https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/tree/master/PulseSensorAmped_Arduino_1.5.0 but it is still the same right as it still uses timer interrupts.

If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the Adafruit_NeoPixel.show() function, since it is quite timing sensitive.
But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the strandtest example for use with the millis() function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.
float brightness = 1.0;
uint32_t strip_state=0;

uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
  }
  WheelPos -= 170;
  return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
}

void fill_color(uint32_t color){
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);
  for(unsigned int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
  strip.show();
}

void fade_color(){
  for(unsigned int i=0;i<strip.numPixels();i++){
    strip.setPixelColor(i,Wheel(&strip,strip_state));
  }
  strip.show();
  strip_state++;
  if(strip_state>255) strip_state = 0;
}

void moving_rainbow(){
  for(unsigned int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
  }
  strip.show();
  strip_state++;
}

void colorWipe(uint32_t color) {
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);

  strip.setPixelColor(strip_state, color);
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c) {
  byte r= ((c & 0xFF0000) >> 16) * brightness;
  byte g= ((c & 0xFF00) >> 8) *brightness;
  byte b= (c & 0xFF) * brightness;
  c = strip.Color(r,g,b);
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow() {
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

The functions use the float variable brigthness to modulate the overall brightness of all LEDs. You can set it to every value between 0.0 and 1.0.
The variable strip_state holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to 0 if you want to restart an effect.
You yourself have to declare the variable strip as from the type Adafruit_NeoPixel.
So now you only have to call these function from the typical millis() code (like from the BlinkWithoutDelay example) in an interval, that you chose.


text:
Is my Arduino mega dead?
I accidentally short-circuited my Arduino mega(ended up connecting the 5V and ground pins). Physically from observation nothing seems to be burnt on the board but I am not able to upload new codes to it again. I am quite sure that the last code I uploaded still run on it because when I plug it in all seems to be normal.
I tried to upload codes to it with the CP2012 programmer I use for my pro mini and that doesn't help either.
Is there any way I can manage to upload codes to the board again or it is dead?

Well, is it still short circuited? What did the old sketch do? And how can you be sure that it is still running? With the CP2012, you can't use the DTR pin to move the reset, you know? So just connect +5v, gnd, rx, tx and start uploading. When the IDE tells you "uploading", briefly press the reset button on the mega and see if it works

Have you tried turning it off and on again? (by "it" I meant both your PC and Mega)

@frarugi87 I am familiar with the manual reset approach, it doesn't work with my mega but works with my pro mini.

"when I plug it in all seems to be normal." What do you see or measure to indicate a normal board? E.g. LED behavior, measured outputs, some response to inputs?

@DannyGH with that adapter you should have the autoreset feature on the pro mini, so you don't have to manually reset it..

See Have I bricked my Uno - a lot of that applies to the Mega too. There is a sketch mentioned on that page you can use to test the processor chip with.


text:
To update GPS after every 30seconds using NeoGPS and NeoSWSerial Libray
I am using Adafruit Ulitimate Breakout GPS module and NeoGPS and NeoSWSerial Library. Now I want the GPS to update in 30seconds once (1time in 30seconds).After it is updated I want to check the location if new location is equal to old location then it should be updated in 60seconds once(1time in 60seconds).If not the location should be new location. It should display the location every 60seconds.
I tried this flow on Adafruit GPS Library, which works but I want to use NeoGPS library and do the same.
Below is my adafruit library code:
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(11, 10);
Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true
uint32_t timer = millis();
float old_lat,old_lon,new_lat,new_lon;

void setup()
{

  Serial.begin(9600);
  delay(1000);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
}

void loop()                     // run over and over again
{
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

if (GPS.fix) {

      old_lat = GPS.latitudeDegrees;
      old_lon = GPS.longitudeDegrees;
      if (timer > millis())  timer = millis();
      if (millis() - timer > 60000) {
        timer = millis();
          Serial.println("Location 1 minute:");
          displaytime();
          new_lat = GPS.latitudeDegrees;
          new_lon = GPS.longitudeDegrees;

          if (new_lat == old_lat){
            new_lat = old_lat;
          }
          else{
            new_lat = GPS.latitudeDegrees;
          }
          Serial.print("Final Latitude: ");
          Serial.println(new_lat,6);

          if (new_lon == old_lon){
            new_lon = old_lon;
          }
          else{
            new_lon = GPS.longitudeDegrees;
          }
          Serial.print("Final Longitude: ");
          Serial.println(new_lon,6);

}
}
}

void displaytime(){
    Serial.print("\nTime: ");
    if (GPS.hour < 10) { Serial.print('0'); }
    Serial.print(GPS.hour, DEC); Serial.print(':');
    if (GPS.minute < 10) { Serial.print('0'); }
    Serial.print(GPS.minute, DEC); Serial.print(':');
    if (GPS.seconds < 10) { Serial.print('0'); }
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    if (GPS.milliseconds < 10) {
      Serial.print("00");
    } else if (GPS.milliseconds > 9 && GPS.milliseconds < 100) {
      Serial.print("0");
    }
    Serial.println(GPS.milliseconds);
}

This is my NeoGPS Library code in which I am using NeoSWSerial:
#include <NMEAGPS.h>
#include <NeoSWSerial.h>// import the serial library

NeoSWSerial gpsPort(11, 10); // RX is 11 (to GPS tx), TX is 10 (to GPS rx)
NMEAGPS gps; // the parser
gps_fix fix; // the struct with all the parsed values

void setup() {

  gpsPort.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS Start");
}

void loop() {

  if (gps.available( gpsPort)) {
      fix = gps.read();
      Serial.println("Latitude:");
      Serial.println( fix.latitude(), 6);
      Serial.println("Longitude:");
      Serial.println( fix.longitude(), 6);

    }
 }

you gave an incomplete description of how the program should behave .... what should happen if the location readings do not match?

I have made the changes if the location doesn't match then it should take the new location. But I want firstly how to update the GPS.

@jsotola Its ok about the location but initially I want to change the update rate.

It seems like using the distance feature in NeoGPS would be a good solution for this problem and it should allow you to create a buffer around the original location to filter some of the noise from the GPS readings.
Here's a page with an overview of using Distance in NeoGPS
https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEAdistance/NMEAdistance.ino

Please edit this answer and add more information from the link into your answer. If the link goes down for whatever reason, the rest of the text as you have it does not answer the question.


text:
Can't figure out source of interference reading 10k POTs with 74HC4051
I realize this gets asked a lot, but I feel like I've applied the most common fixes without success. I have 10 10k potentiometers plugged in to an arduino via a custom shield. 2 are wired directly to the MC via A2 and A3. The other 8 are plugged in via a 74HC4051 multiplexer. The 2 plugged in directly work great. The other 8 show a ton of cross talk and don't seem to vary as much as they should. Here is some example output on the arduino serial plotter:

Things I have tried:

I put a delay between the pin selection and the read.
I'm reading twice (with a delay in between) and discarding the first read.

I'd use an MCP2308 if I were doing this again, but in the mean time is there anything else I can try?
Here is my schematic:

Each pot is plugged in to 5V and ground, with the wiper wired directly to the pin, all via jumper cables to the shield. Here's a picture of how this works (apologies for the mess):

The pin blocks have, per row, one pin each feeding in to a multiplexer input, and another attached to the GND and +5V planes on the PCB. These are attached to +5V and GND on the arduino:

Here is my code:
const int selectPins[3] = {8, 12, 13}; // S0, S1, S2
const int zInput = A1; // Connect common (Z) to A1 (analog input)
const int DIMp = A2;
const int bDIMp = A3;
void setup()
{
  Serial.begin(9600); // Initialize the serial port
  // Set up the select pins as outputs:
  for (int i=0; i<3; i++)
  {
    pinMode(selectPins[i], OUTPUT);
    digitalWrite(selectPins[i], HIGH);
  }
  pinMode(zInput, INPUT);
  pinMode(DIMp, INPUT);
  pinMode(bDIMp, INPUT);
}

// The selectMuxPin function sets the S0, S1, and S2 pins
// accordingly, given a pin from 0-7.
void selectAMuxPin(byte pin)
{
  for (int i=0; i<3; i++)
  {
    if (pin & (1<<i))
      digitalWrite(selectPins[i], HIGH);
    else
      digitalWrite(selectPins[i], LOW);
  }
}

void loop()
{
  // Loop through the hard wired dimmers
  Serial.print(String(analogRead(DIMp))+" ");
  Serial.print(String(analogRead(bDIMp))+" ");
  // Loop through all eight pins.
  for (byte pin=0; pin<=7; pin++)
  {
    selectAMuxPin(pin); // Select one at a time
    delayMicroseconds(500); // delay after pin select
    int inputValueb = analogRead(zInput); // read Z
    delayMicroseconds(150); //delay after first read
    inputValueb = analogRead(zInput); // read Z again
    Serial.print(String(inputValueb) + " ");
  }
  Serial.println();
}

"Z1" is connected to A0 but you are reading from A1?

it is difficult to guess the anything else I can try because you did not say what you already tried

Sorry - the Z1 is a mistake because I removed some code related to the second chip. I tried adding a delay between reads, and I tried reading twice and throwing out the first read.

Please [edit] your question, informations in the comments are very hard to find.

I'd start with decoupling capacitor for 4051. Next step would be reading 0V channel before reading analog input channel (but that's not possible by analogRead), to remove charge of sampling capacitor.

Where does the 5V used on Poties come from? Is it the same voltage you use as the reference voltage for the Arduino ADCs?  Do the Arduino and the poties have the same GND? It would be easier to find someting, if we could see a picture of your setup. Schematics say nothing about what you have really done. ;-)

Thanks everyone for your helpful comments. I've edited the post with cleaned up code and added my (no doubt shameful) PCB layout and a picture of the actual setup.
@PeterPaulKiefer : The poties are plugged in to the arduino Gnd and +5V pins via copper fills on the PCB - I'm guessing that's not the way to go?

Have you tried to connect only one poti to the muxer? Setting the other 1st over a resistor to GND (Just for safety, if there is a short circuit) and 2nd leave them open. I think the program works fine. But there seems to be a problem with the wiring of the poties or PCB. There is an influence of the potis on each other and/or on the ref voltage. And the graph show also a voltage offset. That's a hint that the feeding voltage of the poties and the reference do not match.

Have you a multimeter to measure the voltages before the muxer. Perhaps that gives you a hint.

And one thing, but it might be nonsense: I saw in the layout that the chips are oriented in different ways.  But on the picture it seems as if they are inserted in the same way. If they use different marker to indicate pin 1.

They are pointing in different directions! Too bad - that would have been an easy fix. I'll compare the ref voltage when I can get back to the shop. Per @KIIV I'll also try putting a .1 uf capacitor between the IC VCC and gnd. Not sure how to read 0V.

There is an internal ADC channel connected directly to the ground. But as i wrote, it's not reachable by analogRead. So unless you have free analog input that can be grounded, you'll have to try to read it directly by setting ADC registers. (that's for elliminating crosstalk caused by too big input impedance that can't charge/discharge sampling capacitor enough - causing crosstalk with previous reading)


text:
How do I get a nonzero output from my HX711 and load cell?
I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).
Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

Here is the calibration sketch I am using (from the HX711 hookup guide):
#include <HX711.h>

#define DOUT 9
#define CLK 8

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

Observations:

Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

you do not appear to have any code that reads the load cell

This is a calibration sketch, I also have a separate sketch that reads the load cell once the calibration is complete - is this what you mean?

so if i use a calibration factor of 8388607 and t reads zero then my hx711 is broken? i tried it and it reads -0.5kg

The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.


text:
Which container to use?
So for my project, I am measuring heartbeat of a person in a span of 10s. However, as the number of heartbeats may differ for each person, is it wise to use a vector?

What are you measuring? The time between each and every beat, or the number of beats in that 10 second period?

@Majenko I am measuring the time when each pulse occurs within a span of 10s. I will then use this information and find out the BPM in the end.

Why store information about every heartbeat, if you only need an average. Just store the number of heartbeats, and the timestamp of the last one. Combined with the timestamp of the first heartbeat, gives you enough information to calculate the average. Or do you want to measure irregularities?

No, you don't want a vector, for a number of reasons:

There is no "vector" unless you add extra (unsupported) code.
Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.
Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.

alright thanks a lot. Just wondering too, is there going to be a difference if I allocate a vector with a size of 100 vs an array with a size of 100? Also, can you explain when you mention arduinos dont work well with dynamic memory? Is it due to not having enough memory?

Yes, it's due to not having much memory. It's easy for heap fragmentation to occur, as evidenced when people over-use String variables and their program crashes randomly.  Vectors are pointless. Don't even consider them. Erase them from your mind. They are a concept not compatible with little microcontrollers.

Alright, thats a pity since in c++ we almost always use vectors instead of arrays. So the only container for arduino are arrays?

Not the "only", but the only "sensible" one.

I am curious about your opinion on malloc(), alloc() and free() as well.

On a small MCU they should be avoided at all cost. As should new.  alloca() is OK since it does stack allocation.


text:
Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)
I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++.
I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:
    // path :RadioHead/RH_ASK.cpp
#if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
 #ifdef RH_ASK_PTT_PIN
    RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #else
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #endif
#else
    // Set up digital IO pins for arduino
    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);
#endif

None of the tokens in this snippet like "RH_ASK_PTT_PIN" or  "RH_ASK_TX_PIN" were mentioned anywhere in the code before or any other file that was included.
I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should):
"RH_ASK_PTT_PIN" not declared in this scope
So how does this library work with the Arduino IDE?
Link to the library : https://github.com/PaulStoffregen/RadioHead
Also can someone suggest tags for this post? Its my first post here.

They're not defined. If you notice that whole block is wrapped in a #ifdef which will be false unless you're on some specific platform, where the platform defines those macros.
Everything else uses the last little bit:
pinMode(_txPin, OUTPUT);
pinMode(_rxPin, INPUT);
pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).

Thanks for the prompt reply, I understand that to rewrite this I don't need to care about the #ifdef block but how does this file compile in the first place without actually defining the macros? I added this library as a .zip file using the library manager of the Arduino IDE, the entire folder does not mention them.

The top two thirds of the block only gets compiled if they have been defined. Since they haven't been defined it gets completely ignored. C compiling is done in multiple phases. The first is the "preprocessor" that looks at the #ifdef etc bits and expands them where it can. The C compiler doesn't see the top part at all because the preprocessor deletes it.


text:
IO with port manipulation while not interfering with i2c
I'm using an Attiny84 with the Tiny Core.
I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.
How can I write only to the lower 4 bits to avoid interfering with the i2c?

Have you tried doing it, and it has not worked?

I don't think you need to worry. A simple piece of code:
void setup()
{
 PORTA |= bit (0);
}

void loop() { }

Generates:
00000044 <setup>:
  44:   d8 9a           sbi 0x1b, 0 ; 27
  46:   08 95           ret

In other words, the compiler generates code to set that bit, ignoring all the other bits.

Presumably PORTA |= bit (0000); would set the 4 least significant bits?

Not at all. Zero is zero, no matter how many leading zeroes you put there. You could do this:  PORTA |= 0b00001111;

The bit macro sets a bit by shifting the number 1 left the number of bits in the argument, so bit (0) is 1 << 0 which is the same as 1.

OK, so I understand now that I can set the bits to 1 without touching the i2c pins. Is it the same, but I suppose with the OR operator to set back to 0?

No, you use the AND operator. PORTA &= ~0b00001111; The ~ operator takes the ones-complement, and you AND that into the port. Alternatively: PORTA &= 0b11110000;


text:
Weird multiplication result
Here's come Arduino code.
#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

Why is the result 13?

Because M(3 + 2, 4 + 2) gets replaced to 3 + 2 * 4 + 2 and then the normal priority of operations does the multiply before the addition.
This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.
If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.
#define M(x, y) ((x) * (y))

Always also surround the whole macro in parenthesis; otherwise you can have the same problem in the other direction: If you do #define A(x, y) (x) + (y), then A(1, 2) * 3 will expand to (1) + (2) * 3 = 7, instead of ((1) + (2)) * 3 = 9, like one would expect.

And trailing semicolon here will also make problems.


text:
ESP32 HTTPS server - how to get POST request string
I'm trying to set up an ESP32 (DOIT ESP32 DEVKIT V1 in the Arduino IDE, with Espressif's WiFi libraries) with the following includes so far:
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <HTTPSServer.hpp>
#include <SSLCert.hpp>
#include <HTTPRequest.hpp>
#include <HTTPResponse.hpp>

Now, if I have a callback routine that's set up with
ResourceNode * nodeEchoPost = new ResourceNode("/cmd", "POST", &handleEcho);

how can I parse out the POST request string? On the serial console I get
[HTTPS:I] Request: POST /cmd

which is a debug output from the HTTPSRequest library itself. But I have no clue how to get that '/cmd' string for my own use!
I've tried the example code of
byte buffer[256];
size_t s = req->readBytes(buffer, 256);

getting a buffer that only returns garbage, probably because all the request is in the POST statement and the body is empty.
Since all I need is the request-info
'/cmd?command1=foo&command2=bar&etc'

to chop up and use, well.. how do I get that out from the library? I've been googling around, and looking in the library header files, without much luck.
Also, is there any advantage to using the WiFiClientSecure library instead, since everything already goes over HTTPS? That's more of a side question, though if it makes it easier to grab the Request string that way, I'm totally fine with accepting that.

That's a GET and not a POST, so variables are accessible with
auto params = req->getParams();
std::string command1;
std::string cmd2;
bool hascommand1 = params->getQueryParameter("command1", command1);
bool hascmd2 = params->getQueryParameter("cmd2", cmd2);

See example at
https://github.com/fhessel/esp32_https_server/blob/master/examples/Parameters/Parameters.ino
The .c_str() is required to transition from std::string to what println needs, not a problem related to the getRequestString() function itself
I came across this question while looking for ways to read actual POST variables, which is not documented (and the source code does not show sign of it)

I think I found the answer, by looking through examples in the github repo of Hessel's HTTPS library.
In short, this seems to be it:
void handleEcho(HTTPRequest * req, HTTPResponse * res) {

Serial.print("in handleEcho. request is:");
Serial.println(req->getRequestString().c_str());

Output from serial console:
"in handleEcho. request is:/cmd?command1=foo&cmd2=bar"

Now I have a plain-text string that I can use plain string commands on to chop up in parts with strtok or similar. I don't mind the extra hassle of finding keywords in the string, I'm happy to just have gotten the damn thing.
Since I have all the data I want in that request, I'll just use req->readBytes as mentioned in examples to empty the buffer and discard all 'body' data.
And someone's gotta agree with me that adding the .c_str() to an already existing function just seems extra complicated. :/


text:
Receive socket when in loop arduino (Interupt a while loop with a socket)
I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.
The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.
I found a page that had a solution for this problem but only with a button attached to the arduino.
Link to page (Interrupt with button)
This is the loop I want to be able to interrupt with a socket:
bool loopRunning = true;

void rainbow(int wait) {
while(loopRunning == true) {

      for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
        for(int i=0; i<strip.numPixels(); i++) {
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show();
        delay(wait);
      }
    }
}

I want to set loopRunning to false when I recieve a socket emit.
Anyone have any ides how I can implement this?
Page to the socket functionality that I use

There are two ways to handle events: interrupts (hardware triggered) and polling (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses polling.
The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.
With this library, you have to call SocketIoClient::loop() many times a second. That's why SocketIoClient::loop() exists. So it needs to be added to your outer for loop.
(If your delay(wait) takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)
Then all you need to do is use SocketIoClient::on() to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.

The problem is the while loop trapping execution.  When you have a small section of your loop that you want to stick in, you can do it two ways. You can do what you did with a while loop, that keeps execution stuck inside the while loop with nothing else happening.  Or you can let the loop function be the loop and use flags and if statements to decide what's running.
Imagine this code:
void loop() {
  if(loopRunning){
     // do the stuff in your while loop
  }
  else {
     // all the other stuff in loop that you don't want running during that
  }
  // all the stuff you want to run regardless, like listening to your socket.
}

When you do it like that you still get to have the stuff you were going to while loop to happen on it's own without the rest of loop, but you can also have some stuff that runs both ways.  That logic can be extended in all kinds of ways.  Maybe you want that part to always run but the rest of loop to be skipped when loopRunning is false.
void loop(){
   //  all the stuff that should run all the time (like your socket)
   if(!loopRunning) {
       // all the stuff you would put into a while(!loopRunning) code
       // but wouldn't be able to catch the socket.
   }
}

You'll also have to ditch the delay calls and go to a "Blink Without Delay" style use of millis if you really want to be responsive to your socket.  Those for loops are also blocking, you could have that code take one step at a time and wait to be called from loop to take the next step.  Google around for Arduino neopixel and non-blocking.  You aren't the first person to realize that the demo stuff for neopixels doesn't work out in larger programs.  It's not hack-and-paste code, it's just for demo.


text:
How to use tone in two pins?
I have a buzzer and an IR led emitter so I have to use the tone function to sound the buzzer and to modulate the output of the LED.
I have connected the led pin 5 of the arduino, the buzzer pin A0.
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  tone(cr_pin, 38000);  /* For modulation at 38kHz */
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
  Serial.println("Hello");
}

This is my code but I can not make the led and the buzzer work at the same time, apparently the buzzer is affected by the tone line (cr_pin, 38000); / * For modulation at 38kHz * /.
I tried to remove (cr_pin, 38000); / * For modulation at 38kHz * /. of the setup and leave code in the following way.
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
tone(cr_pin, 38000);  /* For modulation at 38kHz */
      Serial.println("Hello");
noTone(cr_pin);
    }

In the first code the LED works but not the buzzer and in the second code the buzzer now works but not the LED.

Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: arduino.cc - tone().
noTone() Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated. Source: arduino.cc - noTone()


text:
Automatic pet feeder with a simple menu type keypad
this is the sample code where the user enters A to set the number of times the pet needs to be fed. When I click A on the keypad it asks for the user to set the number. However, the keypad still somehow saves the input of A that is initially pressed. I want the system to ask for another input. How would I clear the memory of the keypad?
Here is the code attached
    /* Hello Wokwi! */
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
const int ROW_NUM    = 4; // four rows
const int COLUMN_NUM = 4; // four columns
char keys[ROW_NUM][COLUMN_NUM] = {
  {'1','2','3', 'A'},
  {'4','5','6', 'B'},
  {'7','8','9', 'C'},
  {'*','0','#', 'D'}
};
int col = 0, row =0;
byte pin_rows[ROW_NUM] = {10,9,8,7};      // connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {6,5,4,3}; // connect to the column pinouts of the keypad
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );

void setup () {

  lcd.init(); // initialize the lcd
  lcd.backlight();
  lcd.setCursor(col,row); // move cursor to   (cursorColumn, 0)
  lcd.print("HI OWNER");
  delay(3000);
}
int h1,h2,hf1,min1,min2,minf1;
int numfed,setnofeed=0;

void loop() {

  char key = keypad.getKey();
  if(!key){
    displaytime();
  }

  switch(key){
    case 'A':
      lcd.setCursor(col,row);
    lcd.print("SET NO. OF");
    lcd.setCursor(col,1);
    lcd.print("FEEDING TIMES");
    delay(3000);

    lcd.clear();
    lcd.setCursor(col,row);
    lcd.print("MAX 5 MIN 2");
    col=0;
    lcd.setCursor(col,1);
    if (col==0&&setnofeed==0){
      numfed=key-48;
      lcd.print(numfed);
      delay(1000);
      col=1;
    }
    else if(col==1){
    lcd.setCursor(col,1);
    lcd.clear();
    lcd.print("NO. OF FEEDING");
    lcd.setCursor(col,1);
    lcd.print("SET");
    delay(2000);
    setnofeed=1;
    }

    break;

  }

}
void displaytime(){

      lcd.setCursor(0,0); // move cursor to   (cursorColumn, 0)
    lcd.print("Time now:");
}

where is the keypad memory?

don't be in a rush to do everything when A is pressed ... display the menu only, nothing else

What should I do instead? Are there any proposed solutions?

start by describing the program behavior, on paper,  in great detail ... a very detailed description translates into code almost directly ... anyway, you already have code that runs when A is pressed ... reduce it to display the menu only ... add code that runs when a numeric key is pressed ... add a variable to the program that keeps track of which menu is displayed


text:
Trying to recover my TTL-Wifi
So I bought What I tought was a DOIT Wifi-TTL and after a few bad manipulations I wiped the firmware...
That means the leds are not turning on anymore and I see no activity on it when I connect to it with a USB-TTL...
The FCC ID on it says 2al3b-esp-m that seams to indicate a ESP-8285
(https://fccid.io/2AL3B-ESP-M/User-Manual/User-Manual-3413969)
I tried to flash it with Arduino ESP8285 samples and it flash right but I can't figure how / where I could retrieve the functionality that I had in the pas (login the the web server of it and interact with the TTL...
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8285
Features: WiFi, Embedded Flash
Crystal is 26MHz
MAC: 84:0d:8e:41:22:82
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 1MB
Compressed 280400 bytes to 205882...
Wrote 280400 bytes (205882 compressed) at 0x00000000 in 18.3 seconds (effective 122.7 kbit/s)...
Hash of data verified.

Leaving...

https://github.com/SmartArduino/SZDOITWiKi/wiki/Drivers%2CFirmwares%2C-and-Tools


text:
Scope of RtcDateTime object when declared outside of a function
I'm trying to merge 2 Arduino samples, in order to be able to use DS3231 RTC module with ESP8266 WiFi simple web server.
My RTC library is this:
https://github.com/Makuna/Rtc/wiki
Generally, to code runs ok (I have the Web server responses to my browser calls, and I think the DS3231 RTC code also works). But when I'm trying to use a variable from within the RTC object into the Web server function - I get nothing.
I thought declaring the 'now' object outside any function (Setup() nor Loop()) will make it global, and when I'll update it in the Loop() function using
now = Rtc.GetDateTime();

It will be available to other functions as well, but all I get is "0" when I try to print it.
My code is here:
Definitions part:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* This block is for I2C protocol for DS3231 module (for normal hardware wire use below) */
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
/* The above block is for I2C protocol and DS3231 module  (for normal hardware wire use above) */

ESP8266WebServer server(80);
RtcDateTime now;

My Loop():
void loop(void) {
  now = Rtc.GetDateTime();
  Serial.println(now.Minute());
  server.handleClient();
  delay(500);

}

And all I get is "0" printed.
Any help would be appreciated!

And your code outputs the correct minutes, if you move the declaration of now into the loop() function?

What do you get if you remove the WiFi Web server code?

Update: Thank you so much for everyone looked into it. I've just now tried to debug it, and found that for a strange reason - my DS3231 module stopped working (forgot the time, and also didn't advance, even after program resets). What worked was to disconnect it from power and take out the battery. Now it works ok, and the scope of the variable is good also. Should I delete my question now? or just leave it like this? Many thanks again! I appreciate it so much!

As was suggested by more 'native' friends here - I'm 'Answering my question' to make things clear.
After a check and debug - I've found a mysterious behavior that happened to my DS3231 module. Probably a mistaken initializing set of calls - made it stop working - not getting time updates and not counting the time at all. (Freeze at 1/1/2000, 00:00:00).
Disconnecting it from power source, and taking out the battery - returned it to normal behavior, able to get time updates, and answering the calls from the library.
When that part solved - everything else went as easy as it should.
The code sample I posted in my question (declaring the 'now' object outside of setup() and loop() functions) made that object global, so another function (WebServer) can read its current value and use it internally.
Thanks everyone who looked at my problem and helped,
It was a great lesson about how not to take anything as 'known' without double-checking.


text:
Is possible use Macro F() with Integer and Other types of variable?
i have a sketch that is using very memory RAM of my Atmega2560 (is a giant project), and i need use various "println" because i have a TFT screen and i need to show data on the screen to user see. So, i'm using macro F() to use less RAM memory (example: Serial.println("Hi Naruto-kun") to Serial.println(F("Hi Naruto-kun")). But, it only work if the data entered in F() were to Const String, when i need, by example, show a array of integers, nothing work.
Example:
tft.print(F(mediaTotPg[1]));

This do not work because mediaTotPg is a Integer Array and the errors returned are:
" #define F(string_literal) (reinterpret_cast(PSTR(string_literal))) "
Finally, is possible show integers not const with Macro F()?

For a constant array of integers you need to use PROGMEM and the various pgm_read_*() functions.
You can read more, and find examples, on the Arduino PROGMEM manual page.

Only const array?

Yes. You can't change things in PROGMEM, so it has to be const.  It doesn't have to be an array though, you could use single values, but that makes no sense since if they are const the compiler will optimise them out into inline literals anyway.

F() puts the constant string literal in the flash part of your device. This way it does not use the RAM space otherwise needed.
But your mediaTotPg array is most probably (you didn't say anything about it) a non-const variable, and can't be put in flash memory.
If the values to be shown are in fact const, you need to put them in the flash memory. As Majenko's answer points out in short, you need to use the PROGMEM section for the values, as described on the Arduino PROGMEM page.
The answer to your question is: No, it is not possible to use the macro F() with any type of variable that is not const, and it is not possible to use it for any other type than a string literal.


text:
Arduino AES encryption, working example or tutorial
I am quite new to idea of encryption and am trying to use aes-256-ecb encryption.  I am using library called "Arduino cryptography". Unfortunately I could not find any tutorial that would explain how to encrypt a json string (and other things latter) using a  key.
I have a function that generates same key on both sides of Arduino and php script on a server side, but I could not find a working tutorial (except the case of obsolete buggy library with instruction like : "copy this text" and even that doesn't work.
Unfortunately libraries examples do not bother to show how to retrieve  encrypted string or explain what is what and instead just focus on checking how long encryption takes.
Does any of you know of some tutorial or an example from which I could engineer a solution?
library link:The library
in buioltin example there is a code of:
cipher->decryptBlock(buffer, test->ciphertext);

But I do not understand where is the output and where the input here
Second  question would be if I can use other modes like the mentioned GCM simply by changing the value in
static TestVector const testVectorAES256 = {
    .name        = "AES-256-ECB",
    .key         = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                    0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F},
    .plaintext   = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                    0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF},
    .ciphertext  = {0x8E, 0xA2, 0xB7, 0xCA, 0x51, 0x67, 0x45, 0xBF,
                    0xEA, 0xFC, 0x49, 0x90, 0x4B, 0x49, 0x60, 0x89}
};

or how?
After bits and strougles I have managed to get this working, but next step is how to make it take a string:
/*Skúška kódovania GCM-AES256#*/

#include <Crypto.h>
#include <AES.h>
#include <GCM.h>
//#include <pgmspace.h>

struct TestVector
{
    const char *name;
    uint8_t key[32];
    uint8_t plaintext[60];
    uint8_t ciphertext[60];
    uint8_t authdata[20];
    uint8_t iv[12];
    uint8_t tag[16];
    size_t authsize;
    size_t datasize;
    size_t tagsize;
    size_t ivsize;
};

static TestVector const testVectorGCM PROGMEM = {
    .name        = "AES-256 GCM",
    .key         = {0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,
                    0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08},
    .plaintext   = {0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5,
                    0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,
                    0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
                    0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,
                    0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53,
                    0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
                    0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57,
                    0xba, 0x63, 0x7b, 0x39},
    .ciphertext  = {0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,
                    0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,
                    0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
                    0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,
                    0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,
                    0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
                    0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,
                    0xbc, 0xc9, 0xf6, 0x62},
    .authdata    = {0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xab, 0xad, 0xda, 0xd2},
    .iv          = {0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
                    0xde, 0xca, 0xf8, 0x88},
    .tag         = {0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68,
                    0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b},
    .authsize    = 20,
    .datasize    = 60,
    .tagsize     = 16,
    .ivsize      = 12
};

TestVector testVector;
byte buffer[128];

bool testCipher_N(AuthenticatedCipher *cipher, const struct TestVector *test, size_t inc)
{
    size_t posn, len;
    uint8_t tag[16];

    crypto_feed_watchdog();

    cipher->clear();
    if (!cipher->setKey(test->key, cipher->keySize())) {
        Serial.print("setKey ");
        return false;
    }
    if (!cipher->setIV(test->iv, test->ivsize)) {
        Serial.print("setIV ");
        return false;
    }

    memset(buffer, 0xBA, sizeof(buffer));

    for (posn = 0; posn < test->authsize; posn += inc) {
        len = test->authsize - posn;
        if (len > inc)
            len = inc;
        cipher->addAuthData(test->authdata + posn, len);
    }

    for (posn = 0; posn < test->datasize; posn += inc) {
        len = test->datasize - posn;
        if (len > inc)
            len = inc;
        cipher->encrypt(buffer + posn, test->plaintext + posn, len);
    }

    Serial.println("Vystup:\n");
    for(uint8_t i=0; i<sizeof(buffer); i++) printf("0x%X,",buffer[i]);

    return true;
}

void testCipher(AuthenticatedCipher *cipher, const struct TestVector *test)
{
    bool ok;

    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;

    Serial.print(test->name);
    Serial.print(" ... ");

    ok  = testCipher_N(cipher, test, test->datasize);
    /*ok &= testCipher_N(cipher, test, 1);
    ok &= testCipher_N(cipher, test, 2);
    ok &= testCipher_N(cipher, test, 5);
    ok &= testCipher_N(cipher, test, 8);
    ok &= testCipher_N(cipher, test, 13);
    ok &= testCipher_N(cipher, test, 16);*/

    if (ok)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}

void perfCipherSetKey(AuthenticatedCipher *cipher, const struct TestVector *test, const char *name)
{
    unsigned long start;
    unsigned long elapsed;
    int count;

    crypto_feed_watchdog();

    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;

    Serial.print(name);
    Serial.print(" SetKey ... ");

    start = micros();
    for (count = 0; count < 1000; ++count) {
        cipher->setKey(test->key, cipher->keySize());
        cipher->setIV(test->iv, test->ivsize);
    }
    elapsed = micros() - start;

    Serial.print(elapsed / 1000.0);
    Serial.print("us per operation, ");
    Serial.print((1000.0 * 1000000.0) / elapsed);
    Serial.println(" per second");
}

void perfCipherEncrypt(AuthenticatedCipher *cipher, const struct TestVector *test, const char *name)
{
    unsigned long start;
    unsigned long elapsed;
    int count;

    crypto_feed_watchdog();

    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;

    Serial.print(name);
    Serial.print(" Encrypt ... ");

    cipher->setKey(test->key, cipher->keySize());
    cipher->setIV(test->iv, test->ivsize);
    start = micros();
    for (count = 0; count < 500; ++count) {
        cipher->encrypt(buffer, buffer, 128);
    }
    elapsed = micros() - start;

    Serial.print(elapsed / (128.0 * 500.0));
    Serial.print("us per byte, ");
    Serial.print((128.0 * 500.0 * 1000000.0) / elapsed);
    Serial.println(" bytes per second");
}

void setup(){
    Serial.begin(115200);
    Serial.println("Začínam\n");
    GCM <AES256> *gcm=0;
    gcm= new GCM<AES256>();
    gcm->setKey(testVectorGCM.key, 32);
    gcm->setIV(testVectorGCM.iv,testVectorGCM.ivsize);
    crypto_feed_watchdog();
    //gcm->encrypt(buffer,testVectorGCM.plaintext,60);
    testCipher(gcm,&testVectorGCM);
    delete gcm;
    //gcm.encrypt(&vstupny,&vystup,49);
    crypto_feed_watchdog();
    Serial.println("Vystup: \n");
    for(uint8_t i=0; i<50;i++) Serial.print(buffer[i]);
}

void loop(){
    delay(1000);
    Serial.print(".");
}

I need to be able to get the text on PHP side

It is not recommended to use ECB mode. GCM is currently state of art.

install the library using your Arduino IDE, then look at the examples ... some of them show encrypt and decrypt functions ..... or look at the examples online https://github.com/OperatorFoundation/Crypto .... that link is found in the library.json file

your avatar is ironic, considering the textbook image used to show why ECB sucks.

@Kwasmich and dandavis I take your Point

@jsotola I have seen them, but I still do not understand them where the output comes and what is what

Kind of an answer. After the advise from @Kwasmich I have converted to aes-256-gcm.
Upgraded to UTF-8 thanks to Edgar Bonet

Based mostly on GCMTest example comming with Arduino Cryptograhy libraries:-----------------------------------------------
Shared between Encryption and decrition
First need to define parts which will not change:
#include <Crypto.h>
#include <AES.h>
#include <GCM.h>

struct TestVector
{
    const char *name;
    uint8_t key[32];
    uint8_t authdata[20];
    uint8_t iv[12];
    uint8_t tag[16];
    size_t authsize;
    size_t tagsize;
    size_t ivsize;
};

static TestVector const testVectorGCM PROGMEM = {   //Dont forget to change the Values here
    .name        = "AES-256 GCM",
    .key         = {0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,
                    0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08},
    .authdata    = {0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xab, 0xad, 0xda, 0xd2},
    .iv          = {0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
                    0xde, 0xca, 0xf8, 0x88},
    .tag         = {0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68,
                    0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b},
    .authsize    = 20,
    .tagsize     = 16,
    .ivsize      = 12
};

Now create a global buffer (easier to understand then pointers)
TestVector testVector;
byte buffer[128];

Encrytpion
{
    memcpy_P(&testVector, test, sizeof(TestVector));   //Load into memory
    test = &testVector;
    size_t posn, len;
    uint8_t tag[16];
    crypto_feed_watchdog();    //To protect from Watchdog reseting this function

It is important to clear memory of any ciphering before doing one:
    cipher->clear();

    cipher->setKey(test->key, cipher->keySize());    //Setting key
    cipher->setIV(test->iv, test->ivsize);     //vector
    for (posn = 0; posn < test->authsize; posn += datasize) {
        len = test->authsize - posn;
        if (len > datasize)
            len = datasize;
        cipher->addAuthData(test->authdata + posn, len);   //To make hack even more confusing
    }
    Serial.print("input numbers ");
    for(uint8_t i=0; i<60; i++) Serial.printf("%X",buffer[i]);
    Serial.println();

    for (posn = 0; posn < datasize; posn += datasize) {
        len = datasize - posn;
        if (len > datasize) len = datasize;
        crypto_feed_watchdog();
        cipher->encrypt((uint8_t*)buffer + posn, buffer + posn, len); //This is why we are here
        crypto_feed_watchdog();
    }
    Serial.println("Vystup:\n");
    for(uint8_t i=0; i<sizeof(buffer); i++) printf("0x%X,",buffer[i]);
}

Decryption
void decrypt(AuthenticatedCipher *cipher, const struct TestVector *test, size_t datasize){
    bool ok;

    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;
    size_t posn, len;
    uint8_t tag[16];
    crypto_feed_watchdog();
    cipher->clear();
    cipher->setKey(test->key, cipher->keySize());
    cipher->setIV(test->iv, test->ivsize);
    for (posn = 0; posn < test->authsize; posn += datasize) {
        len = test->authsize - posn;
        if (len > datasize)
            len = datasize;
        cipher->addAuthData(test->authdata + posn, len);
    }

    for (posn = 0; posn < datasize; posn += datasize) {
        len = datasize - posn;
        if (len > datasize)
            len = datasize;
        cipher->decrypt((uint8_t*)buffer + posn, buffer + posn, len);
    }

    Serial.print("\nVystup: ");
    for(uint8_t i=0; i<60;i++) Serial.printf("%c",(char)buffer[i]);
    Serial.println();

}

-----------------------------------------------
full example:
/*Skúška kódovania GCM-AES256#*/

#include <Crypto.h>
#include <AES.h>
#include <GCM.h>

struct TestVector
{
    const char *name;
    uint8_t key[32];
    uint8_t authdata[20];
    uint8_t iv[12];
    uint8_t tag[16];
    size_t authsize;
    size_t tagsize;
    size_t ivsize;
};

static TestVector const testVectorGCM PROGMEM = {
    .name        = "AES-256 GCM",
    .key         = {0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,
                    0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
                    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08},
    .authdata    = {0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
                    0xab, 0xad, 0xda, 0xd2},
    .iv          = {0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
                    0xde, 0xca, 0xf8, 0x88},
    .tag         = {0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68,
                    0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b},
    .authsize    = 20,
    .tagsize     = 16,
    .ivsize      = 12
};

TestVector testVector;
byte buffer[128];

void encrypt(AuthenticatedCipher *cipher, const struct TestVector *test, size_t datasize)
{
    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;
    size_t posn, len;
    uint8_t tag[16];
    crypto_feed_watchdog();

    cipher->clear();
    cipher->setKey(test->key, cipher->keySize());
    cipher->setIV(test->iv, test->ivsize);
    for (posn = 0; posn < test->authsize; posn += datasize) {
        len = test->authsize - posn;
        if (len > datasize)
            len = datasize;
        cipher->addAuthData(test->authdata + posn, len);
    }
    Serial.print("Cisla: ");
    for(uint8_t i=0; i<60; i++) Serial.printf("%X",buffer[i]);
    Serial.println();

    for (posn = 0; posn < datasize; posn += datasize) {
        len = datasize - posn;
        if (len > datasize) len = datasize;
        crypto_feed_watchdog();
        cipher->encrypt((uint8_t*)buffer + posn, buffer + posn, len);
        crypto_feed_watchdog();
    }
    Serial.println("Vystup:\n");
    //      Decrypt
    for(uint8_t i=0; i<sizeof(buffer); i++) printf("0x%X,",buffer[i]);
}

void decrypt(AuthenticatedCipher *cipher, const struct TestVector *test, size_t datasize){
    bool ok;

    memcpy_P(&testVector, test, sizeof(TestVector));
    test = &testVector;
    size_t posn, len;
    uint8_t tag[16];
    crypto_feed_watchdog();
    cipher->clear();
    cipher->setKey(test->key, cipher->keySize());
    cipher->setIV(test->iv, test->ivsize);
    for (posn = 0; posn < test->authsize; posn += datasize) {
        len = test->authsize - posn;
        if (len > datasize)
            len = datasize;
        cipher->addAuthData(test->authdata + posn, len);
    }

    for (posn = 0; posn < datasize; posn += datasize) {
        len = datasize - posn;
        if (len > datasize)
            len = datasize;
        cipher->decrypt((uint8_t*)buffer + posn, buffer + posn, len);
    }

    Serial.print("\nVystup: ");
    for(uint8_t i=0; i<60;i++) Serial.printf("%c",(char)buffer[i]);
    Serial.println();

}

void setup(){
    Serial.begin(115200);
    Serial.println("Začínam\n");
    GCM <AES256> *gcm=0;
    gcm= new GCM<AES256>();
    gcm->setKey(testVectorGCM.key, 32);
    gcm->setIV(testVectorGCM.iv,testVectorGCM.ivsize);
    crypto_feed_watchdog();
    memset(buffer, (int)'\0', sizeof(buffer));
    char vstup[30]="Tak to netuším";     //String containing Non-Asci characters
    for(uint8_t i=0; i<30; i++) buffer[i]=vstup[i];
    encrypt(gcm,&testVectorGCM,30);
    decrypt(gcm,&testVectorGCM,30);
    delete gcm;
}

void loop(){
    delay(1000);
    Serial.print(".");
}

simple key generator in PHP:
<?php
for($i=0;$i<31;$i++) printf("0x%X,",random_int(0,0xFF));
printf("0x%X\n",random_int(0,0xFF));
?>

Re “I could not figure-out how to convert utf-8 into numbers”: an UTF-8 text is a sequence of 8-bit numbers. There is nothing to convert.

I understand that, but the problem is that when one (char)letter get translated to multiple numbers (uint8_t), then converting it back require more then one conversion per number: needs to know how many numbers apply now and as such I could not convert numbers back to char letters

the important part is "and back" as while I could decrypt to the same int array I could not convert the int array into char array with utf-8 letters.

A char is not a letter (or a character): it's a byte. It synonym of int8_t and differs from uint8_t only by signedness. UTF-8 encodes each character as a sequence of 8-bit “code units”, thus an UTF-8 encoded text is just a byte array. You don't care about having a variable-width encoding unless you are converting to/from some form of wide characters. You can encrypt and decrypt the text with the same ease as ASCII text. If it happens to be stored as an array of char, you encrypt it with cipher->encrypt((uint8_t*)buffer...) and recover it with cipher->decrypt((uint8_t*)buffer...).

What are the authdata, iv and tag parameters for? And should I change them too?

I will start with tag witch is something like a check When Decrypting. (think of it same as a checksum), SO it is send with the data from server to client
IV and Auth data are handy way to to make same input generate different output even with the same key. the benefits it has against the brute force attack alone are enormous (there are many others) I generate authdata each time on both sides under same algoritm and send the IV from client. Un

at early stages you can keep auth as constant. (create your own),
same as in case of IV (but this was first one of the two I have generated)

@Tomas Can you show an example of how you decrypt this with php?

Mine decryption routine is too complicated, but I have been using php-aes-gcm composer plugin from spomky-labs, which does contain examples.
https://github.com/Spomky-Labs/php-aes-gcm

you will find a composer in your main hosting panel from any competent  webhosting company, if like me you are using less competent webhosting for developement (planethippo) and more competent for deployment, then you might have to either get a lamp and install composer there or just copy the composer directories from better managed server.
As a warning that when you are converting key, auth and tag from C++ approach to php approach, make sure the variable uses it always as string and that you use each number with two digits (without leading 0x).

Using your arduino sketch then feeding the params into openssl_decrypt (with hex2bin()), or that lib, does not produce any result. I'm sure you'd help the community if you'd make a tutorial/video about the whole cycle (encrypt/decrypt on the arduino then encrypt/decrypt on the web server) as there are absolutely zero meaningfull practical examples on the internet.

I am disgraphic myself, so major tutorial in written form even about how to butter a bread is out of mine league.
Next weak I have inspector inspection (mine inspecting is inspected), so Ill do a video tutorial in two weeks time.  I have wanted to start youtube channel for a while, but mine last attempt died when lorry drow (i know its driven, but it sounds like there should be a past perfect short for being driven) over mine phone just after filming... Sorry, cant do it sooner as I want Rob W to pass me...


text:
Arduino webserver POST receive varriables
I have been learning lower level data reading on internet communication
As a part of bigger project I am testing web interface.
So far I could get main website displayed and by seeing the web-address read the data from GET request. As I intend to send codes I wish to use POST method.
I am Trying to make this as standalone class for mine future projects, so I am only sending the class method itself. (Latter it would take websites content as a string, but for now input variables are yet to be implemented)
I am using esp8266, but would prefer to avoid esp8266 specific libraries as I wish it to eventually run on its realtek equivalent.
The code:
uint8_t Stranky::Stav(String obsahStranky, uint8_t obnovovat){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    char vstupRiadok[150]={'\0'};
    uint8_t i=0;
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        vstupRiadok[i]=c;
        if(c=='\n' || i>=149) {
            Serial.println(vstupRiadok);
            //------------Extract variables here--------
            for(uint8_t j=0; j<149; j++) {
                //Serial.print(vstupRiadok[j]);
                vstupRiadok[j]='\0';
            }
            i=0;
        } else i++;
        if (c == '\n' && currentLineIsBlank) {
            Serial.println("Sending page");
            client.println(ohlasSa(1,1));
            client.println("<!DOCTYPE HTML>");
          // send a standard http response header
            client.println(" <meta charset=\"utf-8\">");
            client.println("
 Nic nove
");
            client.println("<form method='POST'>");
            client.println("Name:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nSurname:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input   type='reset'/>  </form> ");
            client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("Prehliadač dpojený");
  }
}

This results in Browser code:
<!DOCTYPE HTML>
 <meta charset="utf-8">

 Nic nove

<form method='POST'>
   Name:<input type="text" id="Name" name="Name"/>

   Surname<input type="text" id="Surname" name="Surname">

<input type="submit" value="Submit"/><input type='reset'/>  </form>

When I send any data over the form it does not get received  and only receive these:
WS:ac
:ref 1
WS:av
:ref 2
:ur 2
:rn 469
POST / HTTP/1.1

Host: 192.168.43.209

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: sk,cs;q=0.8,ru;q=0.6,en;q=0.4,en-US;q=0.2

Accept-Encoding: gzip, deflate

Referer: http://192.168.43.209/

Content-Type: application/x-www-form-urlencoded

Content-Length: 25

Connection: keep-alive

Upgrade-Insecure-Requests: 1

Sending page

No post, or Cookie variables that I could extract
I am far from home and too short of data to be installing more software like wire-shark over phones network sharing

I found that I have to decode a json object, but how do I get it from received data?

Based on codebreakers code I have been able to combine it into working one
The problem was on a fact that communication starts with header variables, then empty line, then body containing the variables
First get the connection: and create base variables
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)

Get one incoming character:
            char c = client.read();

Now deal with new line character first
If the last line was empty That would mean: Header is finished and moving to the body of the incoming data If not change currentLineIsBlank (until new line gets its first character)
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }

Now lets deal with any other character then new line:
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }

Make sure that our array doesn't overflow
            if(i>=81) linEnd=1;

Now we know what is happening we can take some action after the buffer line is finished
if we are at the body stage, but we havent "finised" sending code
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));

Start extracting characters from body of the incoming data.
In a simple form like ours POST variables are on a last line, so we will just keep rewriting the line
                    uint8_t k=0;
                    while (client.available()) {
                        fullLine[k]=client.read();
                        Serial.printf(F("%c"),fullLine[k]);
                        if(k<80) k++;
                        if(fullLine[k]=='\n') {
                            k=0;
                            Serial.println();
                        }
                    }
                    // Here you can extract variables as shown in codebreakers' answer

Finaly send then websites html code:
                    Serial.print("Sending page\n");
                    client.println(heatheRoutine()); //I have extra routine to inject heather so I do not have to write it every time I write a page
                    client.println("<!DOCTYPE HTML>");
                    // send a standard http response header
                    client.println(" <meta charset=\"utf-8\">");
                    client.println("
Fill the form now !!!
");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> ");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("\n");
                    break;
                }

If we are not dealing with the body yet:
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }

If we have finished what we have wanted we need to get out of communication loop
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }

And close the connection:
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}

Complete code:
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)
            char c = client.read();
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }
            if(i>=81) linEnd=1;
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));
                    uint8_t k=0;
                    while (client.available()) {
                        riadok[k]=client.read();
                        Serial.printf(F("%c"),riadok[k]);
                        if(k<80) k++;
                        if(riadok[k]=='\n') {
                            k=0;
                            Serial.println();
                        }
                    }
                    // Here you can extract variables as shown in codebreakers' answer

                    Serial.print("Sending page\n");
                    client.println("HTTP/1.1 200 OK\r\n");
                    client.println("Content-Type: text/html\r\n");
                    client.println("Connection: close\r\n");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println(" <meta charset=\"utf-8\">");
                    client.println("
Fill the form now !!!
");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/>
\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\">
\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> ");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("\n");
                    break;
                }
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}

Check your definition of
String vstupRiadok

it should not be
String vstupRiadok="                                      "; //80 blanks

I would replace it with a decent sized fixed char anyway
char vstupRiadok[81] = {'\0'};

if you create an empty line or other text do not forget to write the end terminator '\0' and make sure the char array is +1 the size for the longest string totake
As String class is a problem on its own as an Arduino class.
The HTML code generated has a missing
 <meta charset    ="utf-8">

error in the dev-tools. Aside from that whats the server code running on the Arduino,its not given. The class creates a html page, but at least in FF75 it tries to call server.ip\odpoved - so there has to be some js or Arduino code to decode this route there are no params attached from the form.
EDITAn extraction routine would look like:
bool currentLineIsBlank = true;
bool currentLineIsGet = true;
uint8_t tCount = 0;
char tBuf[64];
uint8_t n=0;
uint8_t s=0;
char *pch;

Serial.print("Client request: ");

 while (client.connected()) {
  while (client.available()) {
    char c = client.read();

    if (currentLineIsGet && tCount < 63) {
      tBuf[tCount] = c;
      tCount++;
      tBuf[tCount] = 0;
    }

    if (c == '\n' && currentLineIsBlank) {
      Serial.println(tBuf);
      // retrieve the POST data
      Serial.print("POST data: ");
      while (client.available()) Serial.write(client.read());
      Serial.println();

      pch = strtok(tBuf, "?");

      while (pch != NULL) {
        if (strncmp(pch, "Name=", 5) == 0) {
          pch = pch+6;
          char Name [24] = {'\0'};
          while(pch != '&'){
             char Name [n] = pch;
             n++;
           }
          char Name [n+1] = {'\0'};
          Serial.print("Name="); Serial.println(Name);
        }

        if (strncmp(pch, "Surname=", 8) == 0) {
          pch=pch+9;
          char Surname[24] = {'\0'};
          while(pch != '\r') {   // check if your response has that after the content or if its '\0'
             char Surname [s] = pch;
             s++;
           }
          char Surname [s+1] = {'\0'};
          Serial.print("Surname="); Serial.println(Surname);
        }
        pch = strtok(NULL, "& ");
      }
  // here the Sending response part starts

You do not need a JSON parser for this just get the post request

Comments are not for extended discussion; this conversation has been moved to chat.