text:
Arduino AT Cmd Not Working
We are Using I-CUBE-LRWA Lora Module AT Cmd with Arduino ProMini
Set of commands set with DockLight working Perfectly but with Arduino, we are getting some coded response and well every time RXTimeout response.
Docklight Response

Arduino Response :

Arduino Code:
mySerial.flush();
lora.flush();
Serial.flush();
digitalWrite(lorapin, HIGH);
delay(500);
lora.listen();
lora.print(“AT\r\n”);
String dr = lora.readStringUntil("\r\n");
delay(10);
Serial.print(“AT:” + dr);
Serial.println();

                lora.print("ATZ\r\n");
                String ATZ = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("ATZ:"+ATZ);
                Serial.println();

                lora.print("AT+NJM=0\r\n");
                String NJM = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+NJM:" + NJM);
                Serial.println();

                lora.print("AT+DADDR=as:23:00:00\r\n");
                String DADDR = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+DADDR:" + DADDR);
                Serial.println();

                lora.print("AT+APPSKEY=90:22:53:85:44:7A:22:32:75:35:26:35:63:30:A9:56\r\n");
                String APPSKEY = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+APPSKEY:"+APPSKEY);
                Serial.println();

                lora.print("AT+DEUI=5bb1605000032as\r\n");
               String DEUI = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+DEUI:" + DEUI);
                Serial.println();
                lora.print("AT+NWKSKEY=23:43:67:9A:22:44:22:69:50:67:3A:A3:34:27:26:72\r\n");
                String NWKSKEY = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+NWKSKEY:" + NWKSKEY);
                Serial.println();

                lora.println("AT+CFM=1\r\n");
                String CFM = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("AT+CFM:" + CFM);
                Serial.println();

                lora.println("AT+ADR=1\r\n");
                String ADR = lora.readStringUntil("\r\n");
                delay(10);
                Serial.println();
                Serial.print("AT+ADR:" + ADR);
                Serial.println();

                lora.print("AT+CLASS=C\r\n");
                String CLASS = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("CLASS:" + CLASS);
                Serial.println();

                lora.print("AT+JOIN\r\n");
                String JOIN = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("JOIN:" + JOIN);
                Serial.println();
                delay(500);

                lora.print("AT+NJS=?\r\n");
                String NJS = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("NJS:" + NJS);
                Serial.println();
                delay(500);

                String sendatavar="AT+SEND=2:30";
                Serial.print(sendatavar);
                Serial.println();
                lora.print(sendatavar);
                delay(10000);
                String sedndr = lora.readStringUntil("rxDone\r\n");
                delay(1000);
                Serial.print("AT+send:" + sedndr);

So how exactly did you connect the hardware? Can you show a photo? Also is this running on an Arduino Nano or Pro Mini? You have added both question tags. What voltage is the Pro Mini running on?

What Baud rate you used in the Arduino code?

@Fahad Baud Rate 9600

@MaximilianGerhardt i'm using 5v pro mini

Can you show a wireup or schematic?

The COM Output image you posted, the baud rate is showing 57600. Maybe that's why you are seeing garbage output?


text:
i want to make Node Mcu a bride for other devices but its self connected with home wifi not providing internet to others
i there!
i have Node Mcu which i want to connected with my home wifi
after it it made it own station mode then i want to make it access point for other
but now problem is that it is now in both mode mean (AP+Station ).
when i want to connect any other phone or Pc  it connected successfully
but not providing internet to other devices.
Question?

is problem in wifi configuration of acess point?
which ip,gate way and subnet mask i would assign to the access point?

I don't understand, how you have configured the Node MCU. Please provide a minimal working sketch, that shows your problem. Gateway and subnet mask have to match the corresponding values of your network, that you connect to. If the gateway isn't correctly set, you won't have internet connection, since the routing won't work

the NodeMcu is not a router. there are attempts to make a router application for esp8266, but not with Arduino

The NodeMCU under the Arduino framework cannot do what you want.  There are basically three methods for what you want:

Configure the IP stack to enable routing - not possible in Arduino, and also requires configuration of your upstream router to work.
Configure the IP stack to enable routing and Network Address Translation - not possible in Arduino, and I am not sure if the stack even supports NAT.
Write a sketch to act as a proxy server - only works for certain types of traffic (HTTP) and requires a lot of coding. May be possible, but not an easy task.

1) and 2) certainly can't be don in Arduino. There are rumours on the internet that it is possible to configure and compile your own lwIP stack version with routing enabled, but that is so far outside the scope of this website.
Option 3 is the more realistic, but certainly not something even I would consider doing. Creating a sketch that works like squid, for example, would be a mammoth task, and may even hit the limitations of the ESP8266.
It would be more beneficial to perhaps get an old wireless router that is supported by OpenWRT and learn how to hack that to act as you want.

source: Stack Exchange

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

sort: votes


text:
AutoConnect module does not broadcast SSID on ESP32 Dev Board
This is my first post so I apologize if I'm missing all required info about my Arduino setup.  I'm a little new to this type of development.
Arduino 1.8.9
ESP32 Dev Module on /dev/cu.SLAB_USBtoUART
Mac OSX High Sierra 10.13.
I'm using the AutoConnect by Hieromon Ikasama v1.1.3 library to create an access point (AP), but the SSID (network name) is not being broadcasted even with the simplest code example.
Why isn't "ESP-78e9" showing up in my network list on my MAC or iPhone?
⸮⸮⸮8Y8⸮
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[E][Preferences.cpp:38] begin(): nvs_open failed: NOT_FOUND
[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.192, MASK: 255.255.255.0, GW: 192.168.1.1
WiFi connected: 192.168.1.192 on ESP-78e9

Full code sample below, written with the Arduino IDE
#include <WiFi.h>
#include <WebServer.h>
#include <AutoConnect.h>

WebServer         Server;
AutoConnect       Portal(Server);
AutoConnectConfig Config;

void rootPage() {
  char content[] = "Hello, world";
  Server.send(200, "text/plain", content);
}

void setup() {

  Config.apid = "ESP-" + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX);
  Config.psk = "Password1";
  Portal.config(Config);

  delay(5000);
  Serial.begin(9600);
  Serial.println();

  Server.on("/", rootPage);
  if (Portal.begin()) {
    // Serial.println("WiFi connected: " + WiFi.localIP().toString());
    Serial.println("WiFi connected: " + WiFi.localIP().toString() + " on " + Config.apid);
  }
}

void loop() {
    Portal.handleClient();
}

I've tried looking into why "nvs_open failed: NOT_FOUND" is occurring as that feels like the next step, but can't find any information on how to fix it.
I've also tried this on two boards of the same model.
Any ideas?
** Update **
I've modified the code to include the following, but still no AP and captive portal.
https://hieromon.github.io/AutoConnect/advancedusage.html#on-demand-start-the-captive-portal
According to the link above, that SHOULD start a captive portal before attempting to connect to WiFi.
  Config.autoRise = false;
  Config.immediateStart = true;

Instead I get the debug text here:
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START

Update 2
There may be a bug in the documentation.  I changed "autoRise" to true and the SSID was broadcasted.
  Config.autoRise = true;
  Config.immediateStart = true;

It looks like your ESP32 is already successfully connecting to an access point as a STA (station) and does not start its own Access Point (AP). You probably have already previously configured an SSID and password and the ESP32 is successfully reusing those, so it will not start the Captive Portal (as its own AP).
You should force AutoConnect to start up the Captive Portal or to forget its pre-programmed SSID and password. This can be achieved by On-demand starting of the Captive Portal like described on this page. According to the documentation you should put the following lines in your code (I have not tested this myself):
Config.autoRise = true;
Config.immediateStart = true;
Portal.config(Config);
....
Portal.begin();

NOTE: The documentation actually states Config.autoRise = false but it seems this does not have the desired effect.

Thanks @StarCat .  You'd think that would work according to the docs, but it doesn't.  AP_STOP and then STA_START occurs :/  See update in my post.

You might try to disable your regular Wifi temporarily and see if the portal comes up when the ESP cannot get a Wifi connection itself. What if you connect your browser to the IP address it shows in the serial output?

Thanks for the tips.  Looks like the autoRise = false is a bug and it should be autoRise = true.  I'll mark yours as accepted, but that may fool people in the future.

Thank you. I'll change it in my answer, but this comes from the documentation on the author's website.

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


text:
esp8266 ip address issues
I have android studio app and arduino codes they are connected to each other using esp8266
but it works only on one network when I use another network it doesn't recognise it's ip address instead it gives 0.0.0.0

Only this worked

 #include <LCD5110_Graph.h>
    #include <Adafruit_MLX90614.h>

    #define DEVICE_ID "Monitor1"

    #define DEBUG true
    #define REQ_CODE_ACK 1
    #define REQ_CODE_VALUES 2

    //84w * 48h
    LCD5110 myGLCD(8,9,10,12,11);
    extern uint8_t SmallFont[];   //8h * 6w font

    Adafruit_MLX90614 mlx = Adafruit_MLX90614();
    int pinLM35 = A0;         //Pin A0 is for LM35
    int fsrAnalogPin = A2;    //Pin A2 is for force sensor
    int blinkPin = 13;        // Pin 13 is the on-board LED

  String mSSID = "LibyaADSL-9a86";    //initial ssid and password
  String mPASS = "BYRTPCRJAHPWQ";

    //http request code
    int service_code;

    //wifi listen variables
    String wifiBuf = "";
    char character;
    int connectionId = 0 ;

    //sensor values
    float sensor_mlx, sensor_heart, sensor_lm35;
    int sensor_force;

    void setup() {
      //init LCD
      myGLCD.InitLCD();
      myGLCD.setFont(SmallFont);
      randomSeed(analogRead(7));

      //init MLX90614
      mlx.begin();

      //init serial
      Serial.begin(115200);           //Arduino-PC
      Serial3.begin(115200);          //Arduino-ESP8266\

      //init esp8266
      init8266();

      pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!

      delay(200);
    }

    //init esp8266
    void init8266()
    {
        Serial.println("Init ESP...");
        String stationConCmd = make8266InitCommand();

        sendCommand("AT+RST\r\n",2000,DEBUG);       // reset module
        sendCommand("AT+CWMODE=1\r\n",1000,DEBUG);  // configure as access point
       // sendCommand("AT+CWDHCP=1,1\r\n",1000,DEBUG);
       // sendCommand("AT+CIPSTA=192.168.0.101,192.168.0.1,255,255,255,0\r\n",1000,DEBUG);    // HI اني ضفته
        sendCommand(stationConCmd, 1000, DEBUG);

        delay(1000);
        sendCommand("AT+CIFSR\r\n",1000,DEBUG);     // get ip address
    ///
        sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG);  // configure for multiple connections
        sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
    }

    //Make command string for connect to AP
    String make8266InitCommand()
    {
        String cmd = "AT+CWJAP=\"" ;
        cmd += mSSID;
        cmd += "\",\"";
        cmd += mPASS;
        cmd += "\"";
        cmd += ",11,0\r\n";

        return cmd;
    }

i still can't figure it out
Hope someone can help
Thank you

you send AT+RST immediately after AT+CWJAP. it doesn't have time to connect to the new WiFi. with a remembered network it worked, because it connect to the network automatically

@Juraj how much delay i need to put ?

@jsotola post updated, please check

the logic of your sketch is wrong. you throw a bunch of random commands at the AT firmware. it is unclear from your question if you use or want to use the remembered connection or you did turn off autoconnect and want to connect every time etc...

this is written from a perspective of a library but is valid for raw AT Commands too: https://github.com/jandrassy/WiFiEspAT#persistent-wifi-connection

@Juraj i updated the question with a new image showing the error, please check

what is ,11,0 in CWJAP? remove it

If you configure the esp as an access point then it should also be the DHCP server and be supplying ip addresses to it's clients.  Only if you configure it to be a client station itself (eg. connect to your router as client) will it be assigned an ip address.

what question do you answer here?

i updated the question with a new image showing the error, please check

The comment on CWJAP line said it was to configure as access point which made think there was some confusion with wifi network concepts.  However, the error you show occurs right after you try to connect to your ADSL wifi so there is something not right with that network name or password.  Or maybe your wifi AP is doing mac address filtering.


text:
I think i worn out all of my Arduino Uno memory
Hi my Arduino Uno stacked with a motor driver shield was working perfectly however I am using the same board for a while now and suddenly my board stopped working.
When I upload a code no matter what code is the LED's on the board respond however the code is not executed it does nothing , the board doesn t even beep anymore.
Is there a way to clean the memory or something?
Please help.

To check if you really cannot upload anymore (assuming it's not a software error), try the following sketch
https://www.arduino.cc/en/tutorial/blink
This will blink the BUILTIN led.
There is very low chance to wore out your memory, you can write lots of times to it (like 10,000 times guaranteed, in practice mostly more).
But there can be another hardware problem, but first check if this simple sketch works.
Also (based on jsotola's comment), remove shields/wires.
Especially wires/shields using RX/TX since these pins are (somehow) used for loading a sketch.

@jsotola good point, I will edit my answer

Yes thank all codes that i tried work with just the Arduino Uno however when I stack the motor driver shield l239D i cant upload any code it says that an error has ocurred while uploading the sketch.

That's probably because the shield uses some GPIO pins, especially RX/TX... So that means every time you want to upload a new sketch you have to remove the shield.

Hmm thank you are you saiyng that if i upload a code to Control motors just to the Arduino board without the driver shield atached and the i connect the driver shield it Will work?

Michel keijzers thank you so much man really it worked  just fine!!! Thank you realy you do made Diference.

@Noslen Yes I'm afraid you have to do that … if it is the most helpful answer, please accept it (click on the arrow up next to the answer). Or wait a few days to see if someone else has a better answer. (and accept the one that's best at that time).


text:
POST image from Arduino Uno
I need to post an image to a website. Iam able to capture the image using OV7670 camera module. But don't know how to store and post the image to a website. I didn't get any idea to start this. Can anyone help me to do this.
I got the image capturing code and circuit from
 https://circuitdigest.com/microcontroller-projects/how-to-use-ov7670-camera-module-with-arduino
I have got the below components:
Arduino uno,
ESP 01 module,
OV7670

start by researching the different ways that pictures can be POSTed to a web server from a PC

@jsotola I cannot even post any data from arduino to a webpage using wifi module. Can you please give any idea to post any string data to webpage and the response back.


text:
How do i send data from a Master to another Master?
I am using an ESP32 to receive data from web.
However in an I2C communication, the EPS32 does not work as a Slave and i already have an Atmega as the Master.
i have seen sites saying Master-Master I2C Connection is possible however, how do i do this? or are there other solutions to have the ESP32 communicate to the ATMega?

I don't have much experience with I2C, but there are other ways, like UART, or SPI.

Both your master devices must support Multimaster mode, i.e. Arbitration and Synchronization. See I2C Spec here for a description of the arbitration process.
It's up to you to handle a lost arbitration in your software.

or are there other solutions to have the ESP32 communicate to the
  ATMega?

Of course. As you considered I2C to be sufficient, UART and SPI are feasible alternatives supported by almost all microcontrollers.

what do you recommend i do here?
use multiple communication styles? I2C and SPI?since all i need is to have 2 master device communicate, while only the other master communicate with the slaves.

@JuliusNoelBanayo Depends on your requirements. If you only have to transmit some bytes every 100ms, I2C may be the most economic solution (Multimaster mode is supported by ESL32 and Atmega). If there's much more data and/or you need it fast, you should consider SPI.


text:
Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom?
Hi I'm a newbie and working on a project with Arduino Due(Atmel3X8E).I want to try and save the important variables to the eeprom during a power outage,using the brown out detector.Is it possible to do this?
Thank you.

What is your power source?

We plan on using the ac mains 220v 50hz stepped down to 12v.

Okay, that is good - see my answer for the details

Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.
The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

When external power goes off, you well get enough time and power to store your bytes safely.
How it works
When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER_GOOD signal is LOW.
When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER_GOOD signal goes to HIGH level and your program may start save data to EEPROM.
Why the optocoupler?
We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.

I have the same circuit but without the U1 for a "solar power" display. Just connecting the 5V to an interrupt pin. Your solution is more elegant (but why an optocoupler and not just a mosfet?), but it could be more simple.

@Adriano - updated my answer

I think you could still use a simple transistor instead of an opto-coupler as per Adriano's comment. Or even just put a resistor in series with the pin. You have a resistor there already!

Upvote for answering the question and schematics. I do share concerns about the optocoupler working voltage vs. actual supply levels, but it's a good solution that directly answers the question. FRAM and EERAM are also good, but that depends on use case.

An alternative solution to this is to use an "EERAM". This is an EEPROM with an SRAM buffer in front of it. A large capacitor is used to provide power while the contents of the SRAM are stored in the EEPROM.
It sounds complex, but it's simple since they are made as a dedicated chip. One good example is the 47C16 from Microchip. The EEPROM backup is completely transparent to the user, and you can use it just like an I2C connected SRAM chip (so no worries about wearing out the EEPROM by writing too often).
It's a chip I love so much that I made a breakout of the 3.3V version 47L16 (since I work mainly with 3.3V devices), and a library to support it.

+1 I forgot about these myself. It's an excellent suggestion and also something I have been wanting to use. The one downside is still if you are writing to it when the power goes down; then there's still the chance that you get corrupted data. There are also FRAM chips available that require no backup and have effectively unlimited endurance too. Adafruit sells a few of them.

I think the gbg's circuit will fail in many situations. It will cause interrupt only when the power source voltage is quite low. If there is no considerable load before the diode filtering caps of the power source will likely hold enough charge and the "5V" will be falling slowly. Arduino will drain the the backup capacitor before it gets "power bad" interrupt.
Since OP is using 12V power supply a simple brownout detector giving warning when this source drops under some reasonable value (i.e. 9V) is the best way. A Zener diode and transistor (or the optocoupler) should be enough because the value of the threshold is not critical.

I suggest to add an example circuit.

But we can directly connect the optocoupler to the AC mains (with corresponding resistor and diode, of course). And change firmware to detect pulses of 50/60Hz instead of HIGH level

Connection to mains makes the circuit more dangerous. OP is a newbie after all.

I use FRAM for this. It's always write a byte if it was received, much faster and safety. Additionally you can use chain like approach to save data blocks in EEPROM for controlling of the data integrity. Try to use mosfet instead of diode and optocoupler when it powered from battery.


text:
Is it possible to measure analog output?
I'm using PWM to control LED brightness using MOSFET, using analogWrite(pwmPin,val), while val is a 12 bit bit value.
pwmPin is defined as- pinMode(pwmPin, OUTPUT);
Since val changes in time due to external lightning, I wish to measure PWM value, for later use in code. Using analogRead(pwnPin) yielded a changing value ranges 7-14.
Is there a way to measure PWM value defined as an output ?
EDIT 1:
Saving val's value won't save the problem I'm looking for, since code reaches a deepSeleep phase, which val can be stored, but I want an actual incidication of its value, and if it actually on.

Why not storing val and calculate what you need depending on that? That seems better than measuring something you already know (or knew) as it is/was in the variable val.

@MichelKeijzers - see EDIT1 in my Q

@Guy.D "I want an actual indication of its value" When you are measuring the output, you are actually only writing code to test your code. In most cases this does not really make sense. If your code is written correctly, you can trust the output to do, what you want. Any event, that might change that (like some kind of hardware failure), is high likely to also effect your testing code, which you then also cannot trust. Why do you really need this indication? If for safety, then you should think about the scenarios, that you want to cover, and then build a seperate device for this purpose.

The fact that you sleep doesn't matter. If you keep in a variable the value that you used to analogWrite(), it will still be there when you wake up.

Doesn't analogRead from analog pins but analogWrite write to digital pins? And don't the analog and digital pins have their own numbers (digital 0 is a different pin to analog 0)?

Sorry but I don’t follow....

you could use an rc filter to sample the average voltage.

First: Why would you need to measure the PWM value. You already know it; it's saved in the val variable. Why not just use this variable for later use in code?
Second: Doing the analogRead on the same pin as the PWM output is not going to work. Internally there are 2 different hardware peripherals, that are responsible for these functions: The ADC is responsible for measuring analog voltages, while one of the Timers is responsible for generating the PWM output. Only one of them can connect to the pin at any time. Thus you are not measuring the PWM signal, when you do an analogRead(pwmPin). This function set's the pin for measuring analog voltages (means it connect it to the ADC and configures the ADC) and thus disconnects the Timer hardware.
Third: Doing an analogRead() directly on a PWM signal is not going to work. PWM is still a digital signal, so measuring it's analog voltage would yield only values around 0 and 1023. This signal is transformed to a real analog voltage through a low pass filter, either electrically or mechanically (here I mean because mechanical elements often cannot follow the relatively fast PWM signal - like a motor or a speaker - which results effectively in a low pass filter).
How to measure a PWM signal then? First you definitely need to use a different pin, than the PWM output pin. Then you have 2 ways of measuring the current PWM value:

You can connect the PWM output to a low pass filter (combination of resistor and capacitor; you can google this and get very detailed descriptions), and the output of the low pass filter to an analog input pin of the Arduino. Then you can do analogRead()s to measure the current value.
You can measure the PWM signal directly, meaning measuring the actual pulse width of the signal. There are multiple ways of doing this, one being the pulseIn() function, which wait's for a pulse to complete and returns the length of the pulse.


text:
Please help me read this Schematic Diagram
So, i'm trying to build an Obstacle Avoiding Robot by refering this site "Robot Obstacle Avoiding Car
On the website they have provided with very poor Circuit Diagram.
Please help me read the positions of capacitors.
I have completed connection of all other components.

Help would be appreciated

FYI that 9V depicted is not suitable for driving motors, those 9V bricks are made to power a low drain device for a long time.

Then, should i use two of them in series?

you are wrong, that is a very good schematic diagram ... the only very poor thing i see is the three wiring diagrams that you presented

You need a more capable battery. Those bricks are really only capable of low-current (and/or very short lifetimes). Consider another source, supplied separately to the Arduino and to the motors. And FYI, to increase the current capability of a source, you'd need to put them in parallel, not in series.

They are not poorly described.
All capacitors need to be put from the VCC to GND directly (this will not cause a shortcut).
The left 3 are related to the motor; as it uses a lot of current, it can take the current from the capacitors instead of flowing all the way to the power supply, causing problems of a voltage reduction that can cause other components to fail (temporarily).
The middle two are for the ultrasonic sensor as it also uses some current.
0.1 uF capacitors (the one for the ultrasonic sensor) is typically used for ICs and are called bypass capacitors. These needs to be placed as close as the VCC of the IC (in this case ultrasonic as possible).
And the right two for the power supply itself to remove noise/ripple.
For all capacitors, place them close to where the power is needed (for the motor/ultrasonic) and for the power supply close to the VCC input.
EDIT
Below I added the capacitors for the motor, sorry for using MS paint, having no better option right now. I assume the two red wires from the L293D other than going to the breadboard are the 9V lines (VDD).
Also don't put the capacitors in the same pin as the L293D IC pins, but I didn't want to obfuscate the picture. This might destroy your breadboard or IC pins as there is too less space for both.

Would you please elaborate. I'm new to designing circuit. I've uploaded the Circuit i build.

I edit the capacitors for the L293D, the other capacitors should be placed likewise (as close as the VCC as possible, going directly to GND).

Thanks a lot for showing where to place motor drive capacitors, one last time just check the cirtuit.

Personally I wouldn't put capacitors from the Arduino to the breadboard, but keep them on the breadboard (even if it's not so close to the Vin/VCC of the Arduino).  But if they are close together you could.
I also see a capacitor under the switch (and two from the Arduino), while only 2 in the schematics for the Arduino power.
And you miss one capacitor towards the sensor (the schematics show two, you  only placed one). You can place them  parallel. And in principle you should have 2 capacitors PER sensor.

Maybe it's a bit overdone with capacitors, but better a stable/reliable circuit than one that might fail in some circumstances.

I'm kinda confused. If you have an access to any computer, please fell free to edit the circuit and also simulate to check it's working.
[link]https://www.tinkercad.com/things/iqq6zaNE118-self-driving-robot/editel?sharecode=5ThdoqkBRCWekluTVaZD254A_KYWiiuXoKav8GekRyY=

I have added the capacitors double for Vin and Vcc 5V for the Arduino, maybe too much, but safe. I added/adapted the capacitors near the first sensor. The motor capacitors are ok. What I did not draw is the second and third sensor capacitors (copy them exactly like for the first sensor).


text:
VSCode Platformio Schedule.h: No such file or directory
I suppose this might be more an environment question regarding Platform.io and VSCode, as my code works great in the Arduino IDE, however the lack of syntax highlighting is driving me mad.
I've setup a Platform.io project in VSCode, copied my code across and setup my board (Wemos D1 Mini)
My platformio.ini file looks like:
[env:wemos_d1_mini32]
platform = espressif32
board = wemos_d1_mini32
framework = arduino

There are a couple of headers that are highlighted as having errors:
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

I've installed FirebaseESP8266 to my project from the PlatformIO libraries, however it still says:

include errors detected. Please update your includePath. Squiggles are disabled for this translation unit
  (C:\Users\Greg\Documents\PlatformIO\Projects\Lovebox\src\main.cpp).C/C++(1696)

If I try to build it errors with src\main.cpp:1:22: fatal error: Schedule.h: No such file or directory
As for the ESP8266WiFi library, it simply says cannot open source file "ESP8266WiFi.h"
Anyone know where I'm going wrong?

Did you install the libraries you need / use?
You could do it either via the platformio screen or add the names directly to the
platformio.ini
lib_deps =
    Firebase ESP8266 Client@>=2.7.8

And additionally ESP8266WiFi.h is an ESP8266 library
for the ESP32 you should use the lib #include <WiFi.h>
EDIT: To update the project libraries, select 'Update Project Libraries' from the project tasks.


text:
How can I power an ESP8266 using a 9V 1A barrel connector power supply?
I have a Huzzah Feather ESP8266 (pinout) and due to the requirements of my project, I need to supply it with a 9V power adapter with a barrel connector, such as this one.  I'm REALLY new to all of this, so I am trying to figure out how to do this and understand reading dev board specs.
It looks like this development board has a regulator that will adjust a power source down to the appropriate voltage...  but how do I know what parameters it allows?
If I'm understanding correctly, on the pinout sheet above it looks like I would connect a power supply to the "VBUS" and "GND" (right?) pins.  It also says "500mA Max", so does that mean a 1A power supply won't work?  Also, why wouldn't it specify a maximum voltage?
If just connecting a barrel connector to those pins will not work, what am I missing that would get me there?

Have you seen this forum thread?

just use a cheap buck dc-dc converter to feed it 3.3v or whatever

You cannot. If you look at the datasheet:
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-feather-huzzah-esp8266.pdf
you can read all details on page 25/26:

Alternative Power Options
The two primary ways for powering a feather are a 3.7/4.2V LiPo
  battery plugged into the JST portor a USB power cable.
If you need other ways to power the Feather, here's what we recommend:

For permanent installations, a 5V 1A USB wall adapter (https://adafru.it/duP) will let you plug in a USB cable for reliable
  power
For mobile use, where you don't want a LiPoly, use a USB battery pack! (https://adafru.it/e2q)
If you have a higher voltage power supply, use a 5V buck converter (https://adafru.it/DHs) and wire it to a USB cable's 5V and GND input
  (https://adafru.it/DHu)

Here's what you cannot do:

Do not use alkaline or NiMH batteries and connect to the battery port - this will destroy the LiPoly charger and there's no way to
  disable the charger
Do not use 7.4V RC batteries on the battery port - this will destroy the board

The Feather is not designed for external power supplies - this is a
  design decision to make the board compact and low cost. It is not
  recommended, but technically possible:

Connect an external 3.3V power supply to the 3V and GND pins. Not recommended, this may cause unexpected behavior and the EN pin will no
  longer. Also this doesn't provide power on BAT or USB and some
  Feathers/Wings use those pins for high current usages. You may end up
  damaging your Feather.
Connect an external 5V power supply to the USB and GND pins. Not recommended, this may cause unexpected behavior when plugging in the
  USB port because you will be back-powering the USB port, which could
  confuse or damage your computer.

If you read the docs on that Feather board, the barrel connector is meant for a LiPo battery.
It's a 3V unit, not meant for an external power supply, and 9V is too much for it. You would need to run your 9V supply through a buck converter (or a linear regulator) and drop it down to 5V, which you could feed into the USB connector. That does mean that when you want to connect it to USB to power it it will lose power, unless you also plug a LiPo battery into the barrel connector.


text:
Bootloader vs. Programmer
I have just started using Arduino boards and I am not sure what the programmers are. I read that you can use a bootloader or a programmer to run your code on an Arduino board. I also read that running with a programmer does not take up any memory space for the bootloader and does not take any time to go through the bootloader.
My question is then, why should I not upload my code during development using a programmer?

you definitely can do that if you want ... it is unclear why you think otherwise .... also your question is bogus because it is asking for a reason about something that does not exist

The bootloader is a 'program' that resides inside the Atmel IC and makes that IC an 'Arduino'. The bootloader takes care that a sketch can be retrieved by UART (via the USB) and stored inside the Arduino.
The programmer is an external hardware device that can upload a sketch without using the bootloader. Another Arduino can also be used as programmer.
In both cases, when a sketch is loaded, it can be run by the Arduino. The programmer does not need a bootloader, so the memory that normally is taken by the bootloader can be saved.
You could use a programmer, but normally there's plenty space for a sketch. Note, it's not the SRAM memory that is saved, only the Flash memory. And if you are reaching the limit of the Flash memory, you should either optimize it, or move to an Arduino with more Flash memory.
Also, the bootloader is much more easy to use, since you can upload the sketch (to the boatloader) with the Arduino IDE. Programming can be done too by the IDE but is less trivial.


text:
Arduino ESP8266 - stack ERROR - ESPExceptionDecoder to debug - need help to find ERROR
i have one project that can ready compiled. The function is break on the hardware an i need help to finde the error. I am a beginner and ask for help. How can I narrow the error down?
Sketch:

SIGNALESP.ino (https://github.com/HomeAutoUser/ERROR_search/tree/master/SIGNALESP)

Platform

Hardware: AZDelivery NodeMCU Lua Amica Modul V2 ESP8266 ESP-12E
Core Version: latest git
Development Env: Arduino IDE
Operating System: Windows

Settings in IDE

Module: Nodemcu v1.0
Flash Size: 4MB
Flash Frequency: 40Mhz
CPU Frequency: 80Mhz
Upload Speed: 115200

Problem Description
15:54:11.662 -> Fatal exception 3(LoadStoreErrorCause):
15:54:11.662 -> epc1=0x4000e041, epc2=0x00000000, epc3=0x00000000, excvaddr=0x4024bcc2, depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> Exception (3):
15:54:11.701 -> epc1=0x4000e041 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4024bcc2 depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> >>>stack>>>
15:54:11.701 ->
15:54:11.701 -> ctx: cont
15:54:11.701 -> sp: 3ffffce0 end: 3fffffc0 offset: 01a0
15:54:11.701 -> 3ffffe80:  00000000 00000019 4024bcaa 00000000
15:54:11.701 -> 3ffffe90:  00000001 3fff16a4 00000000 000001ff
15:54:11.701 -> 3ffffea0:  00000000 00000019 401003fc 0001687b
15:54:11.701 -> 3ffffeb0:  00000000 00000000 00000001 4024bcaa
15:54:11.701 -> 3ffffec0:  00000000 00000019 3fff1134 4020ef28
15:54:11.701 -> 3ffffed0:  ffffffff 3fffc6fc 00000001 4024bcaa
15:54:11.741 -> 3ffffee0:  00000001 00000000 3fff1134 4020efc2
15:54:11.741 -> 3ffffef0:  00000019 00000000 3fff1134 4020f09d
15:54:11.741 -> 3fffff00:  40214e08 00000000 00001388 00000057
15:54:11.741 -> 3fffff10:  4020f060 3ffef254 4024bcaa 4021104d
15:54:11.741 -> 3fffff20:  3ffef10c 3ffef10c 3ffef254 40211275
15:54:11.741 -> 3fffff30:  007a1200 3ffef10c 3ffeeec0 402019b9
15:54:11.741 -> 3fffff40:  00000000 00000000 00000001 40100304
15:54:11.741 -> 3fffff50:  3ffef10c 00000000 3fff1134 4020f130
15:54:11.741 -> 3fffff60:  3ffef10c 3ffef254 0000000d 3ffef115
15:54:11.781 -> 3fffff70:  3ffef10c 3ffef254 3ffeeec0 402027dd
15:54:11.781 -> 3fffff80:  3fffdad0 00000000 3ffef728 3ffef768
15:54:11.781 -> 3fffff90:  3fffdad0 00000000 3ffef728 40202849
15:54:11.781 -> 3fffffa0:  3fffdad0 00000000 3ffef728 40212b68
15:54:11.781 -> 3fffffb0:  feefeffe feefeffe 3ffe8500 40101059
15:54:11.781 -> <<<stack<<<
15:54:11.781 ->
15:54:11.781 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
15:54:11.781 ->
15:54:11.781 -> load 0x4010f000, len 1392, room 16
15:54:11.821 -> tail 0
15:54:11.821 -> chksum 0xd0
15:54:11.821 -> csum 0xd0
15:54:11.821 -> v3d128e5c
15:54:11.821 -> ~ld
15:54:11.861 ->

ESPExceptionDecoder Debug
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
PC: 0x4000e041
EXCVADDR: 0x4024bcc2

Decoding stack results
0x401003fc: millis() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_wiring.cpp line 188
0x4020ef28: ClientContext::_write_some() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 514
0x4020efc2: ClientContext::_write_from_source(DataSource*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 450
0x4020f09d: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
0x4020f060: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 220
0x4021104d: Print::write(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266/Print.h line 60
0x40211275: Print::println(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\Print.cpp line 129
0x402019b9: commands::HandleShortCommand() at D:\Temp\arduino_build_652018\sketch/commands.h line 363
0x40100304: ets_post(uint8, ETSSignal, ETSParam) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020f130: ClientContext::_consume(unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 557
0x402027dd: serialEvent() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 591
0x40202849: loop() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 470
0x40212b68: loop_wrapper() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

Well it crashes somewhere related to either answering something via WiFi or a serial command in commands::HandleShortCommand(). What are you entering as input?

The input ist only a command like V or ? link

exactly. What have you inputted? And what is your line end setting in the serial monitor?

I have to enter a V. If I look at the ESP with Netcat and type V, I get an answer. If I do the same with Putty Telnet (port 23), the stack comes :-(
V V 3.4.0-dev SIGNALESP cc1101 (chip CC110 unknown) - compiled at Feb  8 2020 16:08:51 ? ? Use one of V R t X S P C r W s x e V  With linebreak, but here ist it not view

I'm assuming you're taking the sketch from https://github.com/RFD-FHEM/SIGNALDuino and this issue is from you? (https://github.com/RFD-FHEM/RFFHEM/issues/795) Which ino file are you using exactly?

Right, here link is the testcode. This code have one ino SIGNALESP.ino
So you can see all files.

Yes the error is reproducable with PuTTY. It has something to do with line endings and invalid / empty commands. E.g., using ncat -v 192.168.1.135 23 and typing V it works, but with Putty there is a crash. With PuTTY configuration Terminal -> Local Line Ending: Force Off things are a bit better but still empty commands crash it. I'll have a look at the code.

The problem is that code like
            MSG_PRINTLN(TXT_UNSUPPORTED1);

with
#define MSG_PRINTLN(...) { MSG_PRINTER.println(__VA_ARGS__); }

and
static const char TXT_UNSUPPORTED1[]        PROGMEM = "Unsupported short command";

On the ESP8266 calls the println() function which accepts a char*, expected from RAM. However since the string here was put into flash and not RAM, this function will crash upon execution.
The fix is to use the __FlashStringHelper class which calls the correct println() overload and doesn't crash.
See PR https://github.com/HomeAutoUser/ERROR_search/pull/1 and https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html


text:
MacOS 10.15.1 Catalina CU port always busy, and TTY port not selectable
I am trying to use an FTDI breakout board to connect to my custom made Arduino compatible board. I am using a new 16 inch macbook pro with USB-c ports, so I am using a dongle, in case that could be the problem.
Every time I try and upload a sketch I get the error: "can't open device "/dev/cu.usbserial-D306P6WW": Resource busy". When I check the /dev/ folder, both "/dev/cu.usbserial-D306P6WW" and "/dev/tty.usbserial-D306P6WW" show up, however in Arduino IDE I can only choose the "/dev/cu.usbserial-D306P6WW" option. I have installed FTDI VCP drivers, CH340 drivers and all kinds of other drivers to try and fix this issue. I have restarted countless times, and I have used a multitude of commands to check for programs hogging the usb port, but there is never a program. Plugging a harddrive into the same port causes no problems, so the port can't really be the problem. I am using a "FTDI FT231XS" board from Sparkfun.

Do you have the Arduino serial monitor opened in parallel? Also, from where do you have the FTDI drivers? Have you unloaded the mac os kernel drivers before that?

I don't have the serial monitor open. I downloaded the FTDI drivers from their website, and I have not unloaded any drivers? Do I need to do that?

Hm actually I confused it with the CH340 installation process (https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver). But that shouldn't be used for such a recent Mac OS version; also you don't need it because you don't have a CH340 chipset. If you followed https://learn.sparkfun.com/ftdiDriversMac you should be good. Can you open a root terminal and edit your question to include the output of kextstat | grep FTDI? Unplug and replug the FTDI board and post the recent dmesg output starting at the unplugging of the USB device.

Thanks for your help, I tried a whole bunch of other things, and then decided I would update my Mac version. For some mystical reason this actually fixed the problem?! Thanks anyway!

Nevermind, updating my MacOS version to 10.15.3 magically fixed the problem...


text:
How to set ALPN ProtocolName when negotiating SSL using ArduinoBearSSL
I am trying to set up an Arduino MKR Wifi 1010 to push MQTT messages to AWS IOT. I am following this tutorial https://create.arduino.cc/projecthub/Arduino_Genuino/securely-connecting-an-arduino-mkr-wifi-1010-to-aws-iot-core-a9f365 but I run into problems when the standard (secure) MQTT port (8883) seems to be filtered out somewhere between me and AWS. So I try to switch to 443, but AWS advises that you have to use the TLS extension ALPN and set ProtocolName to to "x-amzn-mqtt-ca" (see https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html).
I am at a loss how I am to do this in ArduinoBearSSL (https://github.com/arduino-libraries/ArduinoBearSSL).

Are you 100% sure your network drops conenctions between you and AWS on port 8883? You shouldn't work on a workaround for the wrong problem. What entitity drops your packets? Can you do something against that?

Also, bearssl already has the ALPN function, see https://github.com/arduino-libraries/ArduinoBearSSL/blob/555ec30550cfc7bc6ddf5739cd999e314a6e4f0d/src/bearssl/bearssl_ssl.h#L1293-L1328. You can set give br_ssl_engine_set_protocol_names a list of strings, but you would need to modify your MQTT client to call that function.


text:
Can ESP 32 use the wire library exactly like that was in Arduino?
Compare the YouTube video and this webpage, 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?

in the video he doesn't use Arduino, but the Espressif IDF framework directly. the Arduino esp32 boards package has the Wire library for Arduino

@Juraj so does ESP 32 and ESP 8266 used exactly like Arduino for standard libraries? I heard the methods of pin labels were a little bit different.

I had no trouble to use the same sketch with Wire library on Uno and esp8266

software is the same. watch the voltages and pullups.

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...


text:
Sound sensor only detect peaks
I'm using this SparkFun Sound Sensor 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.

It seems you have to increase the gain, see inside the document
Sound dectector hookup guide
The following fragment:

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.

I thought this is only for the sound detection (gate output) but I'll give it a try, thank you for the insight!

I never used this component, but I guess it will improve the sound sensivity, which is what should be increased if you get too less gain.

I've tried it and it changed nothing :(

Sorry to hear … a poor man solution would be to use an opamp/amplifier before the input of this sound detector.

Maybe, it's above my knowledge at the moment.
Thank you for you replies though :)


text:
Nodemcu powering with 5.2v and 2A?
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 .

the 8 A is the maximum current that can be supplied before the power supply shuts down, or the output voltage starts to drop .... it does not mean that 8 amps will be pushed through any load  ... the amount of current that 5 V can push through a load is dependent on the load resistance

@jsotola i understand thanks for your answer :)

Generally, we specify DC power supplies as constant voltage sources.  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, should exceed the maximum combined current demand of all connected devices (loads).

usb output is 5.2V which is its ok . But now I have a prototype for my project . i plug nodemcu to pc usb port and its provide 500mAh and its ok . but i want to connect 5v 2A usb port . I dont have too much electrical knowledge  . I have difficulty about that. I just wonder nodemcu and other devices does it burn or not ?

USB ports are regulated to be 5 volts or very close to 5 volts.  You don't regulate both voltage and current.  It is one or the other.  Older USB ports are obliged to supply up to 500mA.  Newer USB ports can supply more.  But you only need to match voltages when talking about constant voltage power supplies.  You do not match the current values.  You only need to make sure you draw less current then the constant voltage power supply is rated for.

For example, it is fine if you plug in a USB keyboard which expects 5 volts and draws only 15mA.  As even the oldest USB computer ports supply 5 volts and have at least 500mA to offer.  See, 5 volts == 5 volts and 15mA is < 500mA.  So this should work fine.

Ok. I understand now. more clear in my mind. Thank you for explanation and fast reply :)

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

Thanks man .  I'm saying hypothetically. We will connect 5v 10A supply for nodemcu and nodemcu still pulls as much as it needs right ?

Yes, it will only pull as much as it needs no matter how many amps the supply is capable of.

Ok man thanks for your answer :)


text:
Trouble with 4 digit 7 segment display
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:

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?

the wrong segment is being lit probably .... unplug wires one at a time to figure out which one is causing the problem

Well one is on that is not supposed to and one that is off when it should be, but the rest of the numbers work which I dont understand.

you may have more than one pair of segments interchanged ... the picture shows segments d and e interchanged

It's a binary display: only shows zeros and ones.

It seems that segment lines b and c are interchanged. This might explain why 0, 1, 3, 4, 7, 8, and 9 look correct, because they have both segments on. 2, 5, and 6 need only one of both on.


text:
Arduino UNO + USB Host Shield 2.0 + RFID RFC522
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

}

what is your question? ... you said nothing about any problem

i'm not able to store / use the input from the keyboard and write them into the query from the rfid code. The rfid code waiting for an input from the Serial monitor. So o need to change that is it waiting for the input from the keyboard


text:
To control the relay switching in nextion using esp32 Microcontroller
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,
#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.

What is the NexDualStateButton class? Is that defined by Nextion? And what is Nextion?

If I didn't include the NexDualStateButton in the include statement, I am getting an error as NexDSButton was not declared. So only I included the NexDualStateButton in the include statement

Also, I downloaded the nextion stable environment library(Nextion 7.0.0) and I added that in Arduino IDE. I can't able to add the Nextion unstable version which contains the dual state button library.

That doesn't answer my question. What is that class? I understand that you need it, but what does it do? You're using classes without explaining where they come from, what they are for, or where they are documented.

If I include that class my dual state button works. The Nextion library is not so stable.

You are not providing enough information for us to help you. I've voted to close your question.

Actually I am new to Arduino programming and whatever I am is like trial and error method. The Class #include "NexDualStateButton.h" is used to declare the library of NextionDualState Button.

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 );
  }

}

I am using for taking button state in my case. Don't use if you don't want to use it. Its wait after take button state 200ms and enter if condition . Sometimes there is a delay between arduino and nextion i am waiting because of this .

this delay not for this. in my project i am changing dual_state as 0 after if condition . This is for my case. If you dont want to use it then dont use it.

You're overreacting bye

Thanks Alper Aslan. I will check using your code and will let you know soon.

No, Juraj has a point. Don't include code that does not make sense for most users in your answer. You say "I am using for taking button state in my case." That suggests that most users would not need or want that delay, so edit your answer and delete it. The delay() function causes all sorts of problems, and it should only be used in very special circumstances.

Ok guys i will edit you are right thanks for your advice

@AbhishekhAaron you are welcome i am using this code on my project and working properly its not listen all time. Its just listen when pressed button and take button state.

Thanks, guys. My code works. Alper Aslan I used your code for my dual state button and it works now. Below I have attached my code,

@AbhishekhAaron what a good news :)

@AbhishekhAaron, what is the value of the dual_state variable if it is not 1?

@Juraj Sorry, I didn't get your question?

Its written on if condition its zero

I try to understand the differ3nce between the code in question and code in answer. they look equivalent.

@Juraj in question code bt0 state listen all the time by Esp32. In NexTouch nex_listen_list object.

I don't see what line is different

char buffer[100] = {0};
NexTouch *nex_listen_list[] =
{
&bt0,
NULL
};

ok. sorry I compared the codes in both answers not with the question.

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.

#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 ");

}

It's OK to accept you're own answer as the solution to the problem.

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
}


text:
SIM800L LED is not blinking
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
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.

According to the linked tutorial, the power source is OK. Did you see the warning that, the GND must be connect before any other pin (especially the VCC). Otherwise the device could be destroyed. A working LED is no guaranty that the board is OK too. Most probably you destroyed the device or you made a mistake when connecting the device or the batteries lifetime is at its end or the battery is not fully loaded. You did not add a picture of your setup, so I can not help further with an eventually false connected setup.

okay I shall add the picture once I am home but just give me an idea of how to check the battery. While I check the voltage with multimeter I get 3.8V steady. If the battery is not fully charged then shouldn't it drop the voltage?

Ignore the LED. Have you managed to establish communication with the SIM800L over the UART port?

I thought it needs power to start a communication. Okay let me try that.

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 (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.

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

Hi @Patel and welcome to the Arduino Stack Exchange. This answer is unclear and needs clarification.

@Patel Let me edit my answer. This would help in a better way. and sorry for the delay, was busy with covid.


text:
esp32-cam publish image to mqtt
I want to publish image capture through ESP32-CAM 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 :

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
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);
}

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

As you can see here, the definition of the return value for esp_camera_fb_get() is
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.

I have updated question with somewhat working code.

If it is still not working for you try below code it's working for me:

 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;

I got error: 'mbedtls_base64_encode' was not declared in this scope     int err1= mbedtls_base64_encode(image, image_buf_size, &olen, fb->buf, length);

Include base64 C source File and C header source File in you sketch as it is given at link

#include "mbedtls/base64.h"


text:
MkrWan freezes after short power outage
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 ?

"Mkrwan still seems running" how do you see this? "When electric comes back, it doesnt work anymore" how do you see this?

Because of the led on it seems on and light does not go out.

What is the firmware programmed to do? Please edit to show the code.

a brownout can cause all sorts of unexpected and hard to diagnose issues. Maybe add brownout detection, uses a less buffered PSU, use a bleeder resistor, or a battery backup.

dandavis as you said it looks like brownout problem(I never heard before you). To solve it, ordered Lipo batteries, I will test and will inform if it solves.

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

It is OK to accept your own answer as the solution to the problem.


text:
Serialize JSON as response to HTTP request
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)

Did you look at the documentation of ArduinoJson? Did you try? Did it work? If not, what errors did you get?

Yes I did. Yes I tried. No it did not. I added the error message.

you can just build it as a string. imho, the big advantage of the json lib is parsing, not serializing.

Weird. WiFiServer::ClientType is defined as WiFiClient, which inherits from Client, which inherits from Stream, which inherits from Print, which you should be able to serialize to. Could you try to serialize to Serial, just to see if it works?

That’s what I thought! I serialized into a char[] and it works fine

serializeJson() accepts a Print&, i.e, a reference to a class that implements the Print interface.
WiFiClient does implement the Print interface, but 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:
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 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.