message:
How should I customize UIPEthernet constants?

I am using UIPEthernet to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. I'm customizing a number of its `#define` parameters to change default settings to save space, but I'm not sure I'm doing it correctly.  It's clearly designed to facilitate per-sketch customization, but things aren't quite working for me, and I can't tell if it's me doing it wrong, or if the customization doesn't quite do what I'm expecting.

Specifically, the comments at the top of `utilities/uip-conf.h` say:

>uIP has a number of configuration options that can be overridden  for each project. These are kept in a project-specific uip-conf.h file and all configuration names have the prefix UIP_CONF.

So that sounds great - I've copied `uip-conf.h` into my sketch (into the top directory next to my other sources), adjusted it appropriately, and ... nothing changes.

Now, I'm #including `<UIPEthernet.h>` into my source files, and everything compiles using the Arduino IDE (v1.8.10). Looking in the library, I can see `<UIPEthernet.h>` includes `<utilities/uipopt.h>`, which in turn includes `"uip-conf.h"` (note the quotes). So I think it's intended to be picking up my local one. But it doesn't - it uses the original one from the library.

My understanding of `#include "example.h"` is that it looks for `example.h` relative to the *current file location*, (ie `<utilities/uipopt.h>`, so *utilities/*), so I'm actually seeing correct inclusion behaviour and now I don't see how this customization approach could ever work!

I tried adding the `#include "uip-conf.h"` to my own sources, and that sort of works for my sources, but of course doesn't affect the library `.cpp` files themselves which still see the original version.

I could probably drag the entire lib into my sketch and fix up the includes, but that seems like the wrong answer. It's extensively designed to be customizable. Do you know what steps need to be taken to do it please? (Or a pointer to some docs would be fine!) Thanks!

body:
Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".

The *project* in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

----------

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as

    #ifdef UIP_CONF_UDP_CONNS
    #define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
    #else /* UIP_CONF_UDP_CONNS */
    #define UIP_UDP_CONNS    10
    #endif /* UIP_CONF_UDP_CONNS */

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.

With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:

  mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30

platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.


sender: user

message:
Reading multiple pins via registers on the Arduino Due

I would like to read multiple pins at once in Arduino Due via registers just like PINB, PINC, PIND of the arduino uno. I know that the pins will be scattered to multiple registers, but i deduce it would still be faster this way since there for sure there will be multiple pins on a single register rather than call digitalRead 40 times.

Arduino shared the documentation for what digital/analog pins corressponds to the what ports to the actual sam chip, i just need that snippet of code that reads via registers.

So if any can give me the equivalents to these, It would be greatly appreciated:

- DDRx - The Port C Data Direction Register - read/write
- PORTx - The Port C Data Register - read/write
- PINx - The Port C Input Pins Register - read only

sender: assistant

body:
You will find a good introduction on using port registers [here][1]. It also mentions some cons and pros of using port manipulation.

  [1]:https://www.arduino.cc/en/Reference/PortManipulation


message:
Interfacing Arduino with Python Serial

I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in  Python.

**Python Code**

    import matplotlib.pyplot as plt
    from scipy.fftpack import fft
    from scipy.io import wavfile # get the api
    import serial, time

    samplerate, data = wavfile.read("sample.wav")
    samples = len(data)
    plt.plot(data[:20000])
    arduino = serial.Serial('COM4', 9600, timeout=.1)
    time.sleep(1) #give the connection a second to settle

    for i in range(0,samples):

        arduino.write(data[i])
        time.sleep(1)
        print(arduino.readline())

**Arduino Code**

      void setup() {

      Serial.begin(9600);
      }
      int i = 0;
      int newdata[10];
      void loop() {
         if(Serial.available() > 0) {
              int data = Serial.read();
              newdata[i] = data;
              Serial.print(newdata[i]);
              i = i+1;
            }
       }
The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python.
I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.[![Python cmd window output][1]][1]

  [1]: https://i.stack.imgur.com/0IigV.jpg

body:
```
    arduino.write(data[i].tobytes())
    time.sleep(.1)
    print(int.from_bytes(arduino.readline(),byteorder='little') )
```
Is this what you whant?


body:
I have found a way to tackle this.
Here is my arduino code:

    char buf[100];
    const double coefficients[28] = {
    -0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
     0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
    -0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
     0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
     0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
    -0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
    -0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
    };

    int order_of_filter = 27;
    int sample_array[28] = {};
    double output_sample = 0;
    void setup()
    {
      Serial.begin(9600);
      Serial.setTimeout(50000);
    }
    void loop()
    {
      int  sample_in;
      int num_read = Serial.readBytesUntil('\n', buf, 100);
      buf[num_read] = '\0';
      sscanf(buf, "%d", &sample_in);
      for (int i = order_of_filter; i > 0; i--)
      {
        sample_array[i] = sample_array[i-1];
      }

      sample_array[0] = sample_in;

      for(int i = 0; i<=order_of_filter; i++)
      {
        output_sample = output_sample + sample_array[i]*coefficients[i];
      }
      Serial.println(output_sample);
      output_sample = 0;
    }
And here is my Python Code:

   import matplotlib.pyplot as plt
   from scipy.fftpack import fft
   from scipy.io import wavfile # get the api
    import serial, time
    import numpy as np
   import sounddevice as sd

   arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
  time.sleep(3) #time to get connection ready
  # %%

  fs, data = wavfile.read('hfsound.wav')
  samples = len(data)
  #Plot the signal
  plt.plot(data[:samples])
  plt.ylabel("Amplitude")
  plt.xlabel("Time")
  plt.title("Time Domain Response of the Input Signal")
  plt.grid()
  plt.show()
  #Plotting fft
  fft_input = fft(data)
  half_length = int(len(fft_input)/2)
  omega_axis = np.linspace(0, fs/2, half_length)
  fft_n = fft_input[:half_length]
  plt.plot(omega_axis,abs(fft_n))
  plt.xlabel('frequency')
  plt.ylabel('Amplitude')
  plt.title("Frequency Domain Response of the Input Signal")
  plt.grid()
  plt.show()
  # %%

  #Declare an Array of zeros
  outputArray = np.zeros(64000)
  #Sending data to aurdino
  for i in range(samples):
       number = data[i]
       string = str(number).encode(encoding='utf-8') + b'\n'
       arduino.write(string)
       byt = arduino.read_until();
       print(byt.strip())
       outputArray[i] = byt.strip()

  arduino.close()
  # %%

  #Plotting Output waveform
  #Plot the time-domain output signal
  plt.plot(outputArray[:len(outputArray)])
  plt.ylabel("Amplitude")
  plt.xlabel("Time")
  plt.title("Time Domain Response of the Output Signal")
  plt.grid()
  plt.show()

  #Plotting fft of output
  fft_out = fft(outputArray)
  half_length = int(len(fft_out)/2)
  omega_axis = np.linspace(0, fs/2, half_length)
  fft_n = fft_out[:half_length]
  plt.plot(omega_axis,abs(fft_n))
  plt.xlabel('frequency')
  plt.ylabel('Amplitude')
  plt.title("Frequency Domain Response of the Output Signal")
  plt.grid()
  plt.show()
  # %%

  #Playback code
  sd.play(outputArray, fs)
  # %%


message:
Basketball board arduino endlessly transmitting shot scored

I've been working on trying to get [this][1] arduino project I found to work but I've been encountering some problems.

The project was designed for an Arduino mega 2560 but I've been using my UNO and breadboard for it along with the Software Serial library. I'm very, very new to working with Arduinos so if there are any basic things I might be missing please do mention them.

Components:

 - Arduino UNO
 - Bluetooth HC-05 module
 - E18-D80NK Proximity Sensor
 - Saeed Grove 420 Proximity Sensor
 - 10k Ohm resistor
 - Breadboard
 - The included app in the above link

The issues I'm facing are

a)Initially, the proximity sensor would detect if I e.g. moved my hand infront of it and send the data to the app and it would increment the score and play the sound.

However, if I tried flicking the vibration sensor and not moving my hand infront of the proximity sensor, a miss wouldn't be recorded. Initially, even just flicking the proximity sensor would record a score as well, but later it would just do nothing.

b)I'm not sure what is the problem, but now nothing happens at all. The wiring and everything is all connected in the same way as before, but now even though the proximity sensor lights up if I move my hand infront of it, no scores are transmitted by the HC-05 module or anything. I have tried keeping the Serial Monitor open but nothing is printed on it.

Also, the code I've pasted below is after including the SerialSoftware library header and after deleting all the code for setting the LED lights which is still available in the link above. Problem B started occurring before I did this, so I don't think that has anything to do with it. Just didn't want to include the LEDs in my project.

Any help would be really appreciated, thank you!! If there's any information I've missed out on, please let me know.

Edit: Okay, so I had the RX and TX wires of the module in the incorrect sockets. The RXD of the hc-05 module is now in pin 11 and the TXD in pin 10. Data is being transmitted, but it just endlessly keeps incrementing the shots even if the proximity sensor isn't detecting anything. :/ Any suggestions?

Edit2: Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.

```
#include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX

//----------------------------------------------------------------------------//
// Filename    : Scoreboard.ino                                               //
// Description : Smart Basketball Scoreboard                                  //
// Version     : 1.1.0                                                        //
// Author      : Marcelo Avila de Oliveira <marceloavilaoliveira@gmail.com>   //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// DEFINITIONS                                                                //
//----------------------------------------------------------------------------//

// TURN ON DEBUG MODE
// #define DEBUG
// #define DEBUG_PROX
// #define DEBUG_VIBR

//----------------------------------------------------------------------------//
// CONSTANTS                                                                  //
//----------------------------------------------------------------------------//

// PINS
const int prox_pin = 2;
const int vibr_pin = 3;

// TIME
const unsigned long wait_interval = 3000;

//----------------------------------------------------------------------------//
// VARIABLES                                                                  //
//----------------------------------------------------------------------------//

// TIME
unsigned long wait_time;

// STATUS
boolean prox = false;
boolean vibr = false;
boolean wait = false;

//----------------------------------------------------------------------------//
// FUNCTIONS (SETTINGS)                                                       //
//----------------------------------------------------------------------------//

void setup() {
    // INITIATE PINS
    pinMode(prox_pin, INPUT);
    pinMode(vibr_pin, INPUT);

    // INITIATE SERIAL COMMUNICATION
    Serial.begin(9600);

    // INITIATE BLUETOOTH COMMUNICATION
    setup_bluetooth();

    #ifdef DEBUG
        Serial.println("Board is alive");
        Serial.println();
    #endif
}

void setup_bluetooth() {
    #ifdef DEBUG
        Serial.println("Setting Bluetooth");
        Serial.println();
    #endif

    Serial1.begin(38400);                   // Set baud rate
    Serial1.print("\r\n+STWMOD=0\r\n");     // Set to work in slave mode
    Serial1.print("\r\n+STNA=Arduino\r\n"); // Set name
    Serial1.print("\r\n+STOAUT=1\r\n");     // Permit Paired device to connect me
    Serial1.print("\r\n+STAUTO=0\r\n");     // Auto-connection should be forbidden here
    delay(2000);                            // This delay is required.
    Serial1.print("\r\n+INQ=1\r\n");        // Make the slave inquirable
    delay(2000);                            // This delay is required.
    while (Serial1.available()) {           // Clear data
        delay(50);
        Serial1.read();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (CHECK)                                                          //
//----------------------------------------------------------------------------//

void check_prox() {
    if (!prox) {
        if(digitalRead(prox_pin) == LOW) {
            #ifdef DEBUG_PROX
                Serial.println("Proximity detected");
                Serial.println();
            #endif

            prox = true;
            if (!vibr) {
                wait = true;
                wait_time = millis() + wait_interval;
            }
            set_shot(1);
        }
    }
}

void check_vibr() {
    if (!prox && !vibr) {
        if(digitalRead(vibr_pin) == HIGH) {
            #ifdef DEBUG_PROX
                Serial.println("Vibration detected");
                Serial.println();
            #endif

            vibr = true;
            wait = true;
            wait_time = millis() + wait_interval;
        }
    }
}

void check_wait() {
    if (wait && millis() > wait_time) {
        if (!prox) {
            set_shot(0);
        }
        reset();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (MIS)                                                            //
//----------------------------------------------------------------------------//

void set_shot(int mode) {
    // MODE:
    // 0 = WRONG SHOT (MISS)
    // 1 = RIGHT SHOT (SCORE)

    Serial1.print(mode);
    delay(1000);
}

void reset() {
    vibr = false;
    prox = false;
    wait = false;
}

//----------------------------------------------------------------------------//
// MAIN                                                                       //
//----------------------------------------------------------------------------//

void loop() {
    check_prox();
    check_vibr();
    check_wait();
}

```

  [1]: https://create.arduino.cc/projecthub/marceloavilaoliveira/smart-basketball-scoreboard-f922cb#schematics


message:
LCD Backlight doesn’t work even at 5V. Using 330 Ohm resistor

I’ve been trying to make this project: https://create.arduino.cc/projecthub/chummer1010/electronic-safe-with-arduino-25d039

I’m confident that I’ve assembled everything correctly, but my LCD doesn’t display characters. Other projects seem to have fixed it by changing the potentiometer but I’m not using one.

Arduino code:

    /*
    Made by Marco Fusco
    May 20, 2016
    Contact me at: marcofusco111@gmail.com
    */

    #include <LiquidCrystal.h>
    #include <EEPROM.h>
    #include <Servo.h>

    int address = 0;
    static unsigned long SaveTimer;
    static unsigned long SaveDelay = (30 * 1000);

    char CODE[10] = "1234E";
    char Str[10];
    char CodeLength = 4;
    int Pos = 0;
    bool Unlocked;
    static unsigned long DisplayTimer;
    static unsigned long DisplayDelay = 200;

    LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

    int buttonPin1 = 2;
    int buttonPin2 = 3;
    int buttonPin3 = 4;
    int buttonPin4 = 5;

    int enterbutton = 10;
    int clearlockbutton = 13;

    Servo myServo;

    void setup() {

      myServo.attach(A1);

      int EEPROMCodeOK = true;
      for (Pos = 0; Pos <= (CodeLength); Pos++) {
        Str[Pos] =  EEPROM.read(Pos);
        if (!(strrchr("1123456789", Str[Pos]))) {
          // not a valid code
          EEPROMCodeOK = false;
        }
      }
      Pos++;
      Str[Pos] =  EEPROM.read(Pos);
      if (Str[CodeLength + 1] != 'E') EEPROMCodeOK = false;
      if (EEPROMCodeOK) {
        Str[CodeLength + 2] = '\0';
        strncpy(CODE, Str, CodeLength + 1);
      }
      ClearCode();

      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      pinMode(buttonPin3, INPUT_PULLUP);
      pinMode(buttonPin4, INPUT_PULLUP);

      pinMode(enterbutton, INPUT_PULLUP);
      pinMode(clearlockbutton, INPUT_PULLUP);

      lcd.begin(16, 2);
      lcd.setCursor(0, 0);
      lcd.print("Hello.");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Password:");

      DisplayTimer = millis() + 200;
    }

    void loop() {

      Lock();

      Pos = constrain(Pos, 0, CodeLength);

      int buttonState1 = digitalRead(buttonPin1);
      int buttonState2 = digitalRead(buttonPin2);
      int buttonState3 = digitalRead(buttonPin3);
      int buttonState4 = digitalRead(buttonPin4);

      int clButtonState = digitalRead(clearlockbutton);
      int enterButtonState = digitalRead(enterbutton);

      lcd.setCursor(9, 0);

      if (buttonState1 == LOW) {
        Str[Pos] = '1';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin1) == LOW);

      }

      else if (buttonState2 == LOW) {
        Str[Pos] = '2';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin2) == LOW);

      }

      else if (buttonState3 == LOW) {
        Str[Pos] = '3';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin3) == LOW);
      }

      else if (buttonState4 == LOW) {
        Str[Pos] = '4';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin4) == LOW);

      }
      else if (enterButtonState == LOW) {
        Str[Pos] = 'E';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin1) == LOW);
         if (strcmp (Str,CODE) == 0) {
          Unlocked = true;
          lcd.setCursor(0, 0);
          lcd.print(" Access Granted");
          delay(2000);
          lcd.clear();
          lcd.print("    Unlocked");
        }
        else if (SaveTimer > millis() && (Pos + 1) == CodeLength) {

          strcpy(CODE, Str);
          for (Pos = 0; Pos <= (CodeLength + 1); Pos++) {
            EEPROM.write(Pos, Str[Pos]);
          }
          lcd.setCursor(0, 0);
          lcd.print("Saving Code:");
          lcd.setCursor(0, 1);
          lcd.print(Str);

          Unlocked = true;
        }

        else {

          lcd.clear();
          lcd.print(" Access Denied.");
          delay(2000);
          lcd.clear();
          lcd.print("Password:");

        }

        while (Unlocked) {
          Unlock();
          if (digitalRead(clearlockbutton) == LOW) {
            delay(200);
            lcd.clear();
            lcd.print("     Locked");
            delay(2000);
            lcd.clear();
            Unlocked = false;
            SaveTimer = millis() + 30000;
          }
        }

        ClearCode();

      }

      else if (clButtonState == LOW) {
        delay(500);

        while (clearlockbutton == LOW);
        if ((millis() - SaveTimer) > 4500) {

        }

        ClearCode();

      }

      if ( (long)( millis() - DisplayTimer ) >= 0) {
        DisplayTimer += DisplayDelay;
        lcd.setCursor(9, 0);
        lcd.print(Str);
        lcd.print("     ");

      }
    }

    void ClearCode() {

      Pos = 0;
      Str[Pos] = '\0';
      lcd.setCursor(0, 0);
      lcd.print("Password:");
      lcd.setCursor(0, 1);
      lcd.print("          ");

    }

    void Unlock() {

      myServo.write(150);

    }

    void Lock() {

      myServo.write(50);

    }

body: Please add a foto of the display. Most likely you have problem with a contrast. Schematic at the link you've provided is very strange: pin 3, which is responsible for the contrast, is tied directly to GND, which sets the display to the minimum contrast. You should use either a potentiometer, or a voltage divider for this pin.


body:
Start with the Liquid Crystal, HelloWorld, Example.   Find out if it's your pin configuration or pot/no pot issue, or if you have a doofed LCD.

Some LCD 1602 have an on board pot, so make sure that's not there too.

Process of elimination.


message:
My gimbal program does not compile

my code:

```c++
// Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    // Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

// Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

// Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }

// After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
```

it says ypr does not name a type

```c++
/*
   Arduino and MPU6050 Accelerometer and Gyroscope Sensor Tutorial
   by Dejan, https://howtomechatronics.com
*/
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;
void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);
}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)
  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;
  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  */

  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}
```

We simply print the values on the serial monitor and once we know them, we can implement them in the code as shown earlier, for both the roll and pitch calculation, as well as for the 3 gyroscope outputs.

MPU6050 Pitch Roll and Yaw outputs

Finally, using the Serial.print function we can print the Roll, Pitch and Yaw values on the serial monitor and see whether the sensor works properly.

```c++
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
```

body:
I know this is more of a comment but I can't do that yet.

This is for the code with wire.h at the top of the code.

I loaded your code into my arduino IDE and my line numbers reference those

1. You have lines 22-32 commented out.

2. The // at the end of line 40 may cause you problems.

3. If lines 41-43 the same that you have in
void setup ()
the same then you have the program doing something over and over again, that has already been set up.

4. line 145 you have a lone */ that the compiler should have found.

5. Lines 136 to 178 are not inside {} are not being run.  They also look very similar to what is inside your void loop()

6. Line 180 has the same ````void calculate_IMU_error() { ```` as on line 80, which one is being ran?


message:
SIM800l is not Avalible

I am using :
-arduino uno r3
-SIM800L

connection:

Arduino   SIM800L
5v     -->  vcc
gnd    -->  gnd
pin10  --> TX
pin11  --> RX

the led on the module blinks once each 3~5 seconds
but when i use the function sim.available() i got 0;
thus as i guess there is a problem .

the code :

    #include <SoftwareSerial.h>
    SoftwareSerial sim(10, 11);
    int _timeout;
    String _buffer;
    String number = "000000000000"; //-> change with your number
    void setup() {
      delay(7000); //delay for 7 seconds to make sure the modules get the signal
      Serial.begin(9600);
      _buffer.reserve(50);
      Serial.println("Sistem Started...");
      sim.begin(9600);
      delay(1000);
      Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
    }
    void loop() {
      Serial.print(Serial.available());
      if (Serial.available() > 0)
        switch (Serial.read())
        {
          case 's':
            SendMessage();
            break;
          case 'r':
            RecieveMessage();
            break;
          case 'c':
            callNumber();
            break;
        }
      if (sim.available() > 0)
        Serial.write(sim.read());
    }

i looked the internet they say the voltage should be 3.7~4.2 itriedgivving 3.55 and it didn't work

body:
Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.

For short test you can connect module directly to LiPo 3,7V.

You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

> The power IC and the bypass capacitor should be placed to the module
> as close as possible.

[*SimCom, SIM800_Hardware Design_V1.09, available 27.11.2020*][1]

  [1]: https://simcom.ee/documents/SIM800/SIM800_Hardware Design_V1.09.pdf


message:
Continous running light with fading trail

In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular.
Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. `delay()` is not an option.

    void sinelon()
    {
    fadeToBlackBy( leds, NUM_LEDS, 20);
    int pos = beatsin16( 13, 0, NUM_LEDS-1 );
    leds[pos] += CHSV( gHue, 255, 192);
    }

body:
If you look at the surrounding methods, you'll see that 'fadeToBlackBy' will give a fading effect on anything you feed in. You'll want to locate method 'beatsin16' and then edit it yourself so that it doesn't bounce back but restarts the counter at the first LED. (hint: phase_offset)

You'll find the code snippet you want to copy in lib8tion.h

    /// beatsin16 generates a 16-bit sine wave at a given BPM,
    ///           that oscillates within a given range.
    LIB8STATIC uint16_t beatsin16( accum88 beats_per_minute, uint16_t lowest = 0, uint16_t highest = 65535,
                                   uint32_t timebase = 0, uint16_t phase_offset = 0)
    {
        uint16_t beat = beat16( beats_per_minute, timebase);
        uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
        uint16_t rangewidth = highest - lowest;
        uint16_t scaledbeat = scale16( beatsin, rangewidth);
        uint16_t result = lowest + scaledbeat;
        return result;
    }


message:
CH340 chip getting fried after connecting Arduino to a powerful 12V souce

I'm using a [120 W DC power supply][1] connected in parallel with ESC and Arduino nano through Vin. However, somehow the Arduino get fried near the CH340 chip[![enter image description here][2]][2], i.e. around the big black square chip near the micro usb port on the back of the board, kept getting fried. It's working for a while, until it melted.

This didn't quite make sense, since Arduino Vin can take voltage from 6V to 12V. The ESC also had a maximum current consumption of over 30A, equivalent to 360W. Thus there wasn't an obvious reason for which Arduino ought to get fried at all.

Why CH340 chip getting fried after connecting Arduino to a powerful 12V source?

  [1]: https://www.amazon.com/dp/B00Z9X4GLW/
  [2]: https://i.stack.imgur.com/84SYD.jpg

body:
It's impossible to say for sure what is going on without proper equipment (mostly you need oscilloscope), but I'm pretty sure that due to very high current consumption of the motors, there are voltage spikes at the input of the voltage regulator. If voltage exceeds safe value (15V for most of them), then regulator fails and all the input voltage is now on the output (that's how they fail 99% if the time, not as an open unfortunately, but as a short). Then for some reasons the weakest IC is CH340G which is fried. Try to use destroyed Arduino without ESC, and see what's on the 5V pin.
You say that you have currents up to 30A, but PSU is rated for 120W which means it can deliver only 10A at 12V. So at some point PSU falls into protection mode, switches off the output, and after some time tries to switch it on again. Situation with voltage spikes can be very nasty during this period.
Also please post your schematic and photo of the actual wiring, this can also give us some clues.


message:
Arduino uno wifi rev2 stuck inside loop

It might be a stupid question but I can't figure it out. While running the code below. I want to open the box when the code matches the code in API. This all works. I can even close the box afterwords. But then I am stuck inside my loop. after the box is closed I want the screen to say box closed and then I want the void loop() to start again. so my screen asks for a code again. I tried using break and exit but no luck so far.
entire code:

```
/* hardware libraries*/
#include <Key.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

/*Wifi and request libraries*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>

#define HIGH 0x1
#define LOW 0x0

/* wifi credentials*/
char ssid[] = "ssid";        // your network SSID (name)
char pass[] = "password";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;

int status = WL_IDLE_STATUS;
char server[] = "parcelbox.1819.caro.deweze.nxtmediatech.eu";
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

LiquidCrystal_I2C lcd(0x27, 16, 2); // lcd object
Servo myservo; //servo object
boolean boxOpenend = false ;

/* Keypad*/
const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {9, 8, 7};

Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String value = "";

void setup() {
  lcd.begin(); //start lcd
  Serial.begin(9600);
  myservo.attach(A0); // attach servo to pin
  lcd.backlight(); // start screen light

  /* connect to wifi */
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
}

void loop() {
  lcd.clear();
  lcd.print("Geef bestelcode");
  char customKey = customKeypad.getKey();   // get the key pressed
  value = value + String(customKey);
  lcd.setCursor(0, 1);
  lcd.print(value);
  if (customKey == '#') {

    String response_Status = "";
    Serial.println("\nStarting connection to server...");

    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {

      value.remove(16);
      Serial.println(value);
      Serial.println("connected to server");

      // Make a HTTP request:
      client.println("GET /api/boxes/1444/code/" + value + " HTTP/1.1");
      client.println("Host: parcelbox.1819.caro.deweze.nxtmediatech.eu");
      client.println("Connection: close");
      client.println();
    }
    // if there are incoming bytes available
    // from the server, read them and print them:
    StaticJsonBuffer<500> jsonBuffer;

    while (client.connected()) {

      String response = "";
      bool begin = false;

      while (client.available() || !begin) {
        char c = client.read();

        if (c == '{') {
          begin = true;
        }
        if (begin) response += (c);
        if (c == '"}') {
          break;
        }
        delay(1);
      }
      int start = response.indexOf("status\":\"") + 11;
      int end = start + 3;
      response_Status = response.substring(start, end);

      JsonObject& root = jsonBuffer.parseObject(response);

      if (!root.success())
      {
        Serial.print("parseObject(");
        Serial.print(response);
        Serial.println(") failed");
        break;
      }

      Serial.println(response_Status);
      if (response_Status == "200") {

        Serial.println("200");
        boxOpenend = true;

        while (boxOpenend) {

          lcd.clear();
          lcd.print("Box openend ,press");
          lcd.setCursor(0, 1);
          lcd.print(" * to close");

          myservo.write(0);// rotate the servo to open
          delay(175);

          char key = customKeypad.getKey();   // get the key pressed
          //value = value + String(key);

          if (key == '*') {
            myservo.write(90); // rotate the servo to lock
            value = "";                           // clear the string
            boxOpenend = false;

          }
          // box gaat terug toe maar ik blijf in deze loop zitten want lcd scherm blijft staan op "Box geopend , druk * om te sluiten
        }

      }
      else if (response_Status != "200") {

        Serial.println("not 200");

        lcd.clear();
        lcd.print("wrong code or");
        lcd.setCursor(0, 1);
        lcd.print("already deliverd");

        delay(175);
        value = "";
        exit;
      }
      //hier net hetzelfde
      break ;
    }
    // if the server's disconnected, stop the client:
    if (!client.connected()) {
      Serial.println();
      Serial.println("disconnecting from server.");
      client.stop();

      // do nothing forevermore:
      while (true);
    }
    exit;
  }

  if (customKey == '*') {
    myservo.write(90);                   // rotate the servo to lock
    value = "";                           // clear the string
  }

  delay(175); // for optimal lcd screen view
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```
This is where the code get's stuck.
It keeps on showing box opened press  * to close.
even when I press * and the box closes it keeps on saying this
```
while (boxOpenend) {

          lcd.clear();
          lcd.print("Box openend ,press");
          lcd.setCursor(0, 1);
          lcd.print(" * to close");

          myservo.write(0);// rotate the servo to open
          delay(175);

          char key = customKeypad.getKey();   // get the key pressed
          //value = value + String(key);

          if (key == '*') {
            myservo.write(90); // rotate the servo to lock
            value = "";                           // clear the string
            boxOpenend = false;

          }
          // box gaat terug toe maar ik blijf in deze loop zitten want lcd scherm blijft staan op "Box geopend , druk * om te sluiten
        }

      }
```
It might have a simple solution that I'm just not thinking of but it really bothers me!

UPDATE , We made a little progress as to figuring out why it wont work. the code that we are running now is:

```
/* hardware libraries*/
#include <Key.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

/*Wifi and request libraries*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>

#define HIGH 0x1
#define LOW 0x0

/* wifi credentials*/
char ssid[] = "XXXXXXX";        // your network SSID (name)
char pass[] = "XXXXXXX";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;

int status = WL_IDLE_STATUS;
char server[] = "parcelbox.1819.caro.deweze.nxtmediatech.eu";
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

LiquidCrystal_I2C lcd(0x27, 16, 2); // lcd object
Servo myservo; //servo object
boolean boxOpenend = false ;

/* Keypad*/
const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {9, 8, 7};

Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String value = "";

void setup() {
  lcd.begin(); //start lcd
  Serial.begin(9600);
  myservo.attach(A0); // attach servo to pin
  lcd.backlight(); // start screen light

  /* connect to wifi */
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
}

void loop() {
  lcd.clear();
  lcd.print("Geef bestelcode");

  char customKey = customKeypad.getKey();   // get the key pressed
  value = value + String(customKey);

  lcd.setCursor(0, 1);
  lcd.print(value);

  if (customKey == '#')
  {
  Serial.println("PRESSED #");
    String response_Status = "";
    Serial.println("\nStarting connection to server...");

  Serial.println("RESULT OF CLIENT.CONNECT()");
  Serial.println(client.connect(server, 80));

    // if you get a connection, report back via serial:
    if (client.connect(server, 80) == 1)
  {
    Serial.println("IK BEN HIER");
    value.remove(4);
    Serial.println(value);
    Serial.println("connected to server");

    // Make a HTTP request:
    client.println("GET /api/boxes/1444/pin/" + value + " HTTP/1.1");
    client.println("Host: parcelbox.1819.caro.deweze.nxtmediatech.eu");
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println("client.connect() not successfull");
  }

    // if there are incoming bytes available
    // from the server, read them and print them:
    StaticJsonBuffer<500> jsonBuffer;

    if (client.connected())
  {
    Serial.println("CLIENT CONNECTED");

    String response = "";
    bool begin = false;

    while (client.available() || !begin) {
      char c = client.read();

      if (c == '{') {
        begin = true;
      }

      if (begin) {
        response += (c);
      }

      if (c == '"}') {
        break;
      }

      delay(1);
    }

    int start = response.indexOf("status\":\"") + 11;
    int end = start + 3;

    response_Status = response.substring(start, end);
    Serial.println(response_Status);

    // response successfull
    if (response_Status == "200")
    {
      Serial.println("RESPONSE 200");
      Serial.println("response state == 200");

      // First open the box
      // 0° means open
      Serial.println("OPEN BOX");
      myservo.write(0);
      delay(175);

      lcd.setCursor(0, 0);
      lcd.print("                ");
      lcd.setCursor(0, 0);
      lcd.print("Box opened ,press");
      lcd.setCursor(0, 1);
      lcd.print("                ");
      lcd.setCursor(0, 1);
      lcd.print(" * to close");
    }
    else
    {
      Serial.println("RESPONSE NOT 200");
      Serial.println("not 200");

      lcd.clear();
      lcd.print("Foute code of");
      lcd.setCursor(0, 1);
      lcd.print("al afgeleverd");

      delay(175);
    }
    }

  // reset the value
  value = "";
  }

  // lock box and reset value
  if (customKey == '*')
  {
    Serial.println("CLOSE BOX");
    myservo.write(90);
    value = "";
    client.stop();
  }

  delay(175); // for optimal lcd screen view
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```
this is the serial output:
[![serial output][1]][1]

it's clear that the first request the check the code goes thru but when you try a second time it comes out empty. We did some research and we found that in some cases the servo could affect the request in a bad way. Just not sure if that is correct and how to fix this

  [1]: https://i.stack.imgur.com/NbQIu.jpg

body:
Although I can not verify my code, I tried to modify your program. Probably it does not compile and you have to do some corrections. I changed it in a way I would expect it to work and hopefully I understood your intentions.

At least we could use this version as a base to elaborate a working one together.

    #include <Key.h>
    #include <Keypad.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>
    #include <SPI.h>
    #include <WiFiNINA.h>
    #include <ArduinoJson.h>

    #define HIGH 0x1
    #define LOW 0x0

    char ssid[] = "ssid";
    char pass[] = "password";
    int keyIndex = 0;

    int status = WL_IDLE_STATUS;
    char server[] = "parcelbox.1819.caro.deweze.nxtmediatech.eu";

    WiFiClient client;

    LiquidCrystal_I2C lcd(0x27, 16, 2);
    Servo myservo;

    /* Keypad*/
    const byte ROWS = 4;
    const byte COLS = 3;

    char keys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {3, 4, 5, 6};
    byte colPins[COLS] = {9, 8, 7};

    Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
    String value = "";

    void setup()
    {
      lcd.begin();
      Serial.begin(9600);
      myservo.attach(A0);
      lcd.backlight();

      if (WiFi.status() == WL_NO_MODULE)
      {
        Serial.println("Communication with WiFi module failed!");
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < "1.0.0") { Serial.println("Please upgrade the firmware"); }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED)
      {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
      }

      Serial.println("Connected to wifi");
      printWifiStatus();
    }

    void loop()
    {
      lcd.clear();
      lcd.print("Geef bestelcode");
      char customKey = customKeypad.getKey();
      value = value + String(customKey);
      lcd.setCursor(0, 1);
      lcd.print(value);
      if (customKey == '#')
      {
        String response_Status = "";
        Serial.println("\nStarting connection to server...");

        if ( client.connect( server, 80 ) )
        {
          value.remove(16);
          Serial.println(value);
          Serial.println("connected to server");

          // Make a HTTP request:
          client.println("GET /api/boxes/1444/code/" + value + " HTTP/1.1");
          client.println("Host: parcelbox.1819.caro.deweze.nxtmediatech.eu");
          client.println("Connection: close");
          client.println();
        }

        StaticJsonBuffer<500> jsonBuffer;

        if ( client.connected() )
        {
          String response = "";
          bool begin = false;

          // I do not understand why you have to use  || ! begin
          // If the client has no content available, you can not read some
          // It doesn't matter if begin is true or false.
          // Or am I missing something?
          while ( client.available() || ! begin )
          {
            char c = client.read();

            if ( c == '{' )  { begin = true;    }
            if ( begin )     { response += (c); }
            if ( c == '"}' ) { break;           }

            delay(1);
          }

          // Why do you parse the json text for a special
          // attribute and then parse it again into a json object
          // where you can read this attribute?
          int start = response.indexOf("status\":\"") + 11;
          int end = start + 3;
          response_Status = response.substring(start, end);

    // I commented this out because you do not use the root variable
    // in the following code
    //      JsonObject& root = jsonBuffer.parseObject(response);
    //      if (!root.success())
    //      {
    //        Serial.print("parseObject(");
    //        Serial.print(response);
    //        Serial.println(") failed");
    //        break;
    //      }

          Serial.println(response_Status);
          if (response_Status == "200")
          {
            Serial.println("response state == 200");

            // First open the box

            // 0° means open
            myservo.write(0);
            delay(175);

            // Then inform the user how to close it

            lcd.clear();
            // I added the cursor positioning.
            // As far as I know clear does not reset the cursor.
            lcd.setCursor(0, 0);
            lcd.print("Box openend ,press");
            lcd.setCursor(0, 1);
            lcd.print(" * to close");

            // then check if the user wants to close it
            char key;
            do
            {
              key = customKeypad.getKey();
              if (key == '*')
              {
                // 90° means locked
                myservo.write(90);
                value = "";
              }
            }
            while( key != '*' );

          }
          else
          {
          // I replaced the else if by a simple if
          // as (response_Status != "200") is the else case
          // of (response_Status == "200")
            Serial.println("response state != 200");

            lcd.clear();
            // "set cursor" added
            lcd.setCursor(0, 0);
            lcd.print("wrong code or");
            lcd.setCursor(0, 1);
            lcd.print("already deliverd");

            delay(175);
            value = "";
          }
          // I change the while loop into an if block
          // so you don't need a break; here
        }

    // Here you could enter a halt state without a reason.
    // Even you won't expect to halt here.
    //    if (!client.connected())
    //    {
    //      Serial.println();
    //      Serial.println("disconnecting from server.");
    //      client.stop();
    //
    //      // do nothing forevermore:
    //      while (true);
    //    }
      }

      if (customKey == '*')
      {
        // 90° means locked
        myservo.write(90);
        value = "";
      }

      // for optimal lcd screen view
      delay(175);
    }

    void printWifiStatus()
    {
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

**EDIT**

This edit is related to the updated version of your program.

If you close the box with a key press you also stop the client with the last line.

Please remove the following line from the program.

    // lock box and reset value
    if (customKey == '*')
    {
      Serial.println("CLOSE BOX");
      myservo.write(90);
      value = "";
      // remove this as you can not connect a stopped client
      // client.stop();
    }


body:
```
/* hardware libraries*/
#include <Key.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

/*Wifi and request libraries*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>

#define HIGH 0x1
#define LOW 0x0

/* wifi credentials*/
char ssid[] = "sidd";        // your network SSID (name)
char pass[] = "pass";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;

int status = WL_IDLE_STATUS;
char server[] = "parcelbox.1819.caro.deweze.nxtmediatech.eu";
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

LiquidCrystal_I2C lcd(0x27, 16, 2); // lcd object
Servo myservo; //servo object
boolean boxOpenend = false ;

/* Keypad*/
const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {9, 8, 7};

Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String value = "";

void setup() {
  lcd.begin(); //start lcd
  Serial.begin(9600);
  myservo.attach(A0); // attach servo to pin
  lcd.backlight(); // start screen light

  /* connect to wifi */
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  /*
    // check for the WiFi module:
    if (WiFi.status() == WL_NO_MODULE) {
      Serial.println("Communication with WiFi module failed!");
      // don't continue
      while (true);
    }

    String fv = WiFi.firmwareVersion();
    if (fv < "1.0.0") {
      Serial.println("Please upgrade the firmware");
    }

    // attempt to connect to Wifi network:
    while (status != WL_CONNECTED) {
      Serial.print("Attempting to connect to SSID: ");
      Serial.println(ssid);
      // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
      status = WiFi.begin(ssid, pass);

      // wait 10 seconds for connection:
      delay(10000);
    }
    Serial.println("Connected to wifi");*/
  createConnection();
}

void loop() {
  lcd.clear();
  lcd.print("Bestelcode / pin");

  char customKey = customKeypad.getKey();   // get the key pressed
  value = value + String(customKey);

  lcd.setCursor(0, 1);
  lcd.print(value);

  if (customKey == '#')
  {
    createConnection();
    Serial.println("PRESSED #");
    String response_Status = "";
    Serial.println("\nStarting connection to server...");

    Serial.println("RESULT OF CLIENT.CONNECT()");
    Serial.println(client.connect(server, 80));

    // if you get a connection, report back via serial:
    if (client.connect(server, 80) == 1)
    {
      int valueLen = value.length();
      if(valueLen == 5){
      Serial.println("IK BEN een pin ");
      value.remove(4);
      Serial.println(value);
      Serial.println("connected to server");

      // Make a HTTP request:
      client.println("GET /api/boxes/2025/pin/" + value + " HTTP/1.1");//1444
      client.println("Host: parcelbox.1819.caro.deweze.nxtmediatech.eu");
      client.println("Connection: close");
      client.println();
      }
      if(valueLen ==17){
      Serial.println("IK BEN een bestelcode");
      value.remove(16);
      Serial.println(value);
      Serial.println("connected to server");

      // Make a HTTP request:
      client.println("GET /api/boxes/2025/code/" + value + " HTTP/1.1");//1444
      client.println("Host: parcelbox.1819.caro.deweze.nxtmediatech.eu");
      client.println("Connection: close");
      client.println();

        }
        else{

          Serial.println("invalid amount of numbers code");
          /*lcd.clear();
          lcd.print("ongeldige code");*/

          }
    }
    else
    {
      Serial.println("client.connect() not successfull");
    }

    // if there are incoming bytes available
    // from the server, read them and print them:
    StaticJsonBuffer<500> jsonBuffer;

    if (client.connected())
    {
      Serial.println("CLIENT CONNECTED");

      String response = "";
      bool begin = false;

      while (client.available() || !begin) {
        char c = client.read();

        if (c == '{') {
          begin = true;
        }

        if (begin) {
          response += (c);
        }

        if (c == '"}') {
          break;
        }

        delay(1);
      }

      int start = response.indexOf("status\":\"") + 11;
      int end = start + 3;

      response_Status = response.substring(start, end);
      Serial.println(response_Status);

      // response successfull
      if (response_Status == "200")
      {
        Serial.println("RESPONSE 200");
        Serial.println("response state == 200");

        // First open the box
        // 0° means open
        Serial.println("OPEN BOX");
        myservo.write(0);
        delay(175);

        lcd.setCursor(0, 0);
        lcd.print("                ");
        lcd.setCursor(0, 0);
        lcd.print("Box open ,druk");
        lcd.setCursor(0, 1);
        lcd.print("                ");
        lcd.setCursor(0, 1);
        lcd.print("* om te sluiten");
        delay(5000);
      }
      else
      {
        Serial.println("RESPONSE NOT 200");
        Serial.println("not 200");

        lcd.clear();
        lcd.print("Foute code of");
        lcd.setCursor(0, 1);
        lcd.print("al geleverd");

        delay(2500);
      }
    }

    // reset the value
    value = "";
  }

  // lock box and reset value
  if (customKey == '*')
  {
    Serial.println("CLOSE BOX");
    myservo.write(90);
    value = "";
    client.stop();
  }

  delay(175); // for optimal lcd screen view
}
void createConnection() {

  // This new line is required to disconnect the previous connection otherwise
  // it will try to use the old connection and never reconnect if the connection fails
  status = WiFi.disconnect();

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10);
  }
  // you're connected now, so print out the status:
  printWifiStatus();

}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```
I had to rewrite my wifi connection into a function outside my setup. Because the program only established a connection in the beginning and closed it after my first request. By giving it it's own function I could call it inside my loop whenever the user would enter a code the program could reestablish a connection. My program now runs how I need it to run.


message:
Arduino recorder with SD card module

Can any one suggest me best device in cheap rates to record audio in to SD-card and vice versa from the speaker......i want to record audio into the sd card like as feedback from customer

body:
For decent audio recordings, you need an external (16 or 24 bit, 44.1 KHz or more) ADC with at least two channels (stereo).

To save it to an SD, you can buy a so called SD data logger, they are very cheap. Not all SD cards are compatible so you might have to try several ones. The protocol used is SPI.


message:
json format in esp32 with arduino json

I am using an ESP32 module for bluetooth connection and scaning wifi network. But I cannot format the json using arduinojson library in the way I want.

    void scanWifiNetworks() {
      //creating json
      DynamicJsonDocument jsonDoc(1024);
      char jsonBuffer[512];
      JsonObject wifiJsonObject = jsonDoc.createNestedObject("wifiList");
      wifiJsonObject["ssid"];
      Serial.println("scan start");

      // WiFi.scanNetworks will return the number of networks found
      int n = WiFi.scanNetworks();
      Serial.println("scan done");
      if (n == 0) {
        Serial.println("no networks found");
      } else {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i) {
          // Print SSID and RSSI for each network found
    //      Serial.print(i + 1);
    //      Serial.print(": ");
    //      Serial.print(WiFi.SSID(i));
    //      Serial.print(" (");
    //      Serial.print(WiFi.RSSI(i));
    //      Serial.print(")");
    //      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");

          wifiJsonObject["ssid"] = WiFi.SSID(i);
          serializeJsonPretty(jsonDoc, SerialBT);
          serializeJsonPretty(jsonDoc, Serial);
          delay(10);
        }
      }
      Serial.println("");

      // Wait a bit before scanning again
      delay(60000);
    }

The output is like this

    scan start
    scan done
    5 networks found
    {
      "wifiList": {
        "ssid": "quark"
      }
    }{
      "wifiList": {
        "ssid": "Airtel_Zerotouch"
      }
    }{
      "wifiList": {
        "ssid": "NETGEAR77"
      }
    }{
      "wifiList": {
        "ssid": "Itobuz-technologies"
      }
    }{
      "wifiList": {
        "ssid": "Nokia 6.1"
      }
    }

what I want is something like that

{
      "wifiList": {
        "ssid1": "quark1",
         "ssid2": "quark2"
     }
}

I know I am looping in a wrong way but could not figure it out. if possible please pointing out the right direction will help a lot.

body:
You are repeatedly overwriting the `ssid` property of the same object.
Instead, you want to write different properties, like

```c++
wifiJsonObject["ssid" + String(i+1)] = WiFi.SSID(i);
```

Then, only serialize the document once, when it is complete.

That being said, I strongly concur with Juraj in that the correct way to
represent a list in JSON (and `wifiList` is clearly meant to be a list)
is by using an array:

```c++
void scanWifiNetworks() {
    DynamicJsonDocument jsonDoc(1024);
    JsonArray wifiList = jsonDoc.createNestedArray("wifiList");
    int n = WiFi.scanNetworks();
    for (int i = 0; i < n; ++i) {
        JsonObject wifiNet = wifiList.createNestedObject();
        wifiNet["ssid"] = WiFi.SSID(i);
    }
    serializeJsonPretty(jsonDoc, SerialBT);
    serializeJsonPretty(jsonDoc, Serial);
}
```

This should produce a JSON document that looks like this:

```json
{
  "wifiList": [
    { "ssid": "quark" },
    { "ssid": "Airtel_Zerotouch" },
    { "ssid": "NETGEAR77" },
    { "ssid": "Itobuz-technologies" },
    { "ssid": "Nokia 6.1" }
  ]
}
```

-----

**Edit**: Note that, if it's clear from the context (e.g. a request URL)
that you are transmitting a list of WiFi networks, then you can get rid
of the outer object and the "wifiList" label, and use the array as the
JSON document:

```json
[
  { "ssid": "quark" },
  { "ssid": "Airtel_Zerotouch" },
  { "ssid": "NETGEAR77" },
  { "ssid": "Itobuz-technologies" },
  { "ssid": "Nokia 6.1" }
]
```

As suggested by Jaromanda X, if you are never going to extend the inner
objects with extra information, you can further simplify the document by
removing those objects and just listing the SSIDs in the array:

```json
[
  "quark",
  "Airtel_Zerotouch",
  "NETGEAR77",
  "Itobuz-technologies",
  "Nokia 6.1"
]
```


message:
How to reset millis( )?

I am currently doing a school project.  There you have to program a stopwatch with the Arduino.  I wrote a program where millis starts.  But when I press my start button, millis don‘t start from 0.
Has someone an idea? Please let me know.

Ps: I‘m German, so I‘m sorry for my bad English
![enter image description here](https://i.stack.imgur.com/GJUdt.jpg)

body: You don't. Instead you just remember what `millis()` was when you pressed your start button, then subtract that from whatever `millis()` is showing at any other point in the future.


message:
How can measure the 3-axis accelerations?

i'm a student who is studying the Arduino.
I want to measure acceleration using arduino and any sensor. i looked at some acceleration sensors (ex, MPU6050, AXDL335), but they were just measuring gravity, not axial acceleration.

Could you tell me any sensor that can measure the axis-acceleration available with Arduino?

body:
There is no difference between gravity and other kinds acceleration. Gravity is the constant downward acceleration of ≈9.81 m/s². You cannot feel any difference between the force of gravity and the force you would experience on a surface without gravity that's accelerating upwards at 9.81 m/s².

You can use the gyroscope to keep track of the orientation of the sensor, so you know the downward direction of gravity, and can correct your accelerometer measurements for it.

The problem is that gyroscope orientation measurements are subject to drift. To correct the orientation for drift, the accelerometer is used (because it can measure the direction of gravity, so you know what the downward direction is). The accelerometer only measures the exact acceleration due to gravity if the sensor is not accelerating, of course, but that's most likely not the setup you're going to use an accelerometer in.

As you can see, this is kind of a chicken and egg problem.
Luckily, there are advanced sensor fusion algorithms and complementary filters available that combine the accelerometer and gyroscope measurements, and give you a pretty good approximation for both.
I've successfully used Madgwick's algorithm for a quadcopter.
Depending on your use case, you'll have to tweak some coefficients to indicate if you rely mostly on the gyro or the accelerometer data. The MPU6050 has a DMP that can run sensor fusion algorithms on the chip itself, so the Arduino doesn't have to deal with that.


message:
Sparkfun CCS811 sensor not interfacing with arduino

I have sparkfun indoor air quality sensor CCS811 which needs to be interfaced with arduino. I have soldered wires on the sensors and connected with arduino. Have checked the connection with multimeter so that part works. But even using example code on library still I am not getting reading from sensor.

Code:-

    #include <Wire.h>

    #include "SparkFunCCS811.h"

    #define CCS811_ADDR 0x5B //Default I2C Address
    //#define CCS811_ADDR 0x5A //Alternate I2C Address

    CCS811 mySensor(CCS811_ADDR);

    void setup()
    {
      Serial.begin(9600);
      Serial.println("CCS811 Basic Example");

      Wire.begin(); //Inialize I2C Harware

      //It is recommended to check return status on .begin(), but it is not
      //required.
      CCS811Core::status returnCode = mySensor.begin();
      if (returnCode != CCS811Core::SENSOR_SUCCESS)
      {
        Serial.println(".begin() returned with an error.");
        //while (1); //Hang if there was a problem.
      }
    }

    void loop()
    {
      //Check to see if data is ready with .dataAvailable()
      if (mySensor.dataAvailable())
      {
        //If so, have the sensor read and calculate the results.
        //Get them later
        mySensor.readAlgorithmResults();

        Serial.print("CO2[");
        //Returns calculated CO2 reading
        Serial.print(mySensor.getCO2());
        Serial.print("] tVOC[");
        //Returns calculated TVOC reading
        Serial.print(mySensor.getTVOC());
        Serial.print("] millis[");
        //Simply the time since program start
        Serial.print(millis());
        Serial.print("]");
        Serial.println();
      }

      delay(10); //Don't spam the I2C bus
    }

[![enter image description here][2]][2]

[![enter image description here][3]][3]
[![enter image description here][1]][1]

Things I tried:-
1) different combination of  A4, A5 pins
2) 0x5A & 0x5B i2c address
3) using wake pin with ground
4) using 3.3 & 5V for powering sensor

What else needs to be done?

  [1]: https://i.stack.imgur.com/lXYEl.jpg
  [2]: https://i.stack.imgur.com/3185F.jpg
  [3]: https://i.stack.imgur.com/IySkH.jpg

body: The problem was on the soldering part. SDA & 3.3V pin on sensor were slightly in contact. I modified it and started working fine.


message:
execute if function in a timed loop

I have a school project where I had to make a piece of code work for 1 minute and then return. I first used a RFID reader which didn't work for me so I decided to use the serial monitor. I did this through a switch function and if it was the correct number you had 1 minute to push in the buttons.

But now to the problem for me is that in the timed loop I made it can't look for if functions and because of that I can't look if the buttons are pressed.
I hope it was a
clear explanation and someone can help me.
Thanks in advance.

[![][1]][1]

  [1]: https://i.stack.imgur.com/CvDJq.png

body:
As chrisl mentions,  you should use `digitalRead`.
Assign this to the correct variables:

    switchState1 = digitalRead(…) // Fill in the correct pin here
    switchState2 = digitalRead(…) // Fill in the correct pin here

Also, you can separate the first part of the `if`, so you get:

    if (switchState1 == HIGH)
    {
        if (switchState2 == HIGH)
        {
            digitalWrite(2, HIGH);
            digitalWrite(3, HIGH);
            digitalWrite(4, HIGH);
        }
        else if (switchState2 == LOW)
        {
            digitalWrite(2, LOW);
            digitalWrite(3, LOW);
            digitalWrite(4, LOW);
        }
    }

Since the inner condition only depends on switchState2 and the pins are equal, you can write:

    if (switchState1 == HIGH)
    {
        digitalWrite(2, switchState2 == HIGH);
        digitalWrite(3, switchState2 == HIGH);
        digitalWrite(4, switchState2 == HIGH);
    }

And you can use instead of the switchState2 a switchState2High (Boolean), and only check it when switchState 1 == HIGH.

    if (switchState1 == HIGH)
    {
        switchState2High = (digitalReadState(…) == HIGH);
        digitalWrite(2, switchState2High);
        digitalWrite(3, switchState2High);
        digitalWrite(4, switchState2High);
    }

You also could use a for loop for the last part so you get:

    if (switchState1 == HIGH)
    {
        switchState2High = (digitalReadState(…) == HIGH);
        for (int pin = 2; pin < 5; pin++)
        {
            digitalWrite(pin, switchState2High);
        }
    }


message:
Hook Arduino up with thermal printer and power both externally

**Disclaimer:** *I have no connection to adafruit.*

A friend and me want to build a little project. We want to connect an arduino to a thermal printer and then print out little fortune-cookie like messages, when a button is pressed. The whole setup should not be stationary and thus we need external, mobile power like batteries.

Since this is our first time using an arduino as well as a thermal printer and we have no clue about electronics, I am asking for help to set everything up without frying the arduino or the thermal printer.

We are using a standart arduino uno rev3 and the Adafruit Tiny Thermal Reciept Printer.

First question: **Setting up the power supplies**

So the idea was to power the arduino via a 9v battery pack to it's 2.1mm DC port. I think this should work, right?

What I am confused about is the Adafruit Tiny printer. It says it takes 5-9 V, 1.5-2A. Can I just hook up a 9V battery packand clip the caples to the printer? Or what setup do I need so that the printer will recieve enough amperes when printing?

And how would I connect both tools to a single ( larger ?) battery pack?
So that we can turn the power off easily?

Second question: **Finding a good button compatible with an arduino and setting it up in the project.**

So we have a gerneal idea of how things should work. Somehow we need to connect the button to the arduino which then can register a click via one of it's pins. This click I can then register with my code and from there on things get easy for me. But getting to this point is hard for us.

We don't know which buttons will work and neither how to connect it to the right pin. Which pin should we adress? Digital? Analog?
Does the button need an external power supply as well? Since otherwise the arduino would not register a change of current on a pin, right? Or do we need to connect the button to the whole circuit?

*I do a lot of high language engineering and have no real idea about circuits and electronics and my friend is more of a craftsmen so we really appreciate your ideas, setups and help in general!*

I am not sure if this is too much to ask but a sketch of the whole setup with a single power source and button would be awesome! Thanks. Really!

body:
> Setting up the power supplies

As Gerben already stated in the comments, a 9V block battery isn't capable of supplying enough current for the thermal printer, so you cannot simply use one of them (these are meant for low power applications, like a smoke alarm). There are many different types of batteries, that you can use for this. Probably some kind of LiPo or LiIon pack would be suitable. (I'm sure you can find information about pros and cons of different battery types on the web). But the easiest way for you would be an USB power bank, that can supply at least 2.5A. A power bank incorporates mostly a LiIon pack and also already the mandatory smart charging electronics (to charge and discharge correctly and also to monitor the charge level), and - every important - a 5V voltage regulator. You can supply the 5V from the USB power bank directly to the Arduino and thermal printer in parallel. If you need to switch them on and off together (and the power bank doesn't already incorporate some kind of switch), you can use a simple switch between the positive lead from the power banks USB port and the positive leads for Arduino and printer.

> Finding a good button compatible with an arduino

**Every** normal button is compatible with Arduino. A button is nothing more as a switch, that automatically opens again, if you are not pressing it. Just two pieces of conductive material, that get's pressed together, if you press the button. A normal button has 2 pins (you might see more pins on the button, but mostly some of these are electrically connected together, so that you effectively have only 2 pins). Connect one pin to ground and the other to a digital input pin of the Arduino. Then in your sketch use `pinMode(pin_number, INPUT_PULLUP);` in your `setup()` function. This will enable the Arduinos internal pullup resistor, which pulls the pin to HIGH, if the button isn't pressed. If you press the button, the pin will be pulled to LOW. Keep this inverted logic in mind (LOW means pressed, HIGH not pressed).

There are also many button examples for Arduino on the web, since using a button is the second thing to learn with Arduinos (after blinking an LED). Button example code via `digitalRead()` is also incorporated into the Arduino IDE (look for examples in the menu).

> a sketch of the whole setup

Even, if someone wanted to write the code for you (and this is not a free coding service, so you cannot expect someone to simply do it), you haven't given us enough information, what behavior you want. But please don't add that here, to get this free code. What you are asking (single power source and button) is not difficult. Surely - currently you don't know much about this stuff, but it's not rocket science and there are many many Arduino tutorials on the web to help you. About the code for the thermal printer: Adafruit always provides dedicated guides for the devices they sell. There you can find a description, how the device works and is connected and used. They also provide example code and in most cases complete Arduino libraries, that hide most of the complexity of a task.

You should start by connection the Arduino to the power bank. Then you should go on and get the button going (you can write a sketch to turn the onboard LED on and off with it to learn how it works). Then you can connect the printer. Try adafruits example code. If it works, you can extend your sketch with the printers code.

---

Note: Some power banks turn of the power completely, if only a small current is flowing out of if. With such a power bank your Arduino might turn of as the power bank cuts the power. It normally does not draw enough current for the power bank. I think this shouldn't happen, when the printer is connected, but this depends on the current, that it draws (considering the minimal current, that it draws while idling), and the current, that is the minimal limit for your specific power bank.


message:
How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)

I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.

body:
I will skip the RFID part, that is unrelated to the menu.

What you can do is creating two variables:

    int menuLevel1 = 0;
    int menuLevel2 = 0;

Assuming you have 2 levels, if you have more levels consider an array.

Now you can print the screen based on the values of these two variables (use a `switch` statement for menuLevel1 which calls new functions, each with their own `switch` statement for menuLevel2.

Note there are more solutions, but this is a rather simple solution.

The RFID scanner just changes the values, so going to a different menu screen.

A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).

The last example looks like:

    enum EMenuPage
    {
       StartPage,
       MainMenu,
       FirstMenu,
       DisplayX,
       SetY,
       …
    }

    enum EMenuPage _menuPage;

Displaying like:

    switch (_menuPage)
    {
    case StartPage:
       // Fill LCD with start page
       break;

    case …

And when an RFID messages comes in:

    if (RFID... == Back)
    {
      _menuPage = MainMenu;
    }
    else …


body:
[State machines][1]. it's the general form of the solution provided by michael above. it's a big help on situations when the application have to answer to, or act on many states (e.g. a menu). the good part is you can `draw them on a piece of paper` , draw a graph, manage input/output and write a general routine to act in various states. the state names themsevles can be represented by an integer variable and represented better by enumeration. after that, there should be a routine to act based on the current state, and the input from current state to go to another state. in it's easiest form, it's just a `if-else` block.
depsite the idea is the same as the bare variable solution provided in the other answers, ignoring state machine related techniques (e.g. just drawing state graphs down on a piece of paper) makes a big application unmanageable.


message:
How can I read this digital pin for Nano by using AVR's Atmel Studo?

How can I read digital pin 6 in AVR?

I set the pin as input as follows:

DDRD = B0100000; //this will set pin 6 as input

But how can I now digital read this pin?:

Another way of putting it: how can I convert this Arduino code to be used in Atmel Studio?:

digitalRead(DATA_PIN);

Edit:

    while (1) {

      unsigned long data = 0;//32 bit variable to store encoder data

      for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
      data <<= 1;//shift all read data left one bit
      PORTD &= ~(1 << 5);//clock pin goes low
      _delay_us(2);
      PORTD |= (1 << 5);//clock pin goes high
      _delay_us(2);

      data |= digitalRead(DATA_PIN);//cat the new read bit to the whole read data
      }

I want to use usual C code for AVR instead of using digitalRead above. data is an 32 bit array storing 25 bit encoder data. It is bit by bit filled by digitalRaed.

I think I found it:

    while (1) {

      unsigned long data = 0;//32 bit variable to store encoder data
      uint8_t val;

      for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
      data <<= 1;//shift all read data left one bit
      PORTD &= ~(1 << 5);//clock pin goes low
      _delay_us(2);
      PORTD |= (1 << 5);//clock pin goes high
      _delay_us(2);

      if ( (PIND & (1 << PIND6)) == (1 << PIND6) ) {
       val = 1;
       } else {
       val = 0;
      }

      data |= val;//cat the new read bit to the whole read data
      }

body:
1. Read the port state with PIND
2. Isolate the bit you want with `&`
3. Profit

```c++
if (PIND & 0b0100000) {
    val |= 1;
}
```

Or, as a ternary:

```c++
val |= ((PIND & 0b01000000) ? 1 : 0);
```


message:
String to float on Arduino

I'm trying to convert a String to a float but I'm running into issues with precision, even with the Arduino's own String example I'm getting bad results.

Example 0:
Input string: 1.234567 After conversion to float: 1.2345669

Example 1:
Input string: 60.123456 After conversion to float: 60.1234512

Example 2:
Input string: 9.876543 After conversion to float:9.8765430

Why is this happening and how do I get rid of this?

body: It seems that I must convert to string first then use atof.


body: If you are using atof() to convert the string to a floating-point number, you would only get 6 or 7 digits of precision. And the numbers in your examples already have that much precision.


body:
You get this, because a float uses a certain number of bytes (I don't have an Arduino at hand), I think it is 4 bytes.

In these bytes, only a certain accuracy can be stored, so the least significant digits gets rounded (binary, resulting in different end digits).

Only for e.g. Arduino Due: You can use doubles instead, see https://www.arduino.cc/reference/en/language/variables/data-types/double/

You might check for the `strtod` function, but I'm not sure if it is handled by the Arduino:

https://www.techonthenet.com/c_language/standard_library_functions/stdlib_h/strtod.php

If this doesn't work, you can use a function to split the '.' and process the left/right part to convert to an unsigned long and combine it together. But if there are exponential and minus signs involved it might get more difficult.


body:
There are two issues at play here:

## 1 – Limited precision of the float data type

A float has a precision of roughly 10−7, and any number that
is not an exact float is supposed to be rounded to the nearest float.
For example, the two floats closest to 1.234567 are
10356298 × 2−23 = 1.2345669269561767578125 and
10356299 × 2−23 = 1.23456704616546630859375.
The latter is the closest.

## 2 – Naive string to float implementation in the Arduino core

The Arduino core aims at being small and consume few resources.
Sometimes it cuts corners, at the cost of accuracy. In this case,
although a correct implementation is supposed to round 1.234567 _up_,
because the nearest float is _above_ that number, the actual
implementation ends up rounding _down_. Thus you end up with roughly
1.234566927, which is off by 0.61 ULPs (units of the last place), instead
of the expected error of 0.39 ULPs.


message:
Which one is IR led?

I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?

[![][1]][2]
[![][2]][2]

[1]: https://i.stack.imgur.com/JGCa4.jpg
[2]: https://i.stack.imgur.com/GpGJh.jpg

body:
If you connect one of these and you can see it light up with your naked eye then it is not an IR LED, it's a visible-light LED. It's also not an IR sensor.

If you want to see IR, point a digital camera (like in your phone) at it and apply power. The sensors in digital cameras almost always detect some IR, so you can see a faint light on the screen. To test this, point your phone at a TV remote and press the button. If you see a flashing light in your phone's screen, you know it can "see" IR (Most digital cameras have an IR filter to get rid of most of the IR going into the camera, but they generally allow enough IR through that if you point them directly at an IR LED you can usually see it, at least faintly.)

Note that you should be able to use a visible light LED as a light source for an IR photoresistor/photodiode/phototransistor, since visible light LEDs will also give off some IR. However, an IR LED will put out a WHOLE LOT more IR than a visible light LED at of the same power.

The black one is probably an IR receiver. The color of the lens probably blocks visible light but not IR.

All the IR LEDs I've seen have looked clear, but I could not see any visible light when I powered them up.


body:
The dark coloured one is an IR photodiode.
[Osram SFH203-FA][1]

Hope that hemps.

:)

  [1]: https://uk.farnell.com/osram-opto-semiconductors/sfh203-fa/photodiode-ir-filtered/dp/1212743?gclid=CjwKCAiAp4KCBhB6EiwAxRxbpFTglXFst5jiNCmIW9UlN7svCgrgdTmj2rKkaKElTQHQR5U7p61d5RoCj60QAvD_BwE&gross_price=true&mckv=sr4nhIp3m_dc|pcrid|490856297904|plid||kword||match||slid||product|1212743|pgrid|114088214857|ptaid|pla-336893085108|&CMP=KNC-GUK-SHOPPING-GSE-DoublePresence-Jan11-OPTOELECTRONICS-DISPLAYS-NEWSTRUCTURE


message:
How to connect ESP32 to HC-06?

I am making a small project (BT controlled "tank") and need to connect ESP32 with HC-06 (ESP32 will be in controller and HC-06 in the vehicle). Android phone communication with both ESP and HC-06 works prefectly, I can not just figure out, how to pair/connect these two modules. Any ideas?

EDIT: Just to clarify, I can not connect them, because the HC-06 has PIN and I can not figure out how to remove that PIN or connect to it with PIN from ESP32...

body:
You can either use a breadboard Or Female to Female Jumber wires.

Ofoucrse you can always solder yourself the two modules together with wires.

PS. Too low reputation to comment, so i insert this as answer


message:
motor shield directly to PC? WITHOUT ARDUINO!

Is there a way to connect and control motor shield board WITHOUT Arduino at all.
can i connect it directly to my PC ?
i'm getting confused since i red lot of topics that people use existing pins on motherboard.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/1Eg3N.png

body:
To a normal PC? No. You can't. A PC doesn't have the GPIO pins etc that are needed.

You could wire it to a Pi though.


body: If you have a PC with a real Parallel Port ( LPT1: ) and you don't run an Operating System on it, ( or perhaps MS-DOS ) ... you can connect some leds, but you cannot use an Arduino shield directly.


body:
This super**user** [post][1] might help.

Raspberry Pis have GPIO pins that you can use to communicate with a motor shield, but regular (intel-based) PCs usually don't. In any case, you wouldn't want to mess with motherboard pins anyway; a short circuit might easily fry your computer.

If you don't want to use an Arduino, you can use a USB-to-serial converter (such as a small [FTDI circuit][2]) along with a [motor driver that uses serial communication][3].

However, this wouldn't be any simpler or cheaper than just using an Arduino.

  [1]: https://superuser.com/questions/993690/do-desktop-computer-motherboards-have-gpio-if-they-do-how-to-read-from-or-writ
  [2]: https://learn.adafruit.com/ftdi-friend
  [3]: https://www.sparkfun.com/products/13911