body:
Compare the [YouTube video][1] and [this webpage][2], the former one made programming very different in ESP32 and that was in Arduino nano, while the webpage seemed to imply that they work exactly the same.

Can we use the same code for standard Arduino library, like wire library, for ESP32 and ESP8266, or do we have to do something different?

  [1]: https://www.youtube.com/watch?v=HwurH20jsvw
  [2]: https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/

title: Can ESP 32 use the wire library exactly like that was in Arduino?

Answers: 1

body:
Code using the Arduino Wire library is generally portable between processors, but there are pitfalls to watch for.  One that I'm aware of is a difference in the Wire libraries for the ESP32 and ESP8266. The TwoWire::begin() method for the ESP32 has prototype:
```
bool TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency);
```
whereas for the ESP8266 it is:
```
void TwoWire::begin(int sda, int scl, uint8_t address);
```
So, a call to begin() using the ESP#2 library will set the clock using the third parameter, whereas on the ESP8266 it will truncate the third parameter and use it as an address.

If you wish code to be portable between the ESP32 and ESP8266, then the fix for this particular issue is to call `TwoWire::begin( my_SDA_pin, my_SCL_pin )` (specifying only two parameters:the SDA and SCL pins), and use a separate call to `TwoWire::setClock( my_clock_speed )` to set the clock.

There may be other differences I'm not aware of...


body:
I'm using this [SparkFun Sound Sensor][1] in my project for a simple ambient sound meter.

I'm just trying to monitor the raw analog envelope output for the moment.

My problem is that the output only changes with peak sounds, like a clap in my hands for example. But when the ambient sound is louder, people talking or loud music, the output doesn't change.

  [1]: https://www.sparkfun.com/products/12642

title: Sound sensor only detect peaks

Answers: 1

body:
It seems you have to increase the gain, see inside the document

[Sound dectector hookup guide][1]

The following fragment:

[![Fragment][2]][2]

  [1]: https://learn.sparkfun.com/tutorials/sound-detector-hookup-guide?_ga=2.163503161.463025551.1581195689-620897650.1579562509
  [2]: https://i.stack.imgur.com/KfBr4.png

Also take into account it needs between 3.5 and 5.5 V, while 5 V is ideal (see Quick start at the beginning of the same document.


body:
 I bought a this voltage regulator . DC-DC 5v 8A voltage regulator. ıts supported 8-35V input voltage . And i want to use this with 12v power supply.
But i searched on the internet . Nodemcu max amp is 800mA. This device can provide 2A per usb output if i will plug the nodemcu with usb cable this what happen ? Does it burn ? How can i drop the amps ?  i want to use other 3 usb output with other devices sensors and screen .

[![Dc-Dc 5V 8A Voltage regulator][1]][1]

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

title: Nodemcu powering with 5.2v and 2A?

Answers: 2

body:
Generally, we specify [DC][1] power supplies as constant [voltage sources][2].  In order to do this, power supplies deliver more or less current as demanded by the load in an attempt to keep the voltage constant regardless of the load.

When a constant voltage DC power supply specifies a maximum current, it is saying the power supply can only maintain the specified voltage while the current demand is less than the specified maximum current.

To be clear, unless you need a constant current power supply, a power supply should be picked based on the required constant voltage.  And the capacity of that power supply, usually measured in [Amps][3], should exceed the maximum combined current demand of all connected devices (loads).

  [1]: https://en.wikipedia.org/wiki/Direct_current
  [2]: https://en.wikipedia.org/wiki/Voltage_source
  [3]: https://en.wikipedia.org/wiki/Ampere

body: It will not burn.  The nodeMCU will only "pull" the amount of current (amps) it needs.


body:
So I spent a bit trying to figure the wiring and I THOUGHT I had it working but something interesting happened. Displaying works for only the numbers 1, 3, 4, 7, 8, and 9, but are weird when it comes to the numbers 2, 5, 6. I am unsure why this is happening and tbh I am pretty new to arduino.

This is how it displays 2222:
[![enter image description here][1]][1]

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

Here is the code:
```
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {

byte numDigits = 4;

byte digitPins[] = {2, 3, 4, 5};

byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};

sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);

sevseg.setBrightness(60);

}

int timer = 1000;
void loop() {

  sevseg.setNumber(2222);

  sevseg.refreshDisplay(); // Must run repeatedly

}
```
Any ideas on how this might be happening?

title: Trouble with 4 digit 7 segment display

Answers: 0


body:
I'm trying to get done following. Connect a Keyboard over USB -> USB Host Shield -> Grab the pushed key (char) from the keyboard and write them to the rfid writer.

So the code for the rfid writer is done, and works well - but only over the serial monitor (osx) / putty(win10).
Watt also works is the USBHIDbootKbd from the examples of the USB_Host_Shield_Library_2.0.

So was I exactly need is grab the key'(s) from the keyboard until e.g. '/', store them into a buffer and send / write it to the code line of the rfid writer.
First line for input is where comment:  // Ask personal data: Password
and second  // Ask personal data: user name.

attached is the code for the rfid writer

Thanks in advice
Cheers

        /*
     * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
     * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     *
     * Hardware required:
     * Arduino
     * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
     * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
     * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         5           // Configurable, see typical pin layout above
    #define SS_PIN          6          // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

    void setup() {
      Serial.begin(9600);        // Initialize serial communications with the PC
      SPI.begin();               // Init SPI bus
      mfrc522.PCD_Init();        // Init MFRC522 card
      Serial.println(F("Write personal data on a MIFARE PICC "));
    }

    void loop() {

      // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
      MFRC522::MIFARE_Key key;
      for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }

      Serial.print(F("Card UID:"));    //Dump UID
      for (byte i = 0; i < mfrc522.uid.size; i++) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
      }
      Serial.print(F(" PICC type: "));   // Dump PICC type
      MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
      Serial.println(mfrc522.PICC_GetTypeName(piccType));

      byte buffer[34];
      byte block;
      MFRC522::StatusCode status;
      byte len;

      Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
      // Ask personal data: Password
      Serial.println(F("Type your Password, ending with #"));
      len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
      for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

      block = 1;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("PCD_Authenticate() success: "));

      // Write block
      status = mfrc522.MIFARE_Write(block, buffer, 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      block = 2;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      // Ask personal data: User Name
      Serial.println(F("Type your User Name, ending with #"));
      len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
      for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

      block = 4;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, buffer, 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      block = 5;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      Serial.println(" ");
      mfrc522.PICC_HaltA(); // Halt PICC
      mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

    }

title: Arduino UNO + USB Host Shield 2.0 + RFID RFC522

Answers: 0


body:
I have developed the code to control the relay switching on/off using nextion display and esp32. But whenever I press my dual state button in the nextion display there is some delay and I need to press my dual state button continuously in nextion display for about 10 to 15 seconds to switch on/off the relay.

I am stuck in this work and I 'm looking for help. I need to switch on/off the relay on a single tap on the dual sate button on nextion display. Below I have attached my code,

```c++
#include "NexDualStateButton.h"
#include "Nextion.h"
#include "DHT.h"

#define DHTPIN 27
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
int R1 = 2;
uint32_t dual_state ;

NexText tTempC = NexText(0, 4, "tTempC");
NexText tHumidity = NexText(0, 6, "tHumidity");
NexDSButton bt0 = NexDSButton(0, 8, "bt0");

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
  uint32_t dual_state;
  NexDSButton *btn = (NexDSButton *)ptr;

  dbSerialPrintln("bt0PopCallback");
  dbSerialPrint("ptr=");

  dbSerialPrintln((uint32_t)ptr);
  memset(buffer, 0, sizeof(buffer));

  bt0.getValue(&dual_state);

  if(dual_state>0)
  {
    digitalWrite(R1, LOW);
  }
  else
  {
    digitalWrite(R1, HIGH);
  }
}

void setup(void) {
   dht.begin();
   Serial.begin(9600);
   pinMode(R1, OUTPUT);

   nexInit();
   bt0.attachPop(bt0PopCallback, &bt0);

   Serial.println("DHT Sensor Reading");
   dbSerialPrintln("setup done");
}

void loop(void) {
  nexLoop(nex_listen_list);
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  if (isnan(h) || isnan(t)) {
    Serial2.println(F("Failed to read from DHT sensor!"));
    return;
  }

  static char temperatureCTemp[10];
  dtostrf(t, 6, 2, temperatureCTemp);
  tTempC.setText(temperatureCTemp);

  char hTemp[10] = {0};
  utoa(int(h), hTemp, 10);
  tHumidity.setText(hTemp);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print("°C ");
  //Serial2.print(F("tTempC.txt="));

  //Serial.print("");
  //Serial.print(F("tHumidity.txt:\ "));
  //Serial.print(h);
  //Serial.write(0xff);
  //Serial.write(0xff);
  //Serial.write(0xff);
}
```

Thanks in Advance.

title: To control the relay switching in nextion using esp32 Microcontroller

Answers: 3

body:
I think this method inefficent. Because ESP32  continuously listens to the button state.

You will try this method . Working for me .

    int R1 = 2;
    NexDSButton bt0 = NexDSButton(0, 8, "bt0");
    uint32_t dual_state=0;

    void setup(){
    nexInit();
    pinMode(R1, OUTPUT);
    }
    void loop(){
    bt0.getValue(&dual_state);

    if(dual_state==1) //When pressed dual state button dual_state =1
      {
        digitalWrite(R1, HIGH);
      }
      else if(dual_state==0)
      {
        digitalWrite(R1,LOW );
      }

    }

body:
This is my updated code to display the temperature and humidity in Nextion display and also to control the relay switching in Nextion display. It works good.
<!-- language-all: lang-cpp -->

    #include "NexDualStateButton.h"
    #include "Nextion.h"
    #include "DHT.h"

    #define DHTPIN 27
    #define DHTTYPE DHT22

    DHT dht(DHTPIN, DHTTYPE);

    int R1 = 2;
    NexDSButton bt0 = NexDSButton(0, 8, "bt0");
    NexText tTempC = NexText(0, 4, "tTempC");
    NexText tHumidity = NexText(0, 6, "tHumidity");
    uint32_t dual_state=0;

    void setup(){
      dht.begin();
      nexInit();
      pinMode(R1, OUTPUT);
    }

    void loop(){
      bt0.getValue(&dual_state);

      if(dual_state==1) //When pressed dual state button dual_state =1
      {
        digitalWrite(R1, HIGH);
      }
      else if(dual_state==0)
      {
        digitalWrite(R1,LOW );
      }
      float t = dht.readTemperature();
      float h = dht.readHumidity();

      if (isnan(h) || isnan(t)) {
        Serial2.println(F("Failed to read from DHT sensor!"));
        return;
      }

      static char temperatureCTemp[10];
      dtostrf(t, 6, 2, temperatureCTemp);
      tTempC.setText(temperatureCTemp);

      char hTemp[10] = {0};
      utoa(int(h), hTemp, 10);
      tHumidity.setText(hTemp);

      Serial.print(F("Humidity: "));
      Serial.print(h);
      Serial.print(F("%  Temperature: "));
      Serial.print(t);
      Serial.print("°C ");

    }

body:
There is a simpler way to print the temperature to the display and call the BT button without using the Nextion Library. In this example, I am using a TCA9548A because I am using 2 BMP280s.

    void TEMP() {
      delay(125);
      TCA9548A(0);
      HMISerial10.print("t8.txt=\"");
      HMISerial10.print((bmp.readTemperature() * 1.8) + 32);
      HMISerial10.print("\"");
      HMISerial10.write(0xff);
      HMISerial10.write(0xff);
      HMISerial10.write(0xff);
      Serial.print("Inside Temp: ");
      Serial.println((bmp.readTemperature() * 1.8) + 32);

      TCA9548A(1);
      HMISerial10.print("t7.txt=\"");
      HMISerial10.print((bmp.readTemperature() * 1.8) + 32);
      HMISerial10.print("\"");
      HMISerial10.write(0xff);
      HMISerial10.write(0xff);
      HMISerial10.write(0xff);
      Serial.print("Outside Temp: ");
      Serial.println((bmp.readTemperature() * 1.8) + 32);
    }

Here I have it looking for a button from the Nextion

    void dfd_listen() {

      delay(30);
      dfd = ""; //dfd means Data From Display
      while (HMISerial5.available()) { //This will look to see if there is something coming from the Nextion
        dfd += char(HMISerial5.read());
      }

      if (dfd.substring(1, 4) == "bt4" && dfd.substring(0, 1) == "0") {
        digitalWrite(R6, LOW);   // Roof Lights
        HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
        HMISerial5.write(0xff);
        HMISerial5.write(0xff);
        Serial.println("Roof Lights OFF");
      } else if (dfd.substring(1, 4) == "bt4" && dfd.substring(0, 1) == "1") {
        digitalWrite(R6, LOW);   // Roof Lights
        HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
        HMISerial5.write(0xff);
        HMISerial5.write(0xff);
        Serial.println("Roof Lights ON");
      }

      if (dfd.substring(1, 4) == "b17") {
        HMISerial5.print("page 1");
        HMISerial5.write(0xff);  // We always have to send this three lines after each command sent to the nextion display.
        HMISerial5.write(0xff);
        HMISerial5.write(0xff);
        Serial.println("Change to Page 1");
        dfd = "";
        delay(100);
      }

Now this shows both BT and B buttons. The HMISerial are my serial ports the Nextion are attached to. The "dfd" is set as a string before your setup.
For the Nextion button, you just have to add a value and set it as a string, in this case, my value is va11. Then on the button on the press event, you would put something like this.

      if(bt4.val==1)
    {
      cov bt4.val,va11.txt,1
      va11.txt+="bt4"
      print va11.txt
      t4.pco=17576
    }else if(bt4.val==0)
    {
      cov bt4.val,va11.txt,1
      va11.txt+="bt4"
      print va11.txt
      t4.pco=57033
    }


body:
I am using a SIM800L Module with esp32. I am using a 3.7V 2800mAh lipo battery to power the sim800L but the LED is not blinking. I am lookng for answers in web but evryone seems to have a different problem than mine. In other case the sim800l is at least blinkng or blinked once.
I have tested the led with multimeter and it glows so hopefully the board is okay.
Is the power supplied by the battery is not sufficient? I followed this [tutorial][1]

  [1]: https://lastminuteengineers.com/sim800l-gsm-module-arduino-tutorial/
I am sure about the sim card as it is a working sim card in INDIA (of IDEA) and works fine in my smart phone.

title: SIM800L LED is not blinking

Answers: 2

body:
So I Finally sort out the problem. Both Battery and Module was completely fine. The problem was with the connecting wires. The connecting wires for some reason was not capable to hold the 2amp current. As a solution what I did was, cut the legs of some  quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine.

Even it seems a weird problem with no proper explanation but this solution works for me.

-----------Editing for a better explanation-------------

So my problem was with the connecting wires. For some reason the wires I primarily used could not deliver the the current from battery terminals to the module. May be those wires had a higher resistance for which the current flowing through those could not stay at 2 ampere magnitude and by the time it traveerses the wires and reached to the module, it was no longer at 2 ampere and might be lesser than a certain value which could not trigger the module and so the module did not work.

what I did was cut some legs of a few quatter watt [resistance][1] (the metal leads getting out from the carbon resistance from both sides:pic added) and sholder them to the battery terminals. Since I knew the metal legs of quatter watt resistances had a very less resistance from my course that trick worked and delivered 2amp current through them to the module.

I am trully sorry for not attaching picture as I have already submitted the project and currently have no way to replicate the situation.

  [1]: https://5.imimg.com/data5/VF/IK/MY-28674975/carbon-resistor-500x500.jpg

body:
Can you please explain this part again? if possible,upload image!

As a solution what I did was, cut the legs of some quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine


body:
I want to publish image capture through [ESP32-CAM][1] to MQTT. Have following code :

    #include "WiFi.h"
    #include "esp_camera.h"
    #include "esp_timer.h"
    #include "img_converters.h"
    #include "Arduino.h"
    #include "soc/soc.h"           // Disable brownour problems
    #include "soc/rtc_cntl_reg.h"  // Disable brownour problems
    #include "driver/rtc_io.h"
    #include <StringArray.h>

    #include <PubSubClient.h>
    #include <base64.h>
    #include <libb64/cencode.h>

    // Replace with your network credentials
    const char* ssid = "####";
    const char* password = "####";

    // Add your MQTT Broker IP address, example:
    const char* mqtt_server = "###.cloudmqtt.com";
    const int mqtt_port = 11073;
    const char* mqtt_user = "###";
    const char* mqtt_password = "###";

    #define SLEEP_DELAY 10000 //Delay ofr 10 Sec
    #define FILE_PHOTO "/photo.jpg"

    // OV2640 camera module pins (CAMERA_MODEL_AI_THINKER)
    #define PWDN_GPIO_NUM     32
    #define RESET_GPIO_NUM    -1
    #define XCLK_GPIO_NUM      0
    #define SIOD_GPIO_NUM     26
    #define SIOC_GPIO_NUM     27
    #define Y9_GPIO_NUM       35
    #define Y8_GPIO_NUM       34
    #define Y7_GPIO_NUM       39
    #define Y6_GPIO_NUM       36
    #define Y5_GPIO_NUM       21
    #define Y4_GPIO_NUM       19
    #define Y3_GPIO_NUM       18
    #define Y2_GPIO_NUM        5
    #define VSYNC_GPIO_NUM    25
    #define HREF_GPIO_NUM     23
    #define PCLK_GPIO_NUM     22

    //#define ESP32_CLIENT_ID = WiFi.macAddress()
    //const char* esp_client_id = WiFi.macAddress()
    WiFiClient mqttClient;
    PubSubClient client(mqttClient);

    const int LED_BUILTIN = 4;

    void setup_camera() {
          // Turn-off the 'brownout detector'
          WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

          // OV2640 camera module
          camera_config_t config;
          config.ledc_channel = LEDC_CHANNEL_0;
          config.ledc_timer = LEDC_TIMER_0;
          config.pin_d0 = Y2_GPIO_NUM;
          config.pin_d1 = Y3_GPIO_NUM;
          config.pin_d2 = Y4_GPIO_NUM;
          config.pin_d3 = Y5_GPIO_NUM;
          config.pin_d4 = Y6_GPIO_NUM;
          config.pin_d5 = Y7_GPIO_NUM;
          config.pin_d6 = Y8_GPIO_NUM;
          config.pin_d7 = Y9_GPIO_NUM;
          config.pin_xclk = XCLK_GPIO_NUM;
          config.pin_pclk = PCLK_GPIO_NUM;
          config.pin_vsync = VSYNC_GPIO_NUM;
          config.pin_href = HREF_GPIO_NUM;
          config.pin_sscb_sda = SIOD_GPIO_NUM;
          config.pin_sscb_scl = SIOC_GPIO_NUM;
          config.pin_pwdn = PWDN_GPIO_NUM;
          config.pin_reset = RESET_GPIO_NUM;
          config.xclk_freq_hz = 20000000;
          config.pixel_format = PIXFORMAT_JPEG;

          if (psramFound()) {
            config.frame_size = FRAMESIZE_UXGA;
            config.jpeg_quality = 10;
            config.fb_count = 2;
          } else {
            config.frame_size = FRAMESIZE_SVGA;
            config.jpeg_quality = 12;
            config.fb_count = 1;
          }
          // Camera init
          esp_err_t err = esp_camera_init(&config);
          if (err != ESP_OK) {
            Serial.printf("Camera init failed with error 0x%x", err);
            ESP.restart();
          }
      }

    // Capture Photo and Save it to SPIFFS
    void capturePhoto( void ) {
      camera_fb_t * fb = NULL; // pointer
      bool ok = 0; // Boolean indicating if the picture has been taken correctly

      // Take a photo with the camera
      Serial.println("Taking a photo...");

      fb = esp_camera_fb_get();
      if (!fb) {
        Serial.println("Camera capture failed");
        return;
      }

      Serial.print("Heap Size : ");
      Serial.println(ESP.getFreeHeap());
      //Serial.println(fb->format);
      Serial.print("fb len : ");
      Serial.println(fb->len);
      Serial.print("base64 encode expected len : ");
      Serial.println(base64_encode_expected_len(fb->len) + 1);
      String base64image = base64::encode(fb->buf, fb->len);
      Serial.print("base64 image : ");
      Serial.println(base64image);
      esp_camera_fb_return(fb);
    }

    void setup_wifi() {
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("IP address : ");
      Serial.println(WiFi.localIP());
    }

    void reconnect() {
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
          Serial.println("connected");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          delay(5000);
        }
      }
    }

    void setup() {
      Serial.begin(115200);
      setup_camera();
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
      setup_wifi();
      client.setServer(mqtt_server, mqtt_port);
    }

    // the loop function runs over and over again forever
    void loop() {
      Serial.println("PSRAM found: " + String(psramFound()));
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
      capturePhoto();
      if (!client.connected()) {
        reconnect();
      }
      client.loop();
      delay(SLEEP_DELAY);
    }

This prints following to console

    Connecting to ####
    ...
    WiFi connected
    IP address : 192.168.1.247
    PSRAM found: 1
    Taking a photo...
    Heap Size : 187548
    fb len : 135966
    base64 encode expected len : 181289
    base64 image : -FAIL-

**Update Feb 15 :**

I tried following code

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

    // the loop function runs over and over again forever
    void loop() {
      Serial.println("PSRAM found: " + String(psramFound()));
      Serial.print("Total heap: ");
      Serial.println(ESP.getHeapSize());
      Serial.print("Free heap: ");
      Serial.println(ESP.getFreeHeap());
      Serial.print("Total PSRAM: ");
      Serial.println(ESP.getPsramSize());
      Serial.print("Free PSRAM: ");
      Serial.println(ESP.getFreePsram());
    }

which printed

    PSRAM found: 1
    Total heap: 378748
    Free heap: 352836
    Total PSRAM: 4194252
    Free PSRAM: 4194252

These are the board settings

Board : AI Thinker ESP32 CAM

Latest board package :
[![enter image description here][2]][2]

I tried wit following board settings as well

**Board** : ESP32 Dev Module
**Upload Speed** : 921600
**CPU Frequency** : 240 MHz
**Flash Frequency** : 80 MHz
**Flash Mode** : QIO
**Flash Size** : 4MB
**Partition Scheme** : Default 4MB with spiffs
**Core Debug Level** : Verbose
**PSRAM** : Enabled

which also gives me following output

    [D][esp32-hal-psram.c:47] psramInit(): PSRAM enabled

    Connecting to ###
    [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
    [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
    [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
    [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
    [D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.247, MASK: 255.255.255.0, GW: 192.168.1.1
    .
    WiFi connected
    IP address : 192.168.1.247
    PSRAM found: 1
    Taking a photo...
    Heap Size : 187260
    fb len : 101157
    base64 encode expected len : 134877
    base64 image : -FAIL-

From this output it looks like PSRAM is enabled. How can I use it for base64 encoded image ?

Also tried to add `byte* psdRamBuffer = (byte*)ps_malloc(500000);` mentioned at https://thingpulse.com/esp32-how-to-use-psram/ but didn't help.

I have this [ESP32-CAM][1]

Update :

I got following working, but it crashes for `framesize_t resolution_ =FRAMESIZE_QXGA;` that's why not able to capture 2 Megapixel picture.

    #include "WiFi.h"
    #include "esp_camera.h"
    #include "esp_timer.h"
    #include "img_converters.h"
    #include "Arduino.h"
    #include "soc/soc.h"           // Disable brownour problems
    #include "soc/rtc_cntl_reg.h"  // Disable brownour problems
    #include "driver/rtc_io.h"
    #include "SPIFFS.h"
    #include "base64.h"
    #include <PubSubClient.h>

    // Replace with your network credentials
    const char* ssid = "xxxxx";
    const char* password = "xxxxx";

    // Add your MQTT Broker IP address, example:
    const char* mqtt_server = "xxxx.cloudmqtt.com";
    const int mqtt_port = 1883;
    const char* mqtt_user = "xxxx";
    const char* mqtt_password = "xxxxx";

    //topic name
    const char* mqtt_TopicName = "/devices/esp32/data";

    framesize_t resolution_ = FRAMESIZE_QVGA;

    //use this delay 1000==1 second
    #define SLEEP_DELAY 60000 //Delay ofr 60 Sec
    #define FILE_PHOTO "/photo.jpg"

    // OV2640 camera module pins (CAMERA_MODEL_AI_THINKER)
    #define PWDN_GPIO_NUM     32
    #define RESET_GPIO_NUM    -1
    #define XCLK_GPIO_NUM      0
    #define SIOD_GPIO_NUM     26
    #define SIOC_GPIO_NUM     27
    #define Y9_GPIO_NUM       35
    #define Y8_GPIO_NUM       34
    #define Y7_GPIO_NUM       39
    #define Y6_GPIO_NUM       36
    #define Y5_GPIO_NUM       21
    #define Y4_GPIO_NUM       19
    #define Y3_GPIO_NUM       18
    #define Y2_GPIO_NUM        5
    #define VSYNC_GPIO_NUM    25
    #define HREF_GPIO_NUM     23
    #define PCLK_GPIO_NUM     22

    //#define ESP32_CLIENT_ID = WiFi.macAddress()
    //const char* esp_client_id = WiFi.macAddress()
    WiFiClient mqttClient;
    PubSubClient client(mqttClient);

    const int LED_BUILTIN = 4;

    void setup_camera() {
          // Turn-off the 'brownout detector'
          WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

          // OV2640 camera module
          camera_config_t config;
          config.ledc_channel = LEDC_CHANNEL_0;
          config.ledc_timer = LEDC_TIMER_0;
          config.pin_d0 = Y2_GPIO_NUM;
          config.pin_d1 = Y3_GPIO_NUM;
          config.pin_d2 = Y4_GPIO_NUM;
          config.pin_d3 = Y5_GPIO_NUM;
          config.pin_d4 = Y6_GPIO_NUM;
          config.pin_d5 = Y7_GPIO_NUM;
          config.pin_d6 = Y8_GPIO_NUM;
          config.pin_d7 = Y9_GPIO_NUM;
          config.pin_xclk = XCLK_GPIO_NUM;
          config.pin_pclk = PCLK_GPIO_NUM;
          config.pin_vsync = VSYNC_GPIO_NUM;
          config.pin_href = HREF_GPIO_NUM;
          config.pin_sscb_sda = SIOD_GPIO_NUM;
          config.pin_sscb_scl = SIOC_GPIO_NUM;
          config.pin_pwdn = PWDN_GPIO_NUM;
          config.pin_reset = RESET_GPIO_NUM;
          config.xclk_freq_hz = 20000000;
          config.pixel_format = PIXFORMAT_JPEG;

          if (psramFound()) {
            config.frame_size = resolution_  ;// FRAMESIZE_UXGA;
            config.jpeg_quality = 10;
            config.fb_count = 1;
          } else {
            config.frame_size = FRAMESIZE_SVGA;
            config.jpeg_quality = 12;
            config.fb_count = 2;
          }
          // Camera init
          esp_err_t err = esp_camera_init(&config);
          if (err != ESP_OK) {
            Serial.printf("Camera init failed with error 0x%x", err);
            ESP.restart();
          }
      }

    void publishTelemetryFromFile() {
      File file = SPIFFS.open("/b64image.txt", FILE_READ);
      if (!file) {
        Serial.println("There was an error opening the file for read");
        return;
      } else {
        Serial.println(String(file.size())+ "Byte");

      }

      char* data = (char*)heap_caps_malloc(file.size()+1, MALLOC_CAP_8BIT);
      if (data == NULL)
        Serial.println("Can not malloc memory");

      int i=0;

      //while(file.available()){
      for (i=0;i<file.size();i++){
        data[i] = file.read();

      }

      delay(10);

      //client.publish_P( mqtt_TopicName,"qwertyuiopasdfghjkl;zxcvbnm,", true);
      Serial.print( "Published to MQTT " + String(mqtt_server) + " server.." );
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      boolean Status=client.publish_P( mqtt_TopicName, (const uint8_t*)data, file.size(), true);
      Serial.println(String(Status? "Successfully":"Error") );

      free(data);
      file.close();
    }

    void capturePhoto( void ) {
       // Retrieve camera framebuffer
      camera_fb_t * fb = NULL;
      uint8_t* _jpg_buf = NULL;
      esp_err_t res = ESP_OK;
      size_t frame_size = 0;
      Serial.print("Capturing Image ..");

      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      fb = esp_camera_fb_get();
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
      if (!fb) {
        Serial.println("Camera capture failed");
        res = ESP_FAIL;
      } else {
        Serial.println("Done!");
        Serial.println(String("Size of the image...")+String(fb->len));

        {

          if(fb->format != PIXFORMAT_JPEG){
            Serial.println("Compressing");
            bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &frame_size);
            esp_camera_fb_return(fb);
            fb = NULL;
            if(!jpeg_converted){
              Serial.println("JPEG compression failed");
              res = ESP_FAIL;
            }
          } else {
            frame_size = fb->len;
            _jpg_buf = fb->buf;
            Serial.print("Size of the base64 encoded image...");

            my_base64_encode(_jpg_buf,fb->len,String("Sat Mar 28 11:47:01 EDT 2020") );
            esp_camera_fb_return(fb);
            publishTelemetryFromFile();

          }
        }
      }
      if (res != ESP_OK) {
     //   ESP_LOGW(TAG, "Camera capture failed with error = %d", err);

        return;
      }

     }

    void setup_wifi() {
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("IP address : ");
      Serial.println(WiFi.localIP());
    }

    void reconnect() {
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
          Serial.println("connected");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          delay(5000);
        }
      }
    }

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

      //byte* psdRamBuffer = (byte*)ps_malloc(500000);
      setup_camera();
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
      setup_wifi();
      client.setServer(mqtt_server, mqtt_port);
       if (!SPIFFS.begin(true)) {
        Serial.println("An Error has occurred while mounting SPIFFS");
        return;
      }
    }

    // the loop function runs over and over again forever
    void loop() {
      Serial.println("PSRAM found: " + String(psramFound()));

      capturePhoto();

      if (!client.connected()) {
        reconnect();
      }

      client.loop();
      delay(SLEEP_DELAY);
    }

  [1]: https://www.amazon.com/gp/product/B07MDLFQH2/
  [2]: https://i.stack.imgur.com/pLI8t.png

title: esp32-cam publish image to mqtt

Answers: 2

body:
As you can see [here](https://github.com/espressif/esp32-camera/blob/98669b337cb915ba2a154a73454eed7fbf8e4795/driver/include/esp_camera.h#L112-L118), the definition of the return value for `esp_camera_fb_get()` is

```cpp
typedef struct {
    uint8_t * buf;              /*!< Pointer to the pixel data */
    size_t len;                 /*!< Length of the buffer in bytes */
    size_t width;               /*!< Width of the buffer in pixels */
    size_t height;              /*!< Height of the buffer in pixels */
    pixformat_t format;         /*!< Format of the pixel data */
} camera_fb_t;

..
camera_fb_t* esp_camera_fb_get();

..

typedef enum {
    PIXFORMAT_RGB565,    // 2BPP/RGB565
    PIXFORMAT_YUV422,    // 2BPP/YUV422
    PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE
    PIXFORMAT_JPEG,      // JPEG/COMPRESSED
    PIXFORMAT_RGB888,    // 3BPP/RGB888
    PIXFORMAT_RAW,       // RAW
    PIXFORMAT_RGB444,    // 3BP2P/RGB444
    PIXFORMAT_RGB555,    // 3BP2P/RGB555
} pixformat_t;
```

Meaning that `fb->buf` and `bf->len` hold the raw data in the format specified by `pixformat_t`. Aka this is not a "string", these are raw bytes, which you can still base64-encode perfectly fine.

So for the base64 library

```
    static String encode(const uint8_t * data, size_t length);
```

it already accepts the right data type and you can do

```
  fb = esp_camera_fb_get();
  ..
  //will be allocated on the heap. Takes about 4/3 of the input size, so basically it doubles your memory requirements
  String imgDataB64 = base64::encode(fb->buf, fb->len);
  //add to a JSON object wit the metadata width, height and format so that it can be decoded
```

You should output the `fb->format` value to check what format the data is, and add this and the width & height information so that the image may be constructted on the other side. Beware high memory requierements since the base64 encoding basically creates a new buffer to store the base64 representation of it. That may be optimized by writing the framebuffer data into an initially bigger buffer which is then transformed in-place. But that would have to be changed at the image driver level.

body:
If it is still not working for you try below code it's working for me:
<!-- language-all: lang-cpp -->

     int image_buf_size = 4000 * 1000;
     uint8_t *image = (uint8_t *)ps_calloc(image_buf_size, sizeof(char));

     size_t length=fb->len;

     size_t olen;

     Serial.print("length is");

     Serial.println(length);
     int err1= mbedtls_base64_encode(image, image_buf_size, &olen, fb->buf, length);

     Serial.println(err1);

     String img((const __FlashStringHelper*) image);

     Serial.println(img);
     //msg1=img;


body:
My MkrWan running on 5v 3A external adapter without battery. When short time(15-20 second) power outage happens Mkrwan still seems running. I think it consumes power on capacitors on adapter but voltage value drops. When electric comes back, it doesnt work anymore. Why it doesnt reset itself ?
How to solve this problem ?

title: MkrWan freezes after short power outage

Answers: 1

body: I connected Lipo battery to device. On power outages it supply power to board and brown out problem solved. Thanks a lot


body:
I'd like my ESP8266 to provide some JSON endpoints. I want to use ArduinoJson for serialisation. While this works in general if I serialize into a String and return this String afterwards, I was wondering if there is really no way to do this without wasting so much memory. Shouldn't it be possible to do something like this? Any hints?

    ESP8266WebServer server;
    StaticJsonDocument<768> response;
    response["night"] = _playback.isNight();
    response["shuffle"] = _playback.isShuffle();
    server.send_P(200, "application/json", NULL);
    serializeJson(response, server.client());

(this gives the following error:)

    no instance of overloaded function "serializeJson" matches the argument list -- argument types are: (ArduinoJson6141_0000010::StaticJsonDocument<768U>, WiFiServer::ClientType)

title: Serialize JSON as response to HTTP request

Answers: 1

body:
[`serializeJson()`](https://arduinojson.org/v6/api/json/serializejson/) accepts a `Print&`, i.e, a reference to a class that implements the `Print` interface.

`WiFiClient` does implement the `Print` interface, but [`serializeJson()`](https://arduinojson.org/v6/api/json/serializejson/) cannot make a reference to it because `ESP8266WebServer::client()` returns a temporary. Indeed, C++ forbids references to temporary variables, only `const` reference to temporaries are allowed.

To fix this compilation error, you must extract a variable:

```c++
WiFiClient client = server.client();
serializeJson(doc, client);
```

The way I see it, `ESP8266WebServer::client()` should return a `WiFiClient&` instead of a `WiFiClient`, just as `HTTPClient::getStream()` does. I opened [issue #7075](https://github.com/esp8266/Arduino/issues/7075) about that.

Anyway, even it this fixes the compilation, I'm not sure it will work as you intend because `ESP8266WebServer` may not allow writing directly to the `WiFiClient`.


body:
I am working on a project to run some (relays or LED's) on an inputs (Pins) Arduino by esp8266-01s . now while searching on internet I found a video divided it two step that talks about the issue using a ESP8266-01. The important thing in the topic is that the person uses two codes for project :

1) The first code for esp8266.

2) The second code for arduino uno.

The most important part of the topic I want to modify the code for esp8266 . but the owner of the video uses node red website and I want to use the cayenne website . **I want to specify basic commands to modify in order to work on cayenne website .**

I play with esp and arduino in order to project offline.

[First video][1] , [Second video][2]

**// Code to upload onto ESP8266**

     #include <PubSubClient.h>
     #include <ESP8266WiFi.h>

     //EDIT THESE LINES TO MATCH YOUR SETUP
     #define MQTT_SERVER "192.168.1.117"  ///YourMQTTBroker'sIP
     const char* ssid = "Weems_2GHz";
     const char* password = "1029384756";

     char* Topic = "inTopic"; //subscribe to topic to be notified about

     WiFiClient wifiClient;

     void setup() {
     //initialize the light as an output and set to LOW (off)

     //start the serial line for debugging
     Serial.begin(9600);
     delay(100);

    //start wifi subsystem
    WiFi.begin(ssid, password);
    //attempt to connect to the WIFI network and then connect to the MQTT server
    reconnect();

    //wait a bit before starting the main loop
      delay(2000);
    }

    PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

    void loop(){

    //reconnect if connection is lost
    if (!client.connected() && WiFi.status() == 3) {reconnect();}

    //maintain MQTT connection
    client.loop();

    //MUST delay to allow ESP8266 WIFI functions to run
    delay(20);

    }

    void callback(char* topic, byte* payload, unsigned int length) {

    //convert topic to string to make it easier to work with
    String topicStr = topic;

    //Print out some debugging info
    ////Serial.println("Callback update.");
    //Serial.print("Topic: ");
    //Serial.println(topicStr);

    //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
    if (payload[0] == '0'){
    Serial.print("0");
    respond();}
    if(payload[0] == '1'){
    Serial.print("1");
    respond();}
    if (payload[0] == '2'){
    Serial.print("2");
    respond();}
    if(payload[0] == '3'){
    Serial.print("3");
    respond();}
    if (payload[0] == '4'){
    Serial.print("4");
    respond();}
    if(payload[0] == '5'){
    Serial.print("5");
    respond();}
    if (payload[0] == '6'){
    Serial.print("6");
    respond();}
    if(payload[0] == '7'){
    Serial.print("7");
    respond();
    }

    }
    void respond(){
    delay(5);
    if (Serial.available()) {
    //read serial as a character
    char ser = Serial.read();
    switch (ser) {
      case 'a':
    client.publish("outTopic", "Relay 1 is ON");
    break;
      case 'b':
    client.publish("outTopic", "Relay 1 is OFF");
    break;
      case 'c':
    client.publish("outTopic", "Relay 2 is ON");
    break;
      case 'd':
    client.publish("outTopic", "Relay 2 is OFF");
    break;
      case 'e':
    client.publish("outTopic", "Relay 3 is ON");
    break;
      case 'f':
    client.publish("outTopic", "Relay 3 is OFF");
    break;
      case 'g':
    client.publish("outTopic", "Relay 4 is ON");
    break;
      case 'h':
    client.publish("outTopic", "Relay 4 is OFF");
    break;
    }//switch
    }//if
    }//void
    void reconnect() {

    //attempt to connect to the wifi if connection is lost
    if(WiFi.status() != WL_CONNECTED){

    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
    }
    }

    //make sure we are connected to WIFI before attemping to reconnect to MQTT
    if(WiFi.status() == WL_CONNECTED){
    // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      //Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(Topic);
      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
      }
      }
      }

      //generate unique name from MAC addr
      String macToStr(const uint8_t* mac){

      String result;

      for (int i = 0; i < 6; ++i) {
      result += String(mac[i], 16);

      if (i < 5){
      result += ':';
      }
      }

      return result;
      }

**/* control Relays via serial with numbers*/**

**/// Upload to Arduino uno**

     void setup(){
     Serial.begin(9600);
     //Set all the pins we need to output pins
     pinMode(12, OUTPUT);
     pinMode(11, OUTPUT);
     pinMode(10, OUTPUT);
     pinMode(9, OUTPUT);
     digitalWrite(12, HIGH);
     digitalWrite(11, HIGH);
     digitalWrite(10, HIGH);
     digitalWrite(9, HIGH);
     }

     void loop (){
     if (Serial.available()) {
     //read serial as a character
     char ser = Serial.read();

     //NOTE because the serial is read as "char" and not "int", the read value must be compared to character numbers
     //hence the quotes around the numbers in the case statement
     switch (ser) {
      case '0':
        digitalWrite(12, LOW);
        Serial.print("a");
        break;
      case '1':
        digitalWrite(12, HIGH);
        Serial.print("b");
        break;
      case '2':
        digitalWrite(11, LOW);
        Serial.print("c");
        break;
      case '3':
        digitalWrite(11, HIGH);
        Serial.print("d");
        break;
      case '4':
        digitalWrite(10, LOW);
        Serial.print("e");
        break;
      case '5':
        digitalWrite(10, HIGH);
        Serial.print("f");
        break;
      case '6':
        digitalWrite(9, LOW);
        Serial.print("g");
        break;
      case '7':
        digitalWrite(9, HIGH);
        Serial.print("h");
        break;

       }
      }
     }

  [1]: https://www.youtube.com/watch?v=yfwkHLDC0ow&feature=youtu.be
  [2]: https://www.youtube.com/watch?v=j1TnVpH__Ew&feature=youtu.be

title: How to edit code from Node-Red to Cayenne

Answers: 0


body:
I have a teensy 4.0 which runs at 600MHz, and is double superscaler (i.e. can execute two instructions per clock cycle, sometimes). I need an interrupt to happen faster than every microsecond. I've calculated that it's possible for the processor to run the my code at that speed with some reasonable overhead. **Can TimerOne (or similar) be set to produce an interrupt more than once per microsecond?**

Thanks in advance.

title: Faster TimerOne with Teensy 4.0 (600MHz)

Answers: 2

body:
You can use the [TeensyTimerTool][1] for this. It provides a generic interface to the hardware timers (TMR, GPT, PIT) and 20 software timers. Since the coupling of the timer peripherals to the ARM core is rather inefficient, the software timers might be a better fit for sub micro second interrupts.
If you prefer the hardware timers I suggest to use a GPT timer (also supported by the lib). You can configure it to use a 150MHz clock instead of the standard 24MHz clock. So something like 2MHz interrupt rate should be feasible.

Documentation can be found here: https://github.com/luni64/TeensyTimerTool/wiki

  [1]: https://github.com/luni64/TeensyTimerTool

body:
I had a similar problem with the Teensy 3.5.
I found that using the "Periodic Interrupt Timer (PIT)" let me generate interrupt every 300 ns.
I imagine that with a Teensy 4.0, it must be possible to generate an interrupt every 100 ns.
Here is the code which works for me on my Teensy 3.5,
with comments in french and some references in the comments.
I test the signal on an oscilloscope.

```c++
// ex00305_Timer_pit0_isr_rapide.ino
/*

FONCTIONNE TRES BIEN

Le signal n'est pas très stable, mais acceptable.
J'imagine que d'autres routines d'interruption perturbe la précision, comme la routine millis()

L'instruction suivante améliore la stabilité. visiblement.
NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0);

Le but est de tester l'utilisation du Timer1 .c.f
/home/bg/Arduino/Teensy/Teensy_3_5_manual_K64P144M120SF5RM.pdf
Page 1083, Chapter 41 : "Periodic Interrupt Timer (PIT)"

Pour la gestion des timers PIT, c.f.
====================================
https://github.com/loglow/PITimer/blob/master/PITimer.cpp

********************************************************************************** */

#define PINOUT1 34
#define LEDRED  24
#define LEDYELLOW  25
#define LEDGREEN  26

volatile byte bEtat = 0;

void setup() {
    //============
    pinMode(PINOUT1, OUTPUT);
    digitalWriteFast(PINOUT1, HIGH);

    pinMode(33, OUTPUT);
    pinMode(34, OUTPUT);
    pinMode(LEDRED, OUTPUT);  digitalWriteFast(LEDRED, LOW);
    pinMode(LEDYELLOW, OUTPUT);  digitalWriteFast(LEDYELLOW, LOW);
    pinMode(LEDGREEN, OUTPUT);  digitalWriteFast(LEDGREEN, LOW);

    //if (SIM_SCGC6_PIT == 0b100000000000000000000000) digitalWriteFast(LEDYELLOW, HIGH);
    SIM_SCGC6 |= SIM_SCGC6_PIT; // C.f. page 317.  PIT Clock Gate Control   SIM_SCGC6_PIT == 0b100000000000000000000000

    // C.f. : /home/bg/.arduino15/packages/teensy/hardware/avr/1.58.1/cores/teensy3/kinetis.h
    // #define NVIC_ENABLE_IRQ(n) (*((volatile uint32_t *)0xE000E100 + ((n) >> 5)) = (1 << ((n) & 31)))
    // enable IRQ Interrupt
    NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0); // Haute priorité, pour ne pas être perturbé par d'autres interrupt. Amélioration visible !
    NVIC_ENABLE_IRQ(IRQ_PIT_CH0);
    PIT_TCTRL0 = 3; // 0b011;  // enable Timer 0 interrupts ; start Timer 0   IRQ_PIT_CH0 == 48  Dans #elif defined(__MK64FX512__)
    //if (IRQ_PIT_CH0 == 48) digitalWriteFast(LEDGREEN,  HIGH);

    // Efface le flag du timer, pour permettre d'autres interruptions, nécessaire au départ
    PIT_TFLG0 = 1;

    // L'ordre des instruction a de l'importance !
    //""""""""""""""""""""""""""""""""""""""""""""
    PIT_MCR = 0;  // turn on PIT
    //PIT_LDVAL0 = 600-1;  // == 10 micro secondes setup timer 0 for xxx cycles Fréqu = 60 MHz  dt = 16.666 ns
    //PIT_LDVAL0 = 120-1;  // == 2 micros second
    //PIT_LDVAL0 = 60-1;   // == 1 micros second
    //PIT_LDVAL0 = 30-1;   // == 500 ns
    //PIT_LDVAL0 = 24-1;   // == 400 ns
    //PIT_LDVAL0 = 21-1;   // == 350 ns
    //PIT_LDVAL0 = 20-1;   // == 333 ns
    //PIT_LDVAL0 = 18-1;   // == 300 ns
    PIT_LDVAL0 = 120-1;
} // setup

void loop() {
    //===========
} // loop

void pit0_isr() {  // C.f. mk20dx128.c
    //===============
    // J'espère pouvoir gérer un temps

    // Efface le flag du timer, pour permettre d'autres interruptions
    // Doit être mis en début de routine !!!
    PIT_TFLG0 = 1;

    if (bEtat) {
        digitalWriteFast(PINOUT1, HIGH);
        //digitalWriteFast(LEDRED,  HIGH);
        bEtat = 0;
    }
    else {
        bEtat = 1;
        digitalWriteFast(PINOUT1, LOW);
        //digitalWriteFast(LEDRED,  LOW);
    }

} // pit0_isr
```


body: I've seen people use code like `PORTB |= 0x1 << 6` to set the sixth bit of PORTB in arduino. I understand that this is significantly faster than using `digitalWrite`. How can this be done using a modern Teensy (i.e. 3.6 or 4.0) if at all?

title: What is the equivilent of PORTx for Teensy (4.0)?

Answers: 1

body:
All Teensies support digitalWriteFast out of the box. digitalWriteFast compiles to just setting the bit in the right port register. You can not do that faster by direct register manipulation.

However, if for some reason you do want to manipulate the registers directly here the pin/gpio relation for the T4. (Generated by the sketch described here: https://github.com/luni64/TeensyTimerTool/wiki/Avoid-PWM-timer-clashes")

```
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
00  |  GPIO6_03  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
07  |  GPIO7_17  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
10  |  GPIO7_00  |  QUAD1
11  |  GPIO7_02  |  QUAD1
12  |  GPIO7_01  |  QUAD1
13  |  GPIO7_03  |  QUAD2
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
16  |  GPIO6_23  |  no pwm
17  |  GPIO6_22  |  no pwm
18  |  GPIO6_17  |  QUAD3
19  |  GPIO6_16  |  QUAD3
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
33  |  GPIO9_07  |  FLEX_PWM2
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1

#### Sorted by PWM timer
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
10  |  GPIO7_00  |  QUAD1
13  |  GPIO7_03  |  QUAD2
18  |  GPIO6_17  |  QUAD3
15  |  GPIO6_19  |  QUAD3
14  |  GPIO6_18  |  QUAD3
19  |  GPIO6_16  |  QUAD3
24  |  GPIO6_12  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
23  |  GPIO6_25  |  FLEX_PWM4
22  |  GPIO6_24  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
02  |  GPIO9_04  |  FLEX_PWM4
27  |  GPIO6_31  |  no pwm
17  |  GPIO6_22  |  no pwm
26  |  GPIO6_30  |  no pwm
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
21  |  GPIO6_27  |  no pwm
20  |  GPIO6_26  |  no pwm
16  |  GPIO6_23  |  no pwm

#### Sorted by GPIO register:
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
01  |  GPIO6_02  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
19  |  GPIO6_16  |  QUAD3
18  |  GPIO6_17  |  QUAD3
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
17  |  GPIO6_22  |  no pwm
16  |  GPIO6_23  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
10  |  GPIO7_00  |  QUAD1
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
13  |  GPIO7_03  |  QUAD2
06  |  GPIO7_10  |  FLEX_PWM2
09  |  GPIO7_11  |  FLEX_PWM2
32  |  GPIO7_12  |  no pwm
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
28  |  GPIO8_18  |  FLEX_PWM3
31  |  GPIO8_22  |  no pwm
30  |  GPIO8_23  |  no pwm
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
29  |  GPIO9_31  |  FLEX_PWM3
```


body:
i am trying to parse a page from the route by using Arduino + Ethernet shield. before Arduino testing. I tested my code via python as it shows below. from this code i can get the data as i wish where we need authenticate user name and pass word to access to the router, as you see, here ( admin , admin) in the same time i have to used output variable to get only the data required. Python code is does it.

**Python code:**
```
My_url = "http://192.168.8.1/update.cgi"
r = requests.post (My_url, auth=('admin', 'admin'),data = 'output=netdev' )
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.text)
```

**The output is:**
```
200
text/javascript
ISO-8859-1
netdev = {
 'WIRED':{rx:0x84154,tx:0x5a0cba}
,'BRIDGE':{rx:0x7e680,tx:0x59d98a}
,'WIRELESS0':{rx:0x0,tx:0x0}
,'WIRELESS1':{rx:0x0,tx:0x0}
}
```

Now i am trying to do that by using Arduino + Ethernet shield and i would like print the output on the serial port as it is showing below. Here the router is server and the Arduino is client.

**My problem** is the POST request with the authentication, How I can do it ( POST with authentication + 'output=netdev' like in python code ). Please any idea .. Many thanks in advanced

**Arduino code :**
```
#include <Ethernet.h>
#include <SPI.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192,168,8,1);  // numeric IP for Google (no DNS)
//char server[] = "jsonplaceholder.typicode.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 8, 100);
IPAddress myDns(   8, 8, 8, 8);

// 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):
EthernetClient client;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  delay(1000);
  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:

    client.println("POST /update.cgi HTTP/1.0");
    client.println("Host: 192.168.8.1");
    client.println("Connection: close");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  //if (client.available()) {
  while (client.available()) {
    char c = client.read();
    Serial.print(c);

  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }

}
```

**Arduino output**

```
Initialize Ethernet with DHCP:
  DHCP assigned IP 192.168.8.107
connecting...
connected to 192.168.8.1
HTTP/1.0 401 Unauthorized
Server: httpd
Date: Sat, 01 Jan 2011 00:27:00 GMT
WWW-Authenticate: Basic realm="DR3800"
Content-Type: text/html
Connection: close

<HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
<BODY BGCOLOR="#cc9999"><H4>401 Unauthorized</H4>
Authorization required.
</BODY></HTML>

disconnecting.
```

---

Thank you Dougie for your anser. I used it , please you can see it in my code below where i used this library it gives no error for GET request , but when i use it ti POST request it gives same authentication problem as you see . where the POST request is important to get the data from .cgi page . Maybe i use that in wrong way .. any advice ? thanks

```
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.get("/"+contentType);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}
```
## The output is ok ##
```
making GET request with HTTP basic authentication
Status code: 200
Response:
Wait five seconds

```
## But for POST as follows : ##
```
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.post("/",contentType , postData);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}
```
## the output is : ##
```
making GET request with HTTP basic authentication
Status code: 401
Response: <HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
<BODY BGCOLOR="#cc9999"><H4>401 Unauthorized</H4>
Authorization required.
</BODY></HTML>

Wait five seconds

```

title: HTTP parsing with authentication in Arduino + ethernet shield

Answers: 1

body: Rather than trying to send your own GET/POST request by hand coding it, use https://github.com/arduino-libraries/ArduinoHttpClient which does it all for you.


body:
My Wemos card is reseting for unknown reason. For example, the pump plugged on the relay works fine till 1am and then the pump stop. After a few research I figured out the ESP should reset because all internal parameters are reseted.
[![enter image description here][1]][1]

My hardware is simple Wemos card + relay + sensors (not here because not connected yet).
[![enter image description here][2]][2]

My program is quite complex. I can command/configure the wemos via webservice (ex relay on pin 5 with on 5min/off 10min).
https://github.com/TittyPanda/ESP-commander/blob/master/ESP-COMMANDER

 - OK if no AC device is connected on relay (no reset)
 - OK if a light is connected on relay
 - The issue occurs only when the water pump is connected

Maybe it's an electrical/electromagnetical thing because the pump has motor. What do you think ?

Thanks,

**EDIT**
Power part are done with common wires from power extension cord

[AC-DC converter 5 V 1A 1.5A 500mA][3]
[![C-DC converter][4]][4]

[Pump 40W 3000L/H 220V 50Hz][5]
[![Pump][6]][6]

  [1]: https://i.stack.imgur.com/jijaJ.png
  [2]: https://i.stack.imgur.com/yoMOa.png
  [3]: https://fr.aliexpress.com/item/32800561583.html
  [4]: https://i.stack.imgur.com/E583J.png
  [5]: https://www.amazon.fr/gp/product/B07B8MHYCP
  [6]: https://i.stack.imgur.com/rabHp.png

title: ESP8266 reseted due to relay / AC plugged

Answers: 1

body:
Try add some power filter like this:
[![An LC filter][1]][1]

[![Filter image][2]][2]

Between the breadboard and ESP board.

  [1]: https://i.stack.imgur.com/xXRju.png
  [2]: https://i.stack.imgur.com/2meRd.jpg


body:
I am a newbie trying to interface the infrared temperature sensor MLX90614 with the arduino Due. But it keeps sending out junk values in the serial monitor. I've tried it out on the Arduino Mega and it works perfectly. What might be the problem and how do I rectify it?
Thanks in advance.

    #include <Wire.h>
    #include <Adafruit_MLX90614.h>

    Adafruit_MLX90614 mlx = Adafruit_MLX90614();

    void setup() {
      Serial.begin(9600);
      Serial.println("Adafruit MLX90614 test");
      mlx.begin();
    }
    void loop() {
      Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempC());
      Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
      Serial.print("Ambient = "); Serial.print(mlx.readAmbientTempF());
      Serial.print("*F\tObject = "); Serial.print(mlx.readObjectTempF()); Serial.println("*F");
      Serial.println();
      delay(500);
    }

title: Newbie interfacing MLX90614 with arduino Due (Atmel3X8E)

Answers: 0


body:
I'm using an arduino uno and ESP8266 (esp01) with the WiFiEsp library to connect to WiFi and POST data, connecting to WiFi works just fine.

I need to send a POST request, but I can't get it to work as I want.

```
 #include "WiFiEsp.h"
 // Emulate Serial1 on pins 7/8 if not present
 #ifndef HAVE_HWSERIAL1
 #include "SoftwareSerial.h"
 SoftwareSerial Serial1(6, 7); // RX, TX
 #endif
 char ssid[] = "Innovating-Guest"; // your network SSID (name)
 char pass[] = "wireless"; // your network password
 int status = WL_IDLE_STATUS; // the Wifi radio's status

 char server[] = "10.66.240.66";//http://10.66.240.66:8000/loadimage
 WiFiEspClient client; // Initialize the Ethernet client object

 void setup()
 {
 // initialize serial for debugging
 Serial.begin(9600);
 // initialize serial for ESP module
 Serial1.begin(9600);
 // initialize ESP module
 WiFi.init(&Serial1);
 // check for the presence of the shield
 if (WiFi.status() == WL_NO_SHIELD)
 {
 Serial.println("WiFi shield not present");
 // don't continue
 while (true);
 }

 // attempt to connect to WiFi network
 while ( status != WL_CONNECTED) {
 Serial.print("Attempting to connect to WPA SSID: ");
 Serial.println(ssid);
 // Connect to WPA/WPA2 network
 status = WiFi.begin(ssid, pass);
 }
 // you're connected now, so print out the data
 Serial.println("You're connected to the network");
 printWifiStatus();
 Serial.println();
 Serial.println("Starting connection to server...");
 // if you get a connection, report back via serial
 if (client.connect(server, 8000)) {
 Serial.println("Connected to server");
 String temp= "12.22";
 String humd= "23.33";
 String batt= "100";

 String content ="{\"temperature\": + temp +,\"humidity\":+ humd +,\"batteryPer\": + batt + }";
 client.println("POST /loadimage HTTP/1.1");
 client.println("Host: 10.66.240.66:8000");
 client.println("Accept: */*");
 client.print("Content-Length: ");
 client.println(content.length());
 client.println("Content-Type: application/json");
 client.println();
 client.println(content);
 }
 }
 void loop()
 {

 while (client.available()) {
 char c = client.read();
 Serial.write(c);
 }
 // 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);
  }
 }

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

 // print your WiFi shield'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");
 }

```

  [![Getting output on serial monitor as in image][1]][1]
Can anyone help me to know that why this error is coming.

Thanks in advance.

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

title: POST request using WiFiEsp.h library

Answers: 0


body:
I'm having some issues with esp8266 connecting to a wifi network. I'm testing with a hotspot from a mobile phone.  If I set the network to open (no security) my code below works without any issue. If I enable security, WPA2 PSK (I'm assuming that means the personal version) and add the password to the code it fails to connect. Any suggestions as to what the issue might be?

    //load softserial library
    #include <SoftwareSerial.h>

    //set a boolean constant variable to true
    //#define DEBUG true
    const boolean DEBUG = true;

    //RX (pin 2) goes to TX on esp8266, TX (pin 3) goes to RX on esp8266
    SoftwareSerial esp8266(2, 3);

    //LED pin anode (long leg) is 13 and cathode (short leg) GND
    int LED = 13;

    //LED status array - led 0 is OFF (0) at startup.
    int ledarray[] = {0};

    void setup()
    {
      //set the LED pin as output
      pinMode(LED, OUTPUT);

      //open the serial port
      Serial.begin(9600);

      //start esp8266 module (note: your esp's baud rate might be different)
      esp8266.begin(115200);

      //reset esp8266 module
      senddata("AT+RST\r\n", 2000, DEBUG);

      //set esp8266 as access point mode
      //senddata("AT+CWMODE=1\r\n", 1000, DEBUG);

      //set esp8266 as wireless station mode (web server)
      senddata("AT+CWMODE=1\r\n", 1000, DEBUG);

      //set network SSID and password if esp8266 is activate as station mode else comment out
      senddata("AT+CWJAP=\"test\", \"\"\r\n", 6000, DEBUG);

      //get ip address for esp8266
      senddata("AT+CIFSR\r\n", 2000, DEBUG);

      //configure esp8266 for multiple connections
      senddata("AT+CIPMUX=1\r\n", 1000, DEBUG);

      //turn on esp8266 server on port 80
      senddata("AT+CIPSERVER=1,80\r\n", 1000, DEBUG);
    }

    void loop()
    {
      //is the esp8266 sending a message
      if(esp8266.available())
      {
        //if received data from esp8266
        if (esp8266.find("+IPD,"))
        {
          //subtract 48 because the read() function returns the ASCII decimal
          //value and 0 (the first decimal number) starts at 48
          int connectionid = esp8266.read() - 48;

          //read the url sent by the client, look for the variable (?)
          String msg;
          esp8266.find("?");
          delay(100);
          msg = esp8266.readStringUntil(' ');
          String command = msg.substring(0);

          //HTML served to browser
          String webpage = "<title>LED WEB SWITCH</title>";
          webpage += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">";
          webpage += "
LED WEB SWITCH
";

          //if command is T (variable passed in button link on webpage)
          if (command == "T")
          {
            //if position 0 of ledarray is 1
            if (ledarray[0] == 1)
            {
              //turn LED off
              digitalWrite(LED, LOW);

              //set position 0 of ledarray to 0
              ledarray[0] = 0;

              //add text to webpage
              webpage += "
LED STATUS OFF
";
            }
            else
            {
              //turn the LED on
              digitalWrite(LED, HIGH);

              //set position 0 of ledarray to 1
              ledarray[0] = 1;

              //add text to webpage
              webpage += "
LED STATUS ON
";
            }
          }
          else
          {
            //add text to webpage
            webpage += "
LED STATUS OFF
";
          }

          //add the button (notice the href has a '?T')
          webpage += "TAP";

          //create a senddata string to send the wenbpage to the esp8266
          String cipsend = "AT+CIPSEND=";
          cipsend += connectionid;
          cipsend += ",";
          cipsend += webpage.length();
          cipsend += "\r\n";
          senddata(cipsend, 500, DEBUG);
          senddata(webpage, 500, DEBUG);

          //create a string closecommand, append the connection id, a return and newline
          String closecommand = "AT+CIPCLOSE=";
          closecommand += connectionid;
          closecommand += "\r\n";

          //send the closecommane
          senddata(closecommand, 500, DEBUG);
        }
      }
    }

    void senddata(String command, const int timeout, boolean debug)
    {
      //send the received command to the esp8266
      esp8266.print(command);

      //set int variable to the number of millisends since Arduino began
      long int time = millis();

      //while the time and the timeout is less than the number of millisends since Arduino began
      while((time + timeout) > millis())
      {
        //while the esp8266 is sending messages
        while(esp8266.available())
        {
          //display output in the serial window
          Serial.write(esp8266.read());
        }
      }
    }

title: ESP8266 and WPA2 PSK network

Answers: 1

body:
The solution to this was nothing to do with WPA2 PSK security or the baud rate being used. In my code I had a space between the WIFI server name and password (me correctly formatting). Apparently the ESP8266 does not like this one bit and the space needs to be removed - like so:

    //set network SSID and password if esp8266 is activate as station mode else comment out
    senddata("AT+CWJAP=\"test\",\"\"\r\n", 6000, DEBUG);


body:
![enter image description here](https://i.stack.imgur.com/YERdC.jpg)
Code

    /*Arduino Bluetooth Controlled Car
     *  * Created by Glen Tech
     * https://www.youtube.com/glentech
      */

    #include <AFMotor.h>

    //initial motors pin
    AF_DCMotor motor1(1);
    AF_DCMotor motor2(2);
    AF_DCMotor motor3(3);
    AF_DCMotor motor4(4);

    char command;

    void setup()
    {
      Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
    }

    void loop(){
      if(Serial.available() > 0){
        command = Serial.read();
        Stop(); //initialize with motors stoped
        //Change pin mode only if new command is different from previous.
        //Serial.println(command);
        switch(command){
        case 'F':
          forward();
          break;
        case 'B':
           back();
          break;
        case 'L':
          left();
          break;
        case 'R':
          right();
          break;
        }
      }
    }

    void forward()
    {
      motor1.setSpeed(1000); //Define maximum velocity
      motor1.run(FORWARD); //rotate the motor clockwise
      motor2.setSpeed(1000); //Define maximum velocity
      motor2.run(FORWARD); //rotate the motor clockwise
      motor3.setSpeed(1000);//Define maximum velocity
      motor3.run(FORWARD); //rotate the motor clockwise
      motor4.setSpeed(1000);//Define maximum velocity
      motor4.run(FORWARD); //rotate the motor clockwise
    }

    void back()
    {
      motor1.setSpeed(1000); //Define maximum velocity
      motor1.run(BACKWARD); //rotate the motor anti-clockwise
      motor2.setSpeed(1000); //Define maximum velocity
      motor2.run(BACKWARD); //rotate the motor anti-clockwise
      motor3.setSpeed(1000); //Define maximum velocity
      motor3.run(BACKWARD); //rotate the motor anti-clockwise
      motor4.setSpeed(1000); //Define maximum velocity
      motor4.run(BACKWARD); //rotate the motor anti-clockwise
    }

    void left()
    {
      motor1.setSpeed(255); //Define maximum velocity
      motor1.run(BACKWARD); //rotate the motor anti-clockwise
      motor2.setSpeed(255); //Define maximum velocity
      motor2.run(BACKWARD); //rotate the motor anti-clockwise
      motor3.setSpeed(255); //Define maximum velocity
      motor3.run(FORWARD);  //rotate the motor clockwise
      motor4.setSpeed(255); //Define maximum velocity
      motor4.run(FORWARD);  //rotate the motor clockwise
    }

    void right()
    {
      motor1.setSpeed(255); //Define maximum velocity
      motor1.run(FORWARD); //rotate the motor clockwise
      motor2.setSpeed(255); //Define maximum velocity
      motor2.run(FORWARD); //rotate the motor clockwise
      motor3.setSpeed(255); //Define maximum velocity
      motor3.run(BACKWARD); //rotate the motor anti-clockwise
      motor4.setSpeed(255); //Define maximum velocity
      motor4.run(BACKWARD); //rotate the motor anti-clockwise
    }

    void Stop()
    {
      motor1.setSpeed(0); //Define minimum velocity
      motor1.run(RELEASE); //stop the motor when release the button
      motor2.setSpeed(0); //Define minimum velocity
      motor2.run(RELEASE); //rotate the motor clockwise
      motor3.setSpeed(0); //Define minimum velocity
      motor3.run(RELEASE); //stop the motor when release the button
      motor4.setSpeed(0); //Define minimum velocity
      motor4.run(RELEASE); //stop the motor when release the button
    }

title: Why my 4WD Bluetooth car run so slow

Answers: 1

body:
I can't find issue in your code that I'm convinced is your problem. Without seeing your datasheet for the motor, I would bet your issue is one of two things:

1) A 9V battery is low-current relative to most batteries I've used for powering any decent DC motors. Do you have access to a better current source you could try?

2) Every motor has a trade-off in torque vs max-speed, dictated by the internal gear-ratio. Depending on the motor type, it may not have the torque to accelerate the vehicle to a significant speed.


body:
For a project I'm doing I've used an ESP8266/12e, a RTC Module DS3231 and a DFplayerMini

Basically it's a caller for birds and it has to play a 12-minute long MP3. The MP3 file should be played for 2 hours at the sunrise and 2 hours before the sunset, so each time it should be played 10 times (_10 × 12 = 120 minutes (2 hours)_)

The code I wrote so far (some parts are omitted for brevity):

    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"
    #include <Wire.h>
    #include <RtcDS3231.h>

    #define DELAY_ONPLAY 1000
    #define DELAY_ONPAUSE 20000

    // RTC Library (I2C)
    RtcDS3231<TwoWire> rtcObject(Wire);

    // MP3 Serial communication
    SoftwareSerial mySoftwareSerial(14, 12);
    DFRobotDFPlayerMini myDFPlayer;

    // Variables
    int volume, mth, day, h, m;

    // State of the playback
    int playbackCount = 0;
    bool isPlaying = false;

    RtcDateTime currentTime;

    void setup() {

        mySoftwareSerial.begin(9600);
        // Start serial connection
        Serial.begin(115200);
        // Start I2C
        rtcObject.Begin();

        if (!myDFPlayer.begin(mySoftwareSerial)) {
          while(true){
            delay(10);
          }
        }

        /* Get the value of potentiometer in the range of [3..30] and
         * set the volume
         */
        setVolume();

    }

    void loop() {

        setVolume();
        currentTime = rtcObject.GetDateTime();    //get the time from the RTC

        mth  = currentTime.Month();
        day  = currentTime.Day();
        h    = currentTime.Hour();
        m    = currentTime.Minute();

        /* The caller is not playing: check if date and time should
         * start the playback
         */
        if (isPlaying == false) {

            if (startSunrise() || startSunset()) {
                isPlaying = true;
            }

            else {
                // Nothing to do for the next 20 seconds
                delay(DELAY_ONPAUSE);
            }
        }

        else {

          // Currently playing
          if (playbackCount < 10) {

              if (/* MP3mini_is_idle */) {

                myDFPlayer.play(1);
                playbackCount = playbackCount + 1;

              }
          }

          else {
            playbackCount = 0;
            isPlaying = false;
            Serial.print("End of playback");
          }

          delay(DELAY_ONPLAY);

        }
    }

    void setVolume() {

        // Get the value of potentiometer in the range of [3..30]
        volume = map(analogRead(A0), 0, 1023, 2, 30);
        volume = constrain(volume, 3, 30);
        // Set the player volume
        myDFPlayer.volume(volume);
        Serial.println(String(volume));

    }

    bool startSunrise() {

        /* at the sunrise the call has to be played for 2 hours */

        if (mth == 2) {
            if ((day == 20 && h == 7 && m == 8) ||
                (day == 21 && h == 7 && m == 6) ||
                ...
                (day == 28 && h == 6 && m == 54) ||
                (day == 29 && h == 6 && m == 52)) { return true; }
        }

        if (mth == 3) {
            if ((day == 1  && h == 6 && m >= 49) ||
                (day == 2  && h == 6 && m >= 47) ||
                (day == 3  && h == 6 && m >= 45 ) ||
                (day == 4  && h == 6 && m >= 43) ||
                ...
                (day == 27 && h == 6 && m >= 0) ||
                (day == 28 && h == 5 && m >= 58)) { return true; }
        }

        return false;
    }

    bool startSunset() {

        /* 2 hours before sunset the call has to be played for 2 hours */

        if (mth == 2) {
            if ((day == 20 && h == 15 && m >= 41) ||
                (day == 21 && h == 15 && m >= 42) ||
                ...
                (day == 28 && h == 15 && m >= 52) ||
                (day == 29 && h == 15 && m >= 54)) { return true; }
        }

        if (mth == 3) {
            if ((day == 1  && h == 15 && m >= 56) ||
                (day == 2  && h == 15 && m >= 58) ||
                (day == 3  && h == 15 && m >= 59) ||
                (day == 4  && h == 16 && m >= 1) ||
                ...
                (day == 27 && h == 16 && m >= 31) ||
                (day == 28 && h == 16 && m >= 33)) { return true; }
        }

        return false;
    }

The part I'm stuck on is

      if (playbackCount < 10) {

          if (/* MP3mini_is_idle */) {

            myDFPlayer.play(1);
            playbackCount = playbackCount + 1;

          }

      }

How do I detect in the `if` condition if the MP3 is actually playing before play it again?
I think a 12-minute `delay()` is not the right approach.

In the image below the DFPlayerMini pinout: I noticed It has a `BUSY` pin  but I haven't found examples so far that uses this pin to detect the playback state.

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

Thanks for any suggestion.

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

title: Detect the end of playback of a MP3 file with DFPlayerMini / DFRobotDFPlayerMini.h library

Answers: 2

body:
As @chrisl alread said, you could use the busy pin. Or a simple serial query

    myDFPlayer.readState();

If the result is something like `DFPlayerPlayFinishe` the actual track is complete.

body: The busy pin, means that the flash memory is being accessed. So its not the same as "track being played".


body:
this is my first post here.
For some time I have been struggling with a problem and would like to know if anyone has a solution to share.

I am building a 4 tone sequencer, where I use 4 potentiometers to change the pitch of each tone beat. I want to add more beats to the sequencer so I would like to have an elegant solution instead of keep adding potentiometers.
 My idea was to use 1 potentiometer to control the pitch and use multiple push buttons with the single potentiometer for this process.
 All in all it goes like this:
 - When switch1=HIGH, pitch1=analogRead(A0);
 - When switch2=HIGH, pitch2=analogRead(A0);
 The problem is that when I change pitch1 and pitch2 the end up getting the same values as soon as I press their switch. My code looks like this:

       if(switch1state==HIGH)
      {
        Tone1Pot=analogRead(A0); // 0 – 1023
        pitch1=Tone1Pot/13;
      }

    tone(speakerPin, notes[pitch1], 200);

    Serial.print(pitch1);
    Serial.print("     ");
    delay(tempo);

    if(switch2state==HIGH)
      {
        Tone2Pot=analogRead(A0); // 0 – 1023
        pitch2=Tone2Pot/13;
      }

    tone(speakerPin, notes[pitch2], 200);

    Serial.print(pitch2);
    Serial.print("     ");
    delay(tempo);

I would really like to store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again.

EDIT:

Let me try to explain the issue better:
I have 2 push buttons and 1 potentiometer, all of them are inputs. The code I am aiming for is to do the following: 1 - While pressing push button1 I want to read the value of potentiometer and store it to a variable1. When the button1 is not pressed I want to keep that variable stored. 2 - While pressing push button2 I want to read the value of potentiometer and store it to a variable2. When the button2 is not pressed I want to keep that variable stored.
I have successfully achieved this, however the problem comes when I press button1 again to adjust variable1, variable2 is also getting adjusted in the process, even when I am not pressing button2
Chris - The push buttons are correct since I can change the states of the digital pins when I press them ( and I measure the 5V when pressed). I do not need the buttons to be pressed at the same time. What I need is the buttons to trigger the event of storing potentiometer data only when either one of them is pressed accordingly.
jsotola - Sorry for the bad explanation. I hope this one is better.
Code:

    #include "pitches.h"

    int notes[]={

    NOTE_B1,
    NOTE_C2,
    NOTE_CS2,
    NOTE_D2,
    NOTE_DS2,
    NOTE_E2,
    NOTE_F2,
    NOTE_FS2,
    NOTE_G2,
    NOTE_GS2,
    NOTE_A2,
    NOTE_AS2,
    NOTE_B2,
    NOTE_C3,
    NOTE_CS3,
    NOTE_D3,
    NOTE_DS3,
    NOTE_E3,
    NOTE_F3,
    NOTE_FS3,
    NOTE_G3,
    NOTE_GS3,
    NOTE_A3,
    NOTE_AS3,
    NOTE_B3,
    NOTE_C4,
    NOTE_CS4,
    NOTE_D4,
    NOTE_DS4,
    NOTE_E4,
    NOTE_F4,
    NOTE_FS4,
    NOTE_G4,
    NOTE_GS4,
    NOTE_A4,
    NOTE_AS4,
    NOTE_B4,
    NOTE_C5,
    NOTE_CS5,
    NOTE_D5,
    NOTE_DS5,
    NOTE_E5,
    NOTE_F5,
    NOTE_FS5,
    NOTE_G5,
    NOTE_GS5,
    NOTE_A5,
    NOTE_AS5,
    NOTE_B5,
    NOTE_C6,
    NOTE_CS6,
    NOTE_D6,
    NOTE_DS6,
    NOTE_E6,
    NOTE_F6,
    NOTE_FS6,
    NOTE_G6,
    NOTE_GS6,
    NOTE_A6,
    NOTE_AS6,
    NOTE_B6,
    NOTE_C7,
    NOTE_CS7,
    NOTE_D7,
    NOTE_DS7,
    NOTE_E7,
    NOTE_F7,
    NOTE_FS7,
    NOTE_G7,
    NOTE_GS7,
    NOTE_A7,
    NOTE_AS7,
    NOTE_B7,
    NOTE_C8,
    NOTE_CS8,
    NOTE_D8,
    NOTE_DS8
    };

    int Tone = 0;
    int speakerPin = 3;

    int switch1=6;
    int switch2=7;
    int switch3=8;
    int switch4=9;
    int switch5=10;
    int switch6=11;
    int switch7=12;
    int switch8=13;

    void setup() {

    Serial.begin(9600);

    pinMode(switch1, INPUT);
    pinMode(switch2, INPUT);
    pinMode(switch3, INPUT);
    pinMode(switch4, INPUT);
    pinMode(switch5, INPUT);
    pinMode(switch6, INPUT);
    pinMode(switch7, INPUT);
    pinMode(switch8, INPUT);

    }

    void loop() {

     // get potentiometers inputs
    //int TonePot = analogRead(A0); // 0 – 1023
    //int DurationPot = analogRead(A1); // 0 – 1023
    int TempoPot = analogRead(A2); // 0 – 1023

    int Tone1Pot;
    int Tone2Pot;
    int Tone3Pot;
    int Tone4Pot;
    int Tone5Pot;
    int Tone6Pot;
    int Tone7Pot;
    int Tone8Pot;

    int Duration1Pot;
    int Duration2Pot;
    int Duration3Pot;
    int Duration4Pot;
    int Duration5Pot;
    int Duration6Pot;
    int Duration7Pot;
    int Duration8Pot;

    // calculate corresponding, divide by 13 as we have 77 pitches. 1023/77 ~ 13
    int pitch1;
    int pitch2;
    int pitch3;
    int pitch4;
    int pitch5;
    int pitch6;
    int pitch7;
    int pitch8;

    int pitch1stored;
    int pitch2stored;

    int noteduration1 = Duration1Pot/8;
    int noteduration2 = Duration2Pot/8;
    int noteduration3 = Duration3Pot/8;
    int noteduration4 = Duration4Pot/8;
    int noteduration5 = Duration5Pot/8;
    int noteduration6 = Duration6Pot/8;
    int noteduration7 = Duration7Pot/8;
    int noteduration8 = Duration8Pot/8;

    int tempo = TempoPot;

    //Get state of switches if HIGH or LOW
    int switch1state=digitalRead(switch1);
    int switch2state=digitalRead(switch2);
    int switch3state=digitalRead(switch3);
    int switch4state=digitalRead(switch4);
    int switch5state=digitalRead(switch5);
    int switch6state=digitalRead(switch6);
    int switch7state=digitalRead(switch7);
    int switch8state=digitalRead(switch8);

    ////////////////////////////////////////Sound generation code /////////////////////////////////

    if(switch1state==HIGH)
      {
        Tone1Pot=analogRead(A0); // 0 – 1023
        pitch1=Tone1Pot/13;
      }

    tone(speakerPin, notes[pitch1], 200);

    //tone(speakerPin, 0, 200);}// make the tone mute

    Serial.print("pitch1= ");
    Serial.print(pitch1);
    Serial.print("     ");
    delay(tempo);

    if(switch2state==HIGH)
      {
        Tone2Pot=analogRead(A0); // 0 – 1023
        pitch2=Tone2Pot/13;
      }

    tone(speakerPin, notes[pitch2], 200);

    Serial.print("pitch2= ");
    Serial.print(pitch2);
    Serial.print("     ");
    delay(tempo);

    if(switch3state==HIGH)
      {
        Tone3Pot=analogRead(A0); // 0 – 1023
        pitch3=Tone3Pot/13;
      }

    tone(speakerPin, notes[pitch3], 200);

    Serial.print("pitch3= ");
    Serial.print(pitch3);
    Serial.print("     ");
    delay(tempo);
    }

title: Substitute multiple potentiometers for push buttons and single potentiometers

Answers: 2

body:
So based on the information you provided I understand that the issue is that both the `if(switch1state==HIGH)` and the `if(switch2state==HIGH)' statements evaluate to true if either switch is flipped. That means one of the following things is happening:

1) Somewhere in your code you're mixing their values and assigning ones value to the other

2) Your configuration of the digitalRead pins is wrong (either wrong pins or wrong pupdr config as I've seen incorrect pull-up and pull-down resistors propagate unexpected behavior across the ground)

3) your wires are crossed. If you're using a breadboard make sure you know how it's connected internally. Some swap between horizontal and vertical rows.

body:
I cannot see, how your code would show the described behavior (assuming that, you have connected the buttons correctly with a pulldown resistor). But your code can be greatly simplified, which would make it less error prone.

You have 8 buttons, which screams for the usage of arrays (IMO you should always use arrays, if you have more than 2 or 3 equal buttons). First put the button pins into an array:

    #define N_BUTTONS 8
    int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13};

Then define an array to hold the measured pitches (here initialized with 0):

    int pitches[N_BUTTONS] = {0};

In your `setup()` function you can loop over the `button_pins` array to set them as input:

    for(int pin : button_pins) pinMode(pin, INPUT);

In the `loop()` function you again loop over the button pins, but this time you check, if the current button is pressed. If yes, you measure the analog voltage, calculate the pitch and save it into the corresponding element of the `pitches` array:

    for(int button=0;button < N_BUTTONS;button++){
        if(digitalRead(button_pins[button])){
            pitches[button] = analogRead(A0)/13;
        }
    }

This always works for multiple pressed buttons at once.

Also you should avoid calls to `delay()` in your `loop()` function. That is just time, that the Arduino cannot do anything, including checking your buttons. If you want to do something timed, you should use a non-blocking coding style, like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Basically it uses the `millis()` function as a clock, checking regularily, if the needed time has passed and only doing something if it had passed; letting other code execute, if not. There are tons of tutorials about this on the web.

As you have seen above, I didn't include the `tone()` function in my answer. That is because you should decouple your input and output code. The code above is the input code. It saves the wanted pitches into the corresponding array. Then, after that code, you can write all the code you need for outputting the pitches as tones (however you actually want to output them). The only real logical connection between these 2 parts of code is the `pitches` array. That makes it easier to have more and different inputs (for example if you wanted to have a reset button, which sets all the pitches at onece to a predefined value). Also the function of the input code (which needs to very regularily check the buttons, to be responsive) is not disturbed by the output code.