text:
Reading out two sensors via Com-Port at the same time
I have two Arduino Nano Every and a sensor connected to each of them. Here is what's happening:

I upload the sketch to the first Arduino on Com4 and see its output is correct via the Serial Monitor
I open a new instance of the Arduino-software, upload the same sketch to the second Arduino on Com6 and see its output is correct. However, in the meantime the Arduino on Com4 has stopped sending or receiving data
If I close the second IDE-instance and re-upload the sketch to the first Arduino on Com4, it starts working again.

So, essentially I have two Arduinos which I can't read out at the same time.
The sensors are not connected, so I don't know where the problem is. Shouldn't the Com-Ports be independent?

UPDATE, self answer:
It was a broken USB cable.

Shouldn't the Com-Ports be independent?

Not in the Arduino IDE, no. Basically the IDE is [expletive deleted] when it comes to using more than one board at a time.
You're better off using a proper serial terminal program, not the "serial monitor" in the IDE. Something like Teraterm or Putty, where you can have multiple instances on different ports at once.

Interestingly, the same happens with Putty..

you could write a monitoring sketch in Processing ... https://processing.org/

Or upgrade to UECIDE that has much much better port handling.

I actually used LabView in the first place which usually has no difficulties handling multiple ports at once. However, it doesn't work as well ... and you also see that the LED stops blinking, so I assume it's not just a software problem?

Maybe the firmware in the ATSAMD isn't handling a USB disconnection (LineState change) properly, or maybe the client software isn't opening the port right (Setting LineState).

It is kind of ironic that the chip they chose to implement the USB interface is far more powerful than the chip that you as a user get to program.

@Majenko, it is ATmega4809 20 MHz, 48kB flash, 6 kB SRAM; SAMD11 48 MHz, 16 kB flash, 4kB SRAM

Yes. Like I said. A slow 8 bit vs a faster 32 bit. More power in the USB interface.

I use multiple instances of the Arduino IDE open at once to solve this problem, and it works well for multiple serial connections from multiple boards at once. You get one serial connection per instance open. I used to have multiple versions of the IDE installed for this to work but I think it works fine just running multiple instances of the program at once now. If not, just run multiple zip-installed instances of the IDE from different unzipped folders.

Also, I have a Python demo to read serial data from an Arduino if anyone wants it (and if I won't be suspended for sharing a link to it, of course). It's on my GitHub I believe. It makes logging from Arduino really easy and versatile, and shows how to get a PC program and Arduino talking.


text:
NodeMCU ESP8266 disconnected from WiFi after several hours running
I tried to test NodeMCU ESP8266 with this code from here
                #include <ESP8266WiFi.h>
                #include <WiFiClient.h>
                #include <ESP8266WebServer.h>
                #include <ESP8266HTTPClient.h>

                /* Set these to your desired credentials. */
                const char *ssid = "dummy";  //ENTER YOUR WIFI SETTINGS
                const char *password = "12345678";

                //Web/Server address to read/write from
                const char *host = "192.168.43.128";   //https://circuits4you.com website or IP address of server

                //=======================================================================
                //                    Power on setup
                //=======================================================================

                void setup() {
                  delay(1000);
                  Serial.begin(115200);
                  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
                  delay(1000);
                  WiFi.setSleepMode(WIFI_NONE_SLEEP);
                  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot

                  WiFi.begin(ssid, password);     //Connect to your WiFi router
                  Serial.println("");

                  Serial.print("Connecting");
                  // Wait for connection
                  while (WiFi.status() != WL_CONNECTED) {
                    delay(500);
                    Serial.print(".");
                  }

                  //If connection successful show IP address in serial monitor
                  Serial.println("");
                  Serial.print("Connected to ");
                  Serial.println(ssid);
                  Serial.print("IP address: ");
                  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
                }

                //=======================================================================
                //                    Main Program Loop
                //=======================================================================
                void loop() {
                  HTTPClient http;    //Declare object of class HTTPClient

                  String ADCData, station, postData;
                  int adcvalue=analogRead(A0);  //Read Analog value of LDR
                  ADCData = String(adcvalue);   //String to interger conversion
                  station = "A";

                  //Post Data
                  postData = "status=" + ADCData + "&station=" + station ;

                  http.begin("http://192.168.43.128/c4yforum/postdemo.php");              //Specify request destination
                  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header

                  int httpCode = http.POST(postData);   //Send the request
                  String payload = http.getString();    //Get the response payload

                  Serial.println(httpCode);   //Print HTTP return code
                  Serial.println(payload);    //Print request response payload

                  http.end();  //Close connection

                  delay(5000);  //Post Data at every 5 seconds
                }

It was running well and posted data to Database after a few hours. Then It was disconnected from WiFi somehow . Of course I reset power supply again It's connected.
How should I do to fix with that code to reconnect WiFi right after that accident Or any other Solution  for that ? Thank you

don't use String this way. https://majenko.co.uk/blog/evils-arduino-strings

What you need to do is leave the board connected to your computer and watch the serial monitor to capture the output during the crash.  If the board has a true crash it will output a bunch of information which may tell you why you it is crashing.  It could be a strings/heap problem or maybe a memory issue since you are declaring a new http object every 5 seconds.  Maybe try putting the HTTPClient http; line up where you declare the host variable so that it is a global variable and not a local variable.
Since your loop doesn't test to make sure the wifi connection is still good then if you get a disconnection then the program will just fail and never try to re-connect.  So at the start of your main loop put the same wifi testing logic that is also in the setup function. If the connection is down then reset and start from the very beginning to re-establish the wifi connection.
if (WiFi.status() != WL_CONNECTED) {
    ESP.reset()
  }

Thank you . I declared HTTPClient http ; outside of loop method. However It's still get the same errors .  Assume that It could be a strings/heap problem or maybe a memory issue. How should  I do please ?

That worked for me ! Thank you

I also had the same issues. I've looked for some posting like here.
You can try these codes
void loop()
 {
 WiFiClient client;

 Serial.printf("\n[Connecting to %s ... ", host);
if (client.connect(host, 80))
{
Serial.println("connected]");

Serial.println("[Sending a request]");
client.print(String("GET /") + " HTTP/1.1\r\n" +
             "Host: " + host + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

Serial.println("[Response:]");
while (client.connected() || client.available())
{
  if (client.available())
  {
    String line = client.readStringUntil('\n');
    Serial.println(line);
  }
}
client.stop();
  Serial.println("\n[Disconnected]");
 }
 else
 {
  Serial.println("connection failed!]");
  client.stop();
 }
 delay(5000);
 }

The seconds thing as @tavis said you can try from here.
It sounds ESP.restart(); is recommended rather than ESP.reset();
It seems our issue is very hard.

Thanks for sharing

source: Stack Exchange

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

sort: votes


text:
Is it possible to connect a 36 pin 4 digit 7 segment display on an Arduino Uno R3?
First of all,here's the datasheet of the 4 digit 7 segment display that I'm using:
http://www.kingbrightusa.com/images/catalog/SPEC/ca56-11ewa.pdf
How can I make a counter or a clock out of this particular led display,considering the fact that I don't have enough digital pins to manipulate led's pins?

https://miguelpynto.github.io/ShiftDisplay/

I recently played with a seven segment LED clock display https://github.com/jandrassy/lab/blob/master/KitchenTimer/KitchenTimer.ino

Only need 4, or 5 pins; SCK (D13), MOSI (D11), slave select (D10).
Maybe PWM (D9) for brightness.
D12 not used, but is tied up as part of SPI bus.
Connect the Anodes to +5.
Connect the cathodes, with a current limit resistor per cathode, to the outputs of 4 TPIC6C595, or TPIC6B595.
For the resistor, assume worst case voltage drop of 2V and 20mA current draw:
(5V - 2V)/.02A = 150 phm.
Use a PWM output pin to drive the OE/ pin of the '595s for brightness control.
Then shift data into the daisychained shift registers as an update is needed.
byte dataMap[] = {
0b00111111, // 0 with bits representing DP,g,f,e,d,c,b,a
0b00000110, // 1
0b01011011, // 2
// etc
};

where segments are layed at as
   a
f     b
   g
e     c
   d      DP or colon

then call the array in loop(), make it a function if you want.
digitalWrite (ssPin, LOW); // D10 on Uno, used as Latch signal
for (x = 0; x <4; x=x+1){
SPI.transfer (mapArray[digit0]); // digit0 value mapped to segments
SPI.transfer (mapArray[digit1]);
SPI.transfer (mapArray[digit2]);
SPI.transfer (mapArray[digit3]);
}
digitalWrite (ssPin, LOW); // outputs update on this rising edge

I wonder where DP5, DP6, which make the colon, are? I don't see them in the pinout.

595 shift registers don't use SPI. they can be handled ye the SPI peripheral but I think they predate SPI. I use shiftOut Arduino function. https://www.arduino.cc/en/Tutorial/ShiftOut

I use SPI to load them all the time, goes way faster then shiftout() does. Can even set the SPI clock to 8 MHz (up from the default speed of 4 MHz) to load them crazy fast.  Be sure to have a 0.1uF cap at the VCC pin of each device. I usually have the Clear line connected to +5, and OE/ connected to GND unless I am using PWM on the outputs.

As Juraj mentioned, you can use shift registers, such as 74HC595 which uses the SPI protocol.
To elaborate slightly on this:

You can cascade 4 shift registers, totaling 32 pins for output
If you need 36, you can use the remaining 4 as normal pins (this is probably the easiest solution)
Or you can use the Chip/Slave Select feature of SPI to control two chains of shift registers. So e.g. one chain is doing 4 * 8 = 32 pins, the other (single shift register) using 8 pins (from where 4 pins are used only).

To make a clock, use a RTC (Real time clock) module/IC, a counter (unless very high frequency) does not need an external IC.

for 4 digits two 74HC595 are enough

True … wonder where the 36 pins come from (7 digits + 1 dot maybe, is 8 * 4 = 32 pins, one for VCC/GND, but other two ?)

@MichelKeijzers by 36 I mean:4X7=28 segments 4X1=4 dots,and the other 4 remaining are the pins for the common anode for each digit.

In that case, 32 pins need to be controlled by the shift registers, so 4 shift registers will suffice, and no need for CS/SS, just cascade them.

1 and half shiift registers. one for 7 segments and dot and one for digit select. two registers can handle 8 digits. see the tutorial.

@Juraj that's even easier indeed

You actually only need 12 pins for that display.
The display is made up of 4 separate common anode LED displays, and you can use that to your advantage.
Since the 4 anode clusters are separate you have the ability to switch an entire digit on or off. And as a result all the cathodes of the segments can be commoned together (that is, the cathodes of all the segment As can be commoned, and the cathodes of all the segment Bs, etc), which is then 8 clusters of 4 cathodes.
That means you can have 4 outputs controlling the for anodes (ideally through PNP transistors or P-channel MOSFETs to handle higher current), and 8 outputs to control all the cathodes (each through a resistor and ideally an NPN transistor or N-channel MOSFET to handle higher current).
The you rapidly switch between each digit displaying the right segment combination for that digit.
Here's a partial example showing 4 digits but just segments A and B. Youd expand this out for segments C through G.  GPIO_A1 to GPIO_A4 are activated to select which digit is being displayed. GPIO_CA through GPIO_CG would be to select the arrangement of segments on that digit.

simulate this circuit – Schematic created using CircuitLab

Though it should be mentioned, that multiplexing the displays like this will affect the brightness.

@chrisl True, but with the reduced duty cycle comes the ability to run the LEDs at a higher current, thus somewhat compensating for that.

@Majenko Are GPIO_A1,GPIO_A2,GPIO_A3 and GPIO_A4,and GPIO_CA,GPIO_CA the NPN,respectively the  transistors that you are referring to?If so,I still don't understand how they actually work such that it can manipulate all 4 digits without even turning even one of them off.Also how do I simulate properly your circuit?And I'm asking this because I have never never worked with such online tool before.

Ignore the "simulate this circuit" thing, it's meaningless. The sequence is: 1 .Turn on GPIO_A1. 2. Turn on combination of GPIO_C*. 3. Turn off all GPIO_C*. 4. Turn off GPIO_A1. 5. Turn on GPIO_A2. 6. Turn on combination of GPIO_C*. 7. Turn off all GPIO_C*. 8. Turn off GPIO_A2. Etc...

If you just want to try out multiplexing. You can leave out all the transistors, and use resistors of at least 1.2kOhm. That way you'd never exceed the 20mA per IO pin on the Arduino, even if all segments of a digit are lid. The downside will be that it will be less bright. Connect all the four common anodes for the four digits (22,23,31,32) to 4 Arduino pins. Then connect all A segments (20,25,29,34) together, and connect that, via a 1.2k resitor to an Arduino pin. Repeat for all segments and the DP. You'd end up using 8 resistors and 12 Arduino pins.

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


text:
PCF8575c changes address in I2C Scanner
I want to connect a PCF8575c pin extender to an ESP32, so that I can light 12 LEDs. The problem is that after the connection, when I try to use an I2C Scanner, it shows me a lot of different addresses, not a constant one. Could this happen from a pin fault? I am using this library:
https://github.com/xreef/PCF8575_library
Also, the I2C scanner can be found here: https://playground.arduino.cc/Main/I2cScanner/
And the pins that I use for the LEDs are defined this way:
  pcf8575.pinMode(P0, OUTPUT);
  pcf8575.pinMode(P1, OUTPUT);
  pcf8575.pinMode(P2, OUTPUT);
  pcf8575.pinMode(P3, OUTPUT);
  pcf8575.pinMode(P5, OUTPUT);
  pcf8575.pinMode(P6, OUTPUT);
  pcf8575.pinMode(P11, OUTPUT);
  pcf8575.pinMode(P12, OUTPUT);
  pcf8575.pinMode(P14, OUTPUT);
  pcf8575.pinMode(P15, OUTPUT);
  pcf8575.pinMode(P16, OUTPUT);
  pcf8575.pinMode(P17, OUTPUT);

The link to the exact PCF8575c:
https://www.aliexpress.com/item/2038559527.html?spm=a2g0o.productlist.0.0.3f8331ebu0zuwr&algo_pvid=5e9fc157-a422-4847-acf4-8618a2d365ea&algo_expid=5e9fc157-a422-4847-acf4-8618a2d365ea-2&btsid=0ab6f82415840969999872503e3228&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_

What are the addresses it gives you?

Have you configured the A0/A1/A2 jumpers on the board?

I agree with Majenko. That really sounds like unconnected and thus floating address pins.

Look at the back of the module. There are 3 groups of 3 solder pads each, marked with A0, A1 and A2. With these pads you can set the 3 least significant bits of the address.
On the images in your product link these pads are unconnected. The middle pin is the address pin. The left pad (which is connected to a trace) is Vcc, the right pad (which is connected to the big trace area) is ground. By connecting the middle pad with ground, you set the address bit to zero. By connecting it to Vcc, you set it to 1.
As the pads are unconnected, the address pins are floating. In that state, the pin is reacting to random electrical noise, thus changing state randomly. So also the address changes randomly.
You need to connect every address pin to either ground or Vcc by adding a solder bridge to the pads.


text:
Scroll one line of text while another line is static on a SSD1306 OLED
I have an SSD1306 OLED that I have connected to a Wemos D1 Mini. It works like a charm, but I was wondering if it was possible to have two lines of code, where one line is static, and the other one scrolls? No example on the web as far as I have tried to find.

I just found the answer on the following site: https://lastminuteengineers.com/oled-display-arduino-tutorial/
Basically, the method startscroll* on the display takes some arguments.
By passing the proper start page and stope page you can scroll parts of the screen.
Refer to OLED Memory Map for explanation of the pages on the screen. There are eight pages in the display from 0 to 7, so we can scroll a certain part of the screen by passing specific page numbers as parameters.
In this example, we pass both the parameters as 0x00. This will scoll the first page only (first 8 rows) of the display:
// Scroll part of the screen
display.setCursor(0,0);
display.setTextSize(1);
display.println("Scroll");
display.println("some part");
display.println("of the screen.");
display.display();
display.startscrollright(0x00, 0x00);

Source: https://lastminuteengineers.com/oled-display-arduino-tutorial/

Please either explain more about the solution in your answer or delete your question. These Q&A are supposed to serve as knowledgebase and links tend to get broken rather fast, which would make your answer completely useless for others

@chrisl Updated my post. Thanks for telling me, you are completely right.


text:
How do I make a proper long string scanner to detect specific tags in a stream of characters?
Here's my code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX, TX

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

bool is_uploading_book = false;
char c = ' ';
String recv_scanner = "";
void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        recv_scanner += c;
        if(recv_scanner.length() >= 50) {
          recv_scanner.remove(0, 1);
        }
        // I believe there's something wrong with the recv_scanner.
        if(is_uploading_book) {
          Serial.write(c);
        } else {
          if(recv_scanner.indexOf("(__BOOK_UPLOAD_START__)") >= 0) {
            is_uploading_book = true;
          }
        }
        Serial.println("\n\n" + recv_scanner + "\n\n");
    }
}

I'm sending a book (long text) in the form of characters one by one from my phone to my HC-05 module (and the Arduino).
My goal is to spot the tag "(_BOOK_UPLOAD_START_)" in the incoming characters.
Arduino allows me to receive the characters of the book one by one on each loop.
I'm storing those characters in a string called recv_scanner where I allow it's maximum size to be 50 characters and once it reaches those 50 characters, I start to remove the first character and add a new one on each loop (so it can only see 50 characters at a time because maximum String length is 200 and for my purposes, 50 is enough).
The thing is, it doesn't work properly.
When I Serial.println the recv_scanner on every loop (so I see how it progresses) it starts to look like this:
⸮qsnieq⸮cn .laslvanm.⸮⸮⸮d⸮alvuv⸮⸮urosqiam tr⸮⸮⸮

(It starts normally and then slowly progresses into this)
I have no idea what that is.
As far as my predictions go, it should show 50 characters and they should be parts of the books.
Is there something fundamental about Strings that I don't know of?
I'm doing this so I'm able to detect a tag (_BOOK_UPLOAD_END_) at the end of the book and finish uploading.
Feel free to ask my questions if something is unclear.

Another option is to not save the characters in buffer but instead check each one as they arrive to see if the character is the next in the tag sequence.
This has the advantage that you don't need a buffer to match the tag and you don't have to repeatedly search for the string in the buffer.
const char* TAG_STR="(__BOOK_UPLOAD_START__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

void loop() {
  if (BTserial.available()) {
    c = BTserial.read();
    if (is_uploading_book) {
      //do book stuff
    } else {
      if (c == TAG_STR[tag_pos]) {
        // c matched the next character in the string
        tag_pos++;
      } else if (c == TAG_STR[0]) {
        // matched first char in the middle, restart
        tag_pos = 1;
      } else {
        // Did not match the next character so we should start over
        tag_pos = 0;
      }
      // The next character to match is the string terminator
      // so we must have matched the whole string.
      if (TAG_STR[tag_pos] == '\0') {
        is_uploading_book = true;
      }
    }
  }
}

Works perfectly!!! Thank you!

Unlikely to be an issue in this case, but the algorithm can fail for inputs like __BOOK__BOOK_UPLOAD_START__. At tag_pos 7, _ does not match U, so the algorithm returns to tag pos 1. But then B doesn't match _ and no detection is made. This problem will occur whenever the first character is repeated in the search string, and it can be avoided by comparing the search string with itself.

@Craig Sorry to bother you. Would you mind taking a look at this: https://justpaste.it/3wobv

@jpa yes that is a limit of this method.

I think your problem lies in the usage of the String class. Every time, that you concat a String variable, a new buffer for the result is allocated in the background via dynamic memory allocation. That can result in heap fragmentation, which eats up your memory pretty fast (especially on the smaller ones, like the Uno).
Instead you should use a char array as ring buffer. Let's define the buffer first and initialize it to zero:
#define BUFFER_SIZE    50
char buffer[BUFFER_SIZE] = {0};

Now we define position variables, where the valid data starts and ends in the buffer:
uint8_t buffer_start = 0;
uint8_t buffer_end = 0;

When buffer_start == buffer_end, the buffer is empty. When buffer_end is one position before buffer_start, the buffer is full. To put one character into the buffer we do the following (note, that c is the same variable, as in your code):
if( ((buffer_end + 1) % BUFFER_SIZE) == buffer_start)
{
    buffer_start = (buffer_start + 1) % BUFFER_SIZE;
}
buffer[buffer_end] = c;
buffer_end = (buffer_end+1) % BUFFER_SIZE;

What are we doing here? First we need to check, if our buffer is full. We are doing this by comparing buffer_start to the next position of your buffer_end. The calculation of the new position is where the magic happens. First we increment buffer_end by one and then we are taking the modulus with the buffer size. The modulus is the rest of an integer division. When the position is at the end of the buffer array, it will be (49 + 1) % 50, which is zero. That wraps the array end to the array end for us.
If our buffer is full, then we increment the start counter of the buffer. That means, that we are ditching one character at the start of our buffer to add one at the end (which is what you want to do). (Note, that normally with ring buffers you don't want to throw away data, so you refuse to put more data into the buffer, when it is full).
Then we store the received character into our buffer and increment buffer_end like described above.
The above principle is also called circular FIFO buffer (First In First Out), though there are missing some function to a real FIFO buffer, that you don't need here.

Now, that we have a ring buffer, which gets filled with the data, we also need to implement a function to find a string in the buffer, meaning an equivalent to the String.indexOf() method. It might look something like this:
int find_string(char str[], const char search[]){
    uint8_t start = buffer_start;
    uint8_t search_pos = 0;
    uint8_t result_pos = -1;
    while(start != buffer_end){
        if(str[start] == search[search_pos]){
            if(search_pos == 0) result_pos = start;
            search_pos++;
            if(search[search_pos] == '\0') return result_pos;
        } else {
            result_pos = -1;
            search_pos = 0;
        }
        start = (start + 1) % BUFFER_SIZE;
    }
    return -1;
}

Note, that this implementation is only roughly tested, not thoroughly.

Hello, thank you so much for the detailed answer. I'm struggling to figure out what and how to put in the find_string() function. if(find_string(?, ?)) { ... }

Could you please provide the code for my specific case because I'm not sure how to implement it properly.

First parameter is the buffer, second is the string to search for. You can use it just like the String.indexOf() method.

https://i.ibb.co/bJ3kS9v/img.png I don't think this is supposed to happen. Am I doing something wrong?

If the if(is_uploading_book) { } doesn't have the find_string checking, it works fine. The thing is, I need a find_string checking in there.

There seems to be something else wrong. Are you sure, that you have the correct baudrate configured in the HC-05?

I used Craig's solution and it works perfectly. My main problem seemed to arise when in the if (is_uploading_book) { } part I tried to again check for a second tag (UPLOAD_BOOK_END). Anyways, it works. Thank you so much for your time and attention. If you know what was going on I'm curious to hear.

Sorry, I honestly don't know what happened there. Both solutions don't use String, which is a good thing. Good that you now have your working solution

Let us continue this discussion in chat.


text:
Serial communication by bluetooth hc-05
i am making a ultrasonic radar using stepper motor and ultrasonic sensor , and displaying the output over a software(processing 3) which looks like a radar ppi on display ...is it possible ot replace the usb cable with a bluetooth connection to send data (serial) instead of using a usb cable i want the setup to be remote ..i am using a instructable https://www.instructables.com/id/Acoustic-Radar-Display/ for coding i just need to know how to make it wireless over bluetooth ...just changing the com over processing 3 works or i need to do some changes in command mode of bluetooth

What have you tried?

radar does not use sound, it uses radio waves ... you are building a sonar

i have tried with a hc-05 without mking any changes to arduino code just power bluetooth and after loading code connect xt rx pins and just change com port over processing 3 ...i am just confused to do it with one so i tried all but not working

yes i am building a sonar kind of thing which just have a radar type display just ..its a scaled model to depict working of radar

If you use a Bluetooth Module like this, that has an SSP profile, it will show up as COM port on your windows machine.
Now if you want to use the Arduino's Hardware Serial (i.e. keep using Serial.print() but for Bluetooth) then you will connect the module like this:

Bluetooth HC06 TX to digital pin 0 (Arduino Rx)
Bluetooth HC06 RX to digital pin 1 (Arduino Tx)

But remember, you load your code using these pins too. Arduino has a "USB-to-Serial" IC on board that uses those two pins. So now two entities trying to use those same pins (U2S and BT) i.e. you will have to disconnect U2S connections:

The above image is a snippet from the Arduino schematic. One way to disconnect those connections is to remove those two resistors. But then again, next time you want to load your code, you won't be able to use USB cable anymore.
So, I will suggest you to use SoftwareSerial and choose any other two pins for Bluetooth Module and change in the code wherever you were communicating with the Processing using Serial.println(). replace that with SoftwareSerial println().

i am using a hc-05 ...bluetooth module because it can do both asa slave and master , hc-06 is a only slave type...do u want me to make my hc-05 as a slave and do this ...here dosent it should be master because it(bluetooth) is sending data  to pc(prosessing 3) ???

Your Arduino is Master, so Bluetooth should be a slave.

i a using hc 05 for the same purpose and it have SSP profile .....and i am using the hardware tx rx pins only ..i a using hc 05 for the same purpose and it have SSP profile .....and i am using the hardware tx rx pins only ..just to upload code disconnect them then reconnect then is the only change needed ...

i just wanted to know ...with just attaching the bluetooth to the project and using outgoing connection com in pc (it shows incoming and outgoing com) to which bt is connected ..is it possible to make it wireless ..for all this do i just need to connect the bluetooth at correct braud i.e.115200 in the above case and change the com port at the processing 3 as the outgoing com of bluetooth ...i just want to make the project wireless like no usb cable ..since it s a com connection i am asking can it be replaced with a bluetooth connection ...please help me i am stuck in here ...

please go through code once and see if i need some changes in the coding of project ..thank u regards..its is part of a project which i need to complete but i am not able to do it as i am new to coding and finding out the possibilities

Yes, it is possible. Just follow the connection that I mentioned in the Answer (D0, D1). In the code change the Baud Rate to 9600. Both in Arduino and Processing. HC-05 default baud rate is 9600.

i have tried but as soon as i put the TX Rx pins in hardware pins 0 and 1 ..the system stops ..i have changed the speed of HC-05 to 115200 via AT commands with 1 stop bit and 0 parity bit , AT+UART=115200,0,0...do i need to use software serials ..because the continuous "s" which r send to pc are using that connection or am i doing something wrong ...i cant use 9600 because thats too slow for the radar ... thank you for all ur help

When you connect your Bluetooth with Arduino using D0 and D1, is the USB cable from Arduino still connected to your PC?

yes it is connected ..i am like 1st running entire thing with usb and then give external power to arduino and then connect the bluetooth rx tx of HC-05 to arduino and then disconnect the usb cable..in this as soon as i connect tx rx pins to bluetooth the entire system stops  like the sweep stop over processing 3..which was running fine before this connection ..the usb is connected in this case as to get the sweep over processing 3 after this only i try to connect the rx tx and remove usb cable

Ok, the Arduino has a USB-to-Serial chip on board. And that is using D0 and D1. Without disconnecting those you won't be able to use those two pins. I think it is better to use the software serial. Choose any other two pins, connect Bluetooth there and wherever in the code you are sending something to the PC replace that with software serial.println()

I updated my answer too.

i have done changes in arduino ide as chaning all hard serials to software serials like serial.available to myserial.available(example) i changed every line with serial to myserial (myserial is my software serial)...and then connected the tx and rx of bluetooth changed the uart to 115200,0,0 for braud rate ....then paired the bluetooth with laptop saw the outgoing serial port of bluetooth (mine was com7) then changed the serial.list in processing 3 for the same (com7) port ..issues i am facing r (usb is not connected arduino is powered by a 9v battery through jack)

it shows the com port is busy ..sometimes it connects but the display displays the pings and the sweep for sometime ...like it wont work indefinitely ..not even for one complete sweep of radar ..and sometimes it just start too slow foe motor rotation ..but the biggest issue is the complete sweep thing ....to make it 360 i doubled the array at processing made additional graticules and increased the step count in arduino ide so basically i have got what i wanted but with the usb attached ...

to get it wireless i tried software serial and changes made were every serial event was chaned to software serial but its not working as desired .do i have to keep some serials as the original one and not change them to software serial ...only sending part need to be changed(azimuth direction distances ) or other things too like starting of the stepper at the click of switch and other serial.available events

do i have to create a separate port in processing or just changing the serial.list to the outgoing serial com of bluetooth is enough  (like this "Serial myBluePort;" while importing processing.serial) i am using the earlier created serial port the myPort for the same ..if i am not using it for usb wont just changing its serial.list should do the work


text:
Running commands from string
I have a string:
string s="digitalWrite(8,LOW);"

Is there any way to run it as a code?

Not an easy way, since you basically would need to write a C/C++ interpreter library for this. I don't know of such a library. Why do you need to do this? What are you trying to achieve?

To run commands that will be saved in external eeprom

Do you really have such complex programs to save there, that you need C syntax text there? Instead you could build your own command structure, which can be way easier to interpret. What commands do you need to save in the EEPROM?

@chrisl thank you, I forgot that I can do it like this

This is actually pretty simple:
if (s == "digitalWrite(8,LOW);") {
    digitalWrite(8,LOW);
}

Obviously, it will not work is s contains any other string... If you
want something more general, that is able to interpret a wide range of
possible commands, you will have to define a language, and write an
interpreter for that language. From the example you give, it seems you
would like your language to look like C++. This is most likely a bad
design choice. If you want an interpreter that understands the whole C++
language: forget it. You will never fit something this big into an
Arduino Uno.
Here is, for inspiration, a very simple interpreter I
wrote that understand the following commands:
mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it a basis for writing your custom interpreter. Otherwise
you can do a Web search for “Arduino interpreter”: you should be able to
find interpreters implementing a wide variety of languages, including
compact binary languages (Firmata), Forth (another one),
Lisp, Basic, and even a C-like language.


text:
How do I make a character array scanner properly?
I start with this:
char delay_chars[10];

then I have a stream of incoming characters that I need to assign like this:
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e']

I can do that, but then more characters come in so I need it like this:
[' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ']
['l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a']
['o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n']
['v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd']
['e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ']
[' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c']
['p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a']
['i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k']
['e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k', 'e']

You get the idea. I don't know how I can remove the first character of a char array (like I do with a String, remove(0, 1)) and I don't know how to add a new element at the end.
If I had to guess, I'd make a loop that will reassign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

You can do it this way, but there's a better way that's faster and a lot less work.  You want something called a circular buffer.  Look that up and see if it doesn't do what you want differently but better.

If I had to guess, I'd make a loop that will reasign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

Yep, that's pretty much it...
Here's how I do it:
char data[10];

if (Serial.available()) {
    char inch = Serial.read();
    for (int i = 0; i < 9; i++) {
        data[i] = data[i+1];
    }
    data[9] = inch;
}

Every incoming character gets added to the end of the array after everything else has been shuffled down one place.

It's pretty frustrating that in C you have to do all array stuff yourself

There are functions that can do it for you, but it's not really worth using them for such a simple operation. The for loop could be done with memmove(data, data+1, 9);

@NovaliumCompany By the way, I just corrected a typo.

Ok. I now have another annoying problem... my Arduino Uno seems to start to spit jibberish when I do some stuff... Do you mind helping me? (in a chatroom)

@NovaliumCompany Jibberish usually means you're overrunning a buffer. Maybe you're printing an array with no terminating NULL character?

Here's what I'm doing https://textuploader.com/168i3 The Serial.write starts normal and then turns into Jibberish. Here's more info about the problem: https://justpaste.it/3wobv

You can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.
Here are the library's features:

This library:

can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
works with "software-serial" libraries
is non blocking
uses packet delimiters
uses consistent overhead byte stuffing
uses CRC-8 (Polynomial 0x9B with lookup table)
allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 255 bytes)
can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  myTransfer.txBuff[0] = 'h';
  myTransfer.txBuff[1] = 'i';
  myTransfer.txBuff[2] = '\n';

  myTransfer.sendData(3);
  delay(100);
}

Example RX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");
    Serial.println(myTransfer.status);
  }
}

You can easily edit the above example code to transfer ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e'] instead of ['h', 'i', '\n'].


text:
With what can I replace this for loop so my Arduino doesn't spit jibberish?
I have this:
for (int i = 0; i < (DELAY_SIZE - 1); i++) {
   if (check_tag_in_char(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
       tag_pos = 0;
       Serial.println("Uploaded");
       is_uploading_book = false;
   }
}

where
#define DELAY_SIZE 50
const char* BOOK_UPLOAD_END_TAG = "(__BOOK_UPLOAD_END__)";
char delay_chars[DELAY_SIZE];

int check_tag_in_chars(char a, const char* TAG_STR) {
   if (a == TAG_STR[tag_pos]) { tag_pos++; } else if (a == TAG_STR[0]) { tag_pos = 1; } else { tag_pos = 0; }
   if (TAG_STR[tag_pos] == '\0') {
      return true;
   } else {
      return false;
   }
}

The for loop above with the check_tag_in_chars check seems to make my Arduino spit jibberish on Serial.write() (which you can see in the full code).
I suppose the for loop is somehow overloading the Arduino.
The Serial.write() starts normal and then turns into jibberish like that:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla est purus, ultrices in porttitor
  in, accus⸮o⸮a⸮a⸮nct⸮oto⸮ou⸮ubt⸮ue⸮tl⸮ei⸮at⸮e⸮i⸮rm⸮⸮tlu⸮or⸮tatcsu⸮om⸮lu⸮oaess⸮vi⸮pdteea⸮aestp⸮r⸮tda⸮lcp⸮ddt⸮ir⸮eo⸮oe⸮i⸮g⸮u⸮aacdeu⸮bt.Qiu⸮pdtiu⸮l
  g⸮ie⸮ur.Csveamei⸮n⸮ievtumtp⸮vi⸮d⸮eil⸮oi⸮ruiusbeu⸮rs⸮l⸮ae⸮ai⸮t,⸮⸮oe⸮om
  l⸮cdo⸮aesua⸮i⸮iin⸮⸮ab⸮e⸮vil⸮⸮u⸮u⸮an⸮fiiamssa. C⸮oi⸮tque petu⸮⸮ai⸮sptitmts⸮st⸮ril⸮u⸮tcsu⸮lie⸮t⸮nrnumuscg⸮oa⸮vu⸮vr⸮uci⸮l⸮g⸮oinm⸮msi⸮aq⸮ptb⸮tmn⸮i⸮rrn⸮oe⸮aerrdlsm.Ierbeu⸮gtslu,n⸮aisnl⸮ott
  t.C⸮oi⸮tu⸮etu⸮⸮ai⸮sptit⸮ns⸮st⸮icu⸮s⸮

Here's the full code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX, TX

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

const char* BOOK_UPLOAD_START_TAG = "(__BOOK_UPLOAD_START__)";
const char* BOOK_UPLOAD_END_TAG = "(__BOOK_UPLOAD_END__)";
int tag_pos = 0;
char c;
bool is_uploading_book = false;

#define DELAY_SIZE 50
char delay_chars[DELAY_SIZE];
int update_count = 0;

void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        if (is_uploading_book) {
          Serial.write(c);
          if(update_count < DELAY_SIZE) {
            delay_chars[update_count] = c;
            update_count++;
          } else {
            for (int i = 0; i < (DELAY_SIZE - 1); i++) {
                delay_chars[i] = delay_chars[i + 1];
            }
            delay_chars[DELAY_SIZE - 1] = c;
            // Checking if the end tag is in the delay_chars
            for (int i = 0; i < (DELAY_SIZE - 1); i++) {
              if (check_tag_in_chars(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
                tag_pos = 0;
                Serial.println("Uploaded");
                is_uploading_book = false;
              }
            }
          }
        } else {
          if (check_tag_in_chars(c, BOOK_UPLOAD_START_TAG)) {
            tag_pos = 0;
            Serial.println("Starting");
            is_uploading_book = true;
          }
        }
    }

}

int check_tag_in_chars(char a, const char* TAG_STR) {
  if (a == TAG_STR[tag_pos])
    { tag_pos++; }
  else if (a == TAG_STR[0])
    { tag_pos = 1; }
  else
    { tag_pos = 0; }

  if (TAG_STR[tag_pos] == '\0') {
    return true;
  } else {
    return false;
  }
}

Is there something that is overloading and torturing the Arduino? Are there any alternatives to go about the problem that will not create this problem?
NEW: It turns out that as I decrease the DELAY_SIZE value, the jibberish slowly starts to look normal. Somehow that for loop tortures the Arduino (and it's not so much the for loop but the check it's done in it)
NEW NEW: I tried looping a loop and it seems that making extensive loops overloads the Arduino and it starts jibberish. Is this normal or there's something with my Arduino?
NEW NEW NEW: If my void loop() looks like this:
void loop(){
   if (BTserial.available()) {
      c = BTserial.read();
      Serial.write(c);
      for (int i = 0; i < (DELAY_SIZE - 1); i++) {
         if (check_tag_in_chars(delay_chars[i], BOOK_UPLOAD_END_TAG)) {
            tag_pos = 0;
            Serial.println("Uploaded");
            is_uploading_book = false;
         }
      }
   }
}

The problem of jibberish persists (the jibberish is less but it's still jibberish). The fact that I'm looping through the check_tag_in_chars 50 times every new character is torturing the Arduino.
I don't know what to do.

You didn't read my typo correction in your other correction.                 delay_chars[DELAY_SIZE - 1] = c; } should be } delay_chars[DELAY_SIZE - 1] = c;

@Majenko Sorry, fixed it (I got the delay_chars[DELAY_SIZE - 1] = c; out of the loop) but the problem stays. I did some debugging and the jibberish issue originates from the loop I've stated above.

@Juraj Please take a look at the full code.

I suspect that the problem is actually SoftwareSerial being a pile of rancid badger vomit.

or the BT module is on different baud rate

@Juraj How can that be? When the for loop is gone, everything works fine.

I just checked the HC-05 baud rate through AT, it's 9600.

If it helps, I has problems sending data through SoftwareSerial with the HC05 but receiving it was fine. Hardware serial never had this problem for me

"rancid badger vomit"? Is that a technical term? :)

I had a hard time trying to understand, why you use the delay_char array. I did not succeed. What is the intention of it? Why do you not check each character as it comes in from the bluetooth module? Do you need it for future uses? With the shift operation you have a good chance to create failure code. e.g. You shift only the chars until DELAY_SIZE - 2 because of the < operator (you do not use a <=- Then you write over the last character in the array. That could be problematic;-).

I would also check the charset of the text you send over bluetooth. Is it UTF 8 or a Windows charset or another non ASCII code?


text:
Arduino Measuring Microwave Leakage
I want to measure if my microwave has a leakage using Arduino. Ideally, I would like to get the exact number measured by mW/cm2 (similar to HT-M2 devices). Any advice which Arduino module can do it?

No Arduino can do it. Instead a microwave detector will do it, and the Arduino will control it and process the data.

@Majenko, that's what the OP asked. "Any advice which Arduino module can do it?". They are looking for Arduino compatible components that will measure microwave radiation. Personally, I have no idea if there are microwave measurement devices that have serial interfaces that are easy to connect to an Arduino. I will say that a quick search on HT-M2 revealed dedicated Microwave leakage detectors for less than $15 US. You're not going to compete with that.

@Davithbul, post a link to a microwave detector datasheet and someone here will be able to tell you if the detector is arduino compatible

@DuncanC you are right price wise HT-M2 is not expensive, but for my use case, I need to monitor constantly using some microcontroller - Arduino or Raspberry Pi.

@jsotola I was not able to find the datasheet for HT-M2, but I will still look for it. Thank you for advice.

you asked about a module that can be used with an Arduino ... the HT-M2 is not a module, it is a self contained device

@jsotola Right, I meant maybe it would be possible to understand which exact module does HT-M2 use and use the same module to connect from Arduino.

it probably does not use a standalone module that you could extract from the device ... it probably contains a "front end" of a radio receiver ... just an antenna, a tuned circuit and a demodulator ... the output of the circuit is a voltage level that varies with signal strength


text:
Summarizing a repetitive code in a void loop function
How can I summarize dozens of code lines for blinking a red LED in Arduino Rich Shield? Is there a way or method to eliminate at least half of the code for repetitive scenarios?
const int redPin = 4;

void setup()
{
 pinMode(redPin, OUTPUT);
}

void loop()
{
  digitalWrite(redPin, HIGH);
  delay(250);
  digitalWrite(redPin, LOW);
  delay(250);
  digitalWrite(redPin, HIGH);
  delay(250);
  digitalWrite(redPin, LOW);
  delay(250);
  digitalWrite(redPin, HIGH);
  delay(250);
  digitalWrite(redPin, LOW);
}

void loop()
{
  digitalWrite(redPin, HIGH);
  delay(250);
  digitalWrite(redPin, LOW);
  delay(250);
}

I'm not quite sure what you're after but this is shorter and would get you equivalent results.  Since loop is going to repeat anyway, there's no need to repeat yourself inside loop.
Per the comments, not that this is particularly useful...
const int redPin = 4;

int counter = 0;

void setup()
{
 pinMode(redPin, OUTPUT);
}

void loop()
{
  if(counter < 4) {
     digitalWrite(redPin, HIGH);
     delay(250);
     digitalWrite(redPin, LOW);
     delay(250);
     counter++;
  }
}

ok I didn't know that, but what if I wanted 3 to 5 blinks and then stop red LED? would that result change in code?

If you want to stop it (and don't do anything else), move the code to setup which is only executed once.

thank you for your reply, but I want it in a loop function, to stop it from blinking after 3 to 5 blinks for instance

The point of loop is that it keeps repeating.  If you want it to stop after so many blinks then you need to have a variable that starts out at zero and adds one every time the loop runs.  Put the part that blinks the light inside an if statement that checks to see if that number is below whatever limit.

Aha now I understand the logic behind stopping a certain loop, thank you so much Delta, that was of a great help from you!


text:
WiFi.begin doesn't work with ArduinoJson's const char* output
I'm using ArduinoJson to parse a file full of JSON strings that contain the SSID and password for the registered networks. I have a little web interface that runs in soft AP mode so you can scan for networks and add them to the file. Adding networks to the file works fine, but reading them back and using them as input for WiFi.begin doesn't work. It moves to status code 1, which means it failed to find a network with that SSID.
I have compared the value of the result of const char* ssid = networks[network]["ssid"]; with const char* _ssid = "MySSID"; using strcmp and it returns 0, so I can't figure out why it's not working. It works if I replace networks[network]["ssid] with my SSID (though I need to replace the password with the string literal as well, otherwise it stays on status code 6, disconnected).
I can't figure out what it is about ArduinoJson, but it seems that the result of grabbing a string doesn't return a string that is formatted correctly for WiFi.begin, but it satisfies strcmp?
Edit:
I modified the code quite a bit in an effort to get it to work. I am no longer passing the ArduinoJson object, I'm now passing a struct with the data, and it still doesn't work. Is this the work of some advanced c++ constants/pointers stuff that I don't seem to understand?
main.cpp:
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include <SPIFFS.h>
#include <vector>
#include <elapsedMillis.h>

#include "config.h"
#include "restserver.h"
#include "scanwifiserver.h"

AsyncWebServer *Server = new AsyncWebServer(80);

ScanWifiServer *scanWifi;
RestServer *restServer;

struct Network {
    const char* ssid;
    const char* password;
};

std::vector<Network> readAP(fs::FS &fs) {
    //fs.remove("/ap.txt");
    File file = fs.open("/ap.txt");
    std::vector<Network> networks;
    if (!file) {
#ifdef DEBUG
        Serial.println("Failed to open file for reading");
#endif
        return networks;
    }

    while (file.available()) {
        DynamicJsonDocument n(JSON_CAPACITY);
        auto s = file.readStringUntil('\n');
        deserializeJson(n, s);
        struct Network network = {n["ssid"], n["password"]};
        networks.push_back(network);
        Serial.println(networks.back().ssid);
    }

    file.close();
    return networks;
}

void setup() {
#ifdef DEBUG
    Serial.begin(BAUDRATE);
    delay(2000);
#endif

    SPIFFS.begin();
    auto networks = readAP(SPIFFS);
    if (networks.size() > 0) {
        Serial.println("Networks:");
        int network = 0;
        Serial.println(networks.size());
        while (WiFi.status() != WL_CONNECTED && network < networks.size()) {
            const char* ssid = networks[network].ssid;
            const char* password = networks[network].password;
            Serial.printf("%s, %s\n", ssid, password);

            WiFi.begin(ssid, password);

            while (WiFi.status() != WL_CONNECTED) {
                if (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL)
                    break;
                delay(500);
                Serial.print(WiFi.status());
            }
            Serial.println("");
            network++;
        }
        if (WiFi.status() == WL_CONNECTED) Serial.println("Connected");
        else networks.clear();
    }
    if (networks.size() == 0) {
        Serial.println("Starting ScanWifiServer");
        WiFi.mode(WIFI_AP);

        scanWifi = new ScanWifiServer(Server);

        Server->begin();

        MDNS.begin("grow");
        MDNS.addService("http", "tcp", 80);
    }
}

void loop() {}

add WiFi.persistent(false); and WiFi.setAutoConnect(false)

I found the solution myself. I switched from using struct Network network = {n["ssid"], n["password"]}; to declare the struct and const char pointers to using char arrays and strcpy
struct Network network;
strcpy(network.ssid, n["ssid"]);
strcpy(network.password, n["password"]);

Seems like the pointers were getting freed or something right at the same time that I tried to use the value to connect to the network?

std::vector<JsonDocument> doesn't store a copy of the complete document, but just a copy of the internal pointers of JsonDocument. Therefore, at the time you use the value, it points to an invalid location.
This is clearly a bug, that's why I removed the copy constructor of JsonDocument, but the change hasn't been published yet.
You can fix your program by replacing the std::vector<JsonDocument> with std::vector<DynamicJsonDocument>.

Thanks for the response, though I modified my code a bunch and it still doesn't work. Do you know what's going on?


text:
Send data from UNO to MQTT through NodeMCU 12E - problem
i am trying to send data from ACS712 sensor which is connected to UNO (3 sensors). Everything works fine on UNO, but when I send only one value from UNO through NodeMCU 12E to MQTT server, it shows totally different number (UNO gives 0.25, mqtt shows 0 or 9 or something third). For connection btwn UNO and NodeMCU 12E i was using this picture (attached).
Here is code for UNO:
#include "ACS712.h"
char prva[5];
char druga[5];
char treca[5];
char cetvrta[5];
ACS712 sensor1(ACS712_30A, A0);
ACS712 sensor2(ACS712_30A, A1);
ACS712 sensor3(ACS712_30A, A2);
unsigned long last_time =0;
unsigned long current_time =0;
float Wh1 =0 ;
float Wh2 =0 ;
float Wh3 =0 ;
float Wh4 =0 ;
void setup() {
  Serial.begin(9600);
  sensor1.calibrate();
  sensor2.calibrate();
  sensor3.calibrate();
}

void loop() {
  float V = 220;
  float I1 = sensor1.getCurrentAC();
  float I2 = sensor2.getCurrentAC();
  float I3 = sensor3.getCurrentAC();
// Serial.println(I);
  float P1 = V * I1;
  float P2 = V * I2;
  float P3 = V * I3;
  float U = P1 + P2 + P3;
  last_time = current_time;
  current_time = millis();
   Wh1 = Wh1+  P1 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh1, 4, 2, prva);
   Wh2 = Wh2+  P2 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh2, 4, 2, druga);
   Wh3 = Wh3+  P3 *(( current_time -last_time) /3600000.0) ;
   dtostrf(Wh3, 4, 2, treca);
   Wh4 = Wh4+  (P1 *(( current_time -last_time) /3600000.0))+ (P2 *(( current_time -last_time) /3600000.0))+  (P3 *(( current_time -last_time) /3600000.0)) ;
   dtostrf(Wh4, 4, 2, cetvrta);
  Serial.print( " (1) W: " );
  Serial.print(prva);
  Serial.print("   ");
  Serial.print( " (2) W: " );
  Serial.print(druga);
  Serial.print("   ");
  Serial.print( " (3) W: " );
  Serial.print(treca);
  Serial.print("   ");
  Serial.print( " (4) W: " );
  Serial.print(cetvrta);
  Serial.print("          ");
  Serial.print(P1);
  Serial.print("  W/h (1)");
  Serial.print("      ");
  Serial.print(P2);
  Serial.print("  W/h (2)");
  Serial.print("      ");
  Serial.print(P3);
  Serial.print("  W/h (3)");
  Serial.print("          ");
  Serial.print(U);
  Serial.print("  W/h (1,2,3)");
   delay(10000);
  Serial.println();

Here is code for NodeMCU 12E: (here i want to send only one data named cetvrta.
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WLAN_SSID       "Qwerty"
#define WLAN_PASS       "123456"
char cetvrta[5];
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "werty"
#define AIO_KEY         "12345"

WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish Power = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/power");
//Adafruit_MQTT_Publish bill = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/bill");
void MQTT_connect();

void setup() {
  Serial.begin(9600);
  delay(10);
  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

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

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

 int i=0;
 float watt1;
 if(Serial.available() > 0 ){
   delay(1000); //allows all serial sent to be received together
    while(Serial.available() && i<6) {
     cetvrta[i++] = Serial.read();
    }
    cetvrta[i++]='\0';
  }

 watt1 = atof(cetvrta);
  Serial.print(F("\nSending Power val "));
  Serial.println(watt1);
  Serial.print("...");

  if (! Power.publish(watt1)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

delay(3000);
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

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


text:
connected between 2 arduino
i want to connect  SPI 2 arduino master and slave through the MUX , to write  and read in external memory , when the master write in memory slave read .
pls help .
code to master
#include <SPI.h>
//-------FM------------------
#define WENB 0x06
#define RDSR 0x05
#define WRSR 0x01
#define PPROGRAM 0x02
#define SERASE 0x20
#define BERASE 0xd8
#define READ 0x03
#define RDSCUR 0x2B
#define CERASE 0x60//or 0xC7

//------------Specify the address-----------
int address = 0x00ff0000;
byte x, Y;
int IN = 5;
int SS1 = 9;
/*char data[]=("don't be afraid ");
char recived[15];*/
//--------------------------
void setup() {
    //------------------------------------------
    // pinMode(EN,OUTPUT);
    pinMode ( SS, OUTPUT ); //ss pin 10
    pinMode ( SS1, OUTPUT );
    digitalWrite ( SS1, HIGH );
    pinMode ( IN, OUTPUT );
    digitalWrite ( IN, LOW ); // MUX connect A
    //digitalWrite(CS,low);
    Serial.begin ( 9600 );
    SPI.begin();//start the SPI connection with the flash memory
    SPI.setClockDivider ( SPI_CLOCK_DIV8 );
    SPI.setBitOrder ( MSBFIRST );
    digitalWrite ( SS, HIGH );
    delay ( 10 );
    //-------erase the sector--//-----------
    digitalWrite ( SS, LOW );
    SPI.transfer ( WENB );
    digitalWrite ( SS, HIGH );
    //-------------------------------------
    digitalWrite ( SS, LOW );
    SPI.transfer ( SERASE );
    SPI.transfer ( ( address >> 32 ) & 0xff );
    SPI.transfer ( ( address >> 16 ) & 0xff );
    SPI.transfer ( ( address >> 8 ) & 0xff );
    SPI.transfer ( address & 0xff );
    digitalWrite ( SS, HIGH );
    delay ( 5000 );
    //------------------------------------------
    //Serial.println("okay fine")
    //-----Program Data Into Memory Array-----.
    //-----------interrupts the slave----------
    /* digitalWrite(SS1,LOW);
     SPI.transfer(0xff);//are you there?
     digitalWrite(SS1,HIGH);
     delay(1000);

     digitalWrite(IN,HIGH);*/
}

void loop()

{
    char c;
    int i = 0;
    char data[] = "Hello!:";
    char recived[7];
    byte x;
    //----------Enable the write in the memory-----.
    digitalWrite ( SS, LOW );
    SPI.transfer ( WENB );
    digitalWrite ( SS, HIGH );
    delay ( 20 );
    //-----Program Data Into Memory Array-----.
    digitalWrite ( SS, LOW );
    SPI.transfer ( PPROGRAM );
    SPI.transfer ( ( address >> 32 ) & 0xff );
    SPI.transfer ( ( address >> 16 ) & 0xff );
    SPI.transfer ( ( address >> 8 ) & 0xff );
    SPI.transfer ( address & 0xff );

    for ( int i = 0; i < sizeof ( data ); i++ ) {
        SPI.transfer ( data[i] );
        // Serial.print(data[i]);
    }

    // disable Slave Select
    digitalWrite ( SS, HIGH );
    //--------------------------------------------
    delay ( 1000 );
    //--------------------------- ----------
    i = 0;
    Serial.print ( "It's okay saved: " );

    while ( data[i] != NULL ) {
        Serial.println ( data[i] );
        i++;
    }

    // delay(100);
    //-----------interrupts the slave----------
    digitalWrite ( SS1, LOW );
    SPI.transfer ( 0xff ); //are you there?
    digitalWrite ( SS1, HIGH );
    delay ( 1000 );
    digitalWrite ( IN, HIGH ); // MUX connect B
}

code to slave
#include <SPI.h>
//-------FM------------------
#define WENB 0x06
#define RDSR 0x05
#define WRSR 0x01
#define PPROGRAM 0x02
#define SERASE 0x20
#define BERASE 0xd8
#define READ 0x03
#define RDSCUR 0x2B
#define CERASE 0x60//or 0xC7

//------------Specify the address-------------
int address = 0x00ff0000;

int SS1 = 9;
char data[] = "Hello!:";
char buff[7];

byte slave;
volatile bool process;
//----------------config slave----------------
void setup() {
    //pinMode(IN,OUTPUT);
    pinMode ( SS, OUTPUT ); //SS pin 10
    pinMode ( MISO, OUTPUT );
    pinMode ( SS1, INPUT );
    pinMode ( MOSI, INPUT );
    //--------------------------------------------------
    Serial.begin ( 9600 );
    ///SPCR |= bit (SPE);
    SPI.begin();//start the SPI connection with the flash memory
    SPI.setClockDivider ( SPI_CLOCK_DIV8 );
    SPI.setBitOrder ( MSBFIRST );
    // digitalWrite(SS,HIGH);
    //-------------master interrupts the slave----------------------------------------------
    // now turn on interrupts
    // SPCR |=bit(SPIE);
    //SPCR |=bit(SPE); //set SPE bit at the SPCR(spi control register) to enable SPI
    SPI.attachInterrupt();
}

ISR ( SPI_STC_vect ) {
    slave = SPDR;

    if ( slave = 0xff ) {
        pinMode ( MISO, INPUT );
        // pinMode(SS1,INPUT);
        pinMode ( MOSI, OUTPUT );
        //digitalWrite(IN,HIGH);
        digitalWrite ( SS, LOW );
        SPI.transfer ( READ );
        SPI.transfer ( ( address >> 32 ) & 0xff );
        SPI.transfer ( ( address >> 16 ) & 0xff );
        SPI.transfer ( ( address >> 8 ) & 0xff );
        SPI.transfer ( address & 0xff );

        for ( int n = 0; n < sizeof ( data ); n++ ) {
            data[n] = SPI.transfer ( 0 );
            Serial.print ( data[n] );
        }

        digitalWrite ( SS, HIGH );
    }
}

You mean you want one Arduino to be able to access the memory of another over SPI? If so, what part are you having problems with? You have told us what you want to do, and you have dumped code on us, but you haven't told us what is actually happening (or not happening) and what you need help with.

I'm afraid you have to clarify your question. Do you mean you want to connect two Arduinos to on external memory? And one Arduino drives a MUX to decide which Arduino is allowed to access the ext. memory? Which MUX do you use? How do you plan to negotiate which Arduino can have access to the memory? Wouldn't it be a better idea to let one Arduino access the memory and the other sends its data to that "master" Arduino?

what my want to do! okay , i have 2 arduino , i program one to be master to control in my project and write in external memory , and anther to be slave and read from external memory , through MUX   to which who can connect with memory , and i control in MUX by  the master. my problem  the slave can't know when exactly read from memory . I used MUX ADG774 and the type of memory MX25L25735E. you can see my code . I hope now be clear

Then you need to have some form of communication between the two Arduinos so that the master can tell the slave when it's allowed to read from the external memory. And in that case you may as well just forget sharing the memory and just use that connection to send data from one Arduino to the other.

The master and slave connected by interrupt  command . what do you think ?

As far as I understand it, SPI library in Arduino supports SPI Master mode only. When you call SPI.begin() in your slave code, it "initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high". So your pinMode(MOSI, INPUT); is override. Read the source code for better understanding of the library.

Not true - Arduino can be SPI slave also.  Nick Gammon has example here  https://www.gammon.com.au/spi  In this case tho, "slave" only indicate another user of the memory.

May be you right-   ("slave" only indicate another user of the memory ) but here I used MUX to control in slave. okay may be I don't need to MUX if I have 2 arduino . But now I want to use the MUX .another way?

Having a line from Arduino 1 to Arduino 2 to indicate that Arduino 2 should do something is sufficient.
Simple way: a line that is an input on both sides with internal pullups turned on.  Both sides monitor it.
When Arduino 1 wants to write, it checks to make sure the line is high, then it makes its pin an output and pulls it low, and when done releases it by going back to an input (using pinMode() command).
When Arduino 2 see the low, it waits for it to go high, then makes its input and output and pulls it low until it is done reading.
Arduino 1 sees the low and holds off on any writing until it goes back high again.
This is known as arbitration, and is an example of one simple method.

okay-  when or how can arduino 2 know arduino 1 finished write ?

Arduino 1 puts the common pin back to an input, which lets it go High.


text:
Interrupting a servo sweep with a force sensor
this is my first time dealing with arduinos and I have a school assignment. I have a servo and a force sensor. When "1" (a character, not an integer) is typed in the serial monitor, the servo needs to rotate 180 degrees but can be interrupted when the force sensor sends a value over let's say 300. And when "0" is typed in, the servo goes back to its initial position.
I have been trying really hard figuring this out.
I basically need to exit a loop when the analog value exceeds 300.
here's my code:
#include <Servo.h>
Servo myservo;

int initpos; //initial position of the servo before the sweep (this doesn't change)
int angle; //used to store the servo angle value (this changes)
char code; //the value entered in the serial monitor
int force; //value of the analog force sensor

void setup()
{
  initpos = 10;
  Serial.begin(9600);
  myservo.attach(4);

  myservo.write(170); // makes the servo sweep(absolutelly useless for my project but I left it there)
  delay(500);         //
  myservo.write(10);  //
  delay(500);         //

  code = Serial.read();

}

void loop()
{

  if(Serial.available())
  {

    angle = initpos;
    force = analogRead(A1);
    Serial.println(force);

    for(angle = 0; angle < 180; angle += 1)
    {
      if (code == "1" and force <= 300)
      {
        angle += 1;
        Serial.print(code);
        myservo.write(angle);
      }

      else if(code == "0")
      {
        myservo.write(initpos);
      }
    }

  }
}

any help is deeply appreciated and if there is already a topic on this please redirect me to it

ask yourself this when is code in  setup() executed?   and  when is code in  loop() executed?

I've written this code without access to a compiler,
so there might be errors. Use it as an idea how to solve the quest. Hopefully the comments are helpful. Don't hesitate to ask if you do not understand or correct me if you see an error.
#include <Servo.h>

Servo myservo;

// end positions of the servo
// declared as constant values
const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;

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

  myservo.attach(4);
  // move the servo to minPos
  // or whatever you want/need
  servoAngle = minPos;
  myservo.write( servoAngle );

  // PPK: keep code as simple as possible -> sweep removed

  // PPK: removed - this makes no sense here
  // code = Serial.read();
}

void loop()
{
  // PPK: here you check if data is available (I added "> 0")
  if( Serial.available() > 0 )
  {
    // PPK: but you did not read the data
    // Let's do it
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      // only "0" and "1" are valid codes
      code = newCode;
    }
  }

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      servoAngle--;

      // PPK: the next line is only necessary if you want the
      // servo to go towards the min position
      // if a force > 300 is detected
      // remove the line if you wish to
      // hold the servo at the position where
      // the force exceeds 300
      code = '0':
    }
    else
    {
      servoAngle++;
    }
    myservo.write( servoAngle );
  }
  // a little delay to slow down the servo
  // remove it if you want
  delay( 10 );
}

EDIT
If you intend to stop the servo if force > 300, you can add a flag that indicates the exceptional state.
#include <Servo.h>

Servo myservo;

const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;
int flagServoStopped = 0;

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

  myservo.attach(4);
  servoAngle = minPos;
  myservo.write( servoAngle );
}

void loop()
{
  if( Serial.available() > 0 )
  {
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      code = newCode;
    }
  }

  if ( flagServoStopped == 1 && code == '1' )
  {
    // The servo is frozen as long as the stop flag is set and
    // you have not entered a '0'.
    // leave the loop
    return;
  }

  // in case `code = '0'`, reset the flag if it is set.
  flagServoStopped = 0;

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      flagServoStopped = 1;
    }
    else
    {
      servoAngle++;
      myservo.write( servoAngle );
    }
  }
  delay( 10 );
}

Hi thanks for your help this is great! (idk if you saw my previous comment it was missleading). Unfortunately the servo is expected to stop when force > 300 and wait for 0

@Kiz0 I've changed the code according to your last comment.

Thank you for your help! This works perfectly and has saved me hours in my project! :)


text:
Esp8266 SD card read from inside of class
This is now my 3rd attempt at being able to read this sd card from within the Esp8266webserver.
I have made a class WebServer, and would like my sd card to contain my site.
What throws me off, is I am able to access the SD card everywhere with the exception of inside of the
.on callbacks.
I can read from/write to the sd card from Everywhere except for inside of a call back. What makes things even more odd, if I init my sd card using SD.begin(0) inside of the call back, it ALSO fails, That really is confusing. For somereason I can't get SD access inside of the callback.
Any ideas or suggestions would really really be appreciated.
so:
void WebServer::handlers(){
  // THIS WORKS!!!!!
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  // END THIS WORKS!!!!

  server.on("/", [this](){ sayHello(); }); // <- HERE IS WHERE THE TROUBLE STARTS!!!

  server.begin();
}

Here is what isn't working, i have removed some code to make it more easy to see:
void WebServer::sayHello() { //<- HERE IS THE CALLBACK, This always fails
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }

  server.send(200, "text/plain", "hello from esp8266!");
}

void WebServer::handlers(){
  server.on("/", [this](){ sayHello(); }); // <- HERE IS THE SETUP FOR THE CALLBACK (TROUBLE HERE)
  server.begin();
}

Here is my full code for reference:
#include <ESP8266WebServer.h>
#include "webserver.h"
#include <SD.h>

WebServer::WebServer(int n) { //, Storage*& storage
  ESP8266WebServer server(n);
  if (!SD.begin(0)) {
      Serial.println("SD initialization failed!");
  } else {
    Serial.println("SD initialization success!");
  }
}

void WebServer::sayHello() {
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  server.send(200, "text/plain", "hello from esp8266!");
}

void WebServer::handlers(){
  File myFile;
  myFile = SD.open("/test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }

  server.on("/", [this](){ sayHello(); });
  // server.onNotFound(handleNotFound(server));
  server.onNotFound([this, SD]() {
    handleNotFound();
  });
  server.begin();
}

void WebServer::handleClients() {
  server.handleClient();
}

bool WebServer::stream(File dataFile, String dataType) {
  return server.streamFile(dataFile, dataType) != dataFile.size();
}

void WebServer::writeFile(String message) {
  File myFile;
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    myFile.println(message);
    myFile.close();
  }
}

bool WebServer::loadFromSdCard(String path) {
  Serial.print(path);
  String dataType = "text/plain";
  if (path.endsWith("/")) {
    path += "index.htm";
  }
  if (path.endsWith(".src")) {
    path = path.substring(0, path.lastIndexOf("."));
  } else if (path.endsWith(".htm")) {
    dataType = "text/html";
  } else if (path.endsWith(".css")) {
    dataType = "text/css";
  } else if (path.endsWith(".js")) {
    dataType = "application/javascript";
  } else if (path.endsWith(".png")) {
    dataType = "image/png";
  } else if (path.endsWith(".gif")) {
    dataType = "image/gif";
  } else if (path.endsWith(".jpg")) {
    dataType = "image/jpeg";
  } else if (path.endsWith(".ico")) {
    dataType = "image/x-icon";
  } else if (path.endsWith(".xml")) {
    dataType = "text/xml";
  } else if (path.endsWith(".pdf")) {
    dataType = "application/pdf";
  } else if (path.endsWith(".zip")) {
    dataType = "application/zip";
  }
  File dataFile = SD.open(path.c_str());
  if (dataFile.isDirectory()) {
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }
  if (!dataFile) {
    return false;
  }
  if (server.hasArg("download")) {
    dataType = "application/octet-stream";
  }
  Serial.print(dataFile.size());
  Serial.print("About to send it!");

  while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
    Serial.print("Returned too little data");
  }
  dataFile.close();
  return true;
}

void WebServer::handleNotFound() {
  Serial.print(server.uri());
  if (loadFromSdCard(server.uri())) {
    return;
  }
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

Also, I want to add, I am seeing this message while compiling. Because I can access the files in other places, I have been ignoring it, but I am seeing:
extern SDClass SD;

                ^

C:\Users\kevin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SD\src/SD.h:206:16: note: 'SDClass SD' declared here

When you say it "fails" or "doesn't work", what actually happens?  Is it reading gibberish?  Is it printing the error message?  Is it failing to compile?  What's going on?

ahh, sorry, The exact thing that happens is the card initializes i get the "SD initialization success!" message from line 10 of the full code. however, I get the error message from the result of myFile = SD.open("/test.htm"); saying: "error opening test.txt"

Have have SD.open("test.htm") and SD.open("/test.htm"). Don't know if the slash matters...

@simSon, I have, I acutally just changed that as It was something I was testing. By moving the read into ANY part of this other than a callback, then it works.... it is just inside of the call back where it fails, I think it has something to do with the callback and I just don't understand this enough to know what is wrong

You could try to make void WebServer::sayHello() a static member if possible


text:
Having issue with a redeclaration as a different kind of symbol
Been struggling with this for a few days and I suspect that i have several issues but I cannot find them.
Project: Need a serial count that counts by 5-50 and a button interrupt should trigger a display of the current time and then continue counting.
Issue: Cannot complete compiling because my "void rtcTime()" is saying I am redeclared as different kind of symbol.
Any help the community can provide is greatly appreciated.
Code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"
#include <Wire.h>

RTC_DS1307 rtc;

int count = 5;
int rtcTime = 0;
int pin = 0;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup (){

  pinMode(2, INPUT);

  rtc.begin();

  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(9600);

  if (! rtc.begin()) {
   Serial.println("Couldn't find RTC");
   while (1);
      }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
     }

     attachInterrupt(pin, rtcTime, RISING);
}

void loop()
{
  // Count X5 on Serial Monitor

  if (count > 50)
    {
    count=5;
    Serial.println(count);
    }

   else if (count<50)
    {
    count=count+5;
    Serial.println(count);
    delay(1000);
     }
  }

void rtcTime() {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    }

Error Message:

Arduino: 1.8.10 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
  ATmega2560 (Mega 2560)"
ds1307_workingCopy_Mod5:60:14: error: 'void rtcTime()' redeclared as
  different kind of symbol  void rtcTime() {
                ^ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:9:5:
  note: previous declaration 'int rtcTime'  int rtcTime = 0;
       ^~~~~~~ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:
  In function 'void setup()':
  /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:38:42:
  warning: invalid conversion from 'int' to 'void ()()' [-fpermissive]
        attachInterrupt(pin, rtcTime, RISING);
                                            ^ In file included from sketch/ds1307_workingCopy_Mod5.ino.cpp:1:0:
  /Users/kiko/Desktop/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/Arduino.h:150:6:
  note:   initializing argument 2 of 'void attachInterrupt(uint8_t, void
  ()(), int)'  void attachInterrupt(uint8_t, void (*)(void), int mode);
        ^~~~~~~~~~~~~~~ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:
  In function 'void rtcTime()': ds1307_workingCopy_Mod5:60:14: error:
  'void rtcTime()' redeclared as different kind of symbol  void
  rtcTime() {
                ^ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:9:5:
  note: previous declaration 'int rtcTime'  int rtcTime = 0;
       ^~~~~~~ Multiple libraries were found for "RTClib.h"  Used: /Users/kiko/Documents/Arduino/libraries/RTClib-1.3.3  Not used:
  /Users/kiko/Documents/Arduino/libraries/RTCLib_by_NeiroN Multiple
  libraries were found for "Wire.h"  Used:
  /Users/kiko/Desktop/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
  exit status 1 'void rtcTime()' redeclared as different kind of symbol
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

It's not a good idea to use rtcTime for everything....

You gave the same name rtcTime to a variable and a function. Cannot work

I'm voting to close this question as off-topic because it's a pure programming problem, a very simple syntax error, not related to Arduino

KIIV, I have no emotional attachment to "rtcTime", just changed it to "buttonPressed" and changed it also in the declaration at the beginning to "volatile int buttonPressed=0". No change into the results, still error "void buttonPressed() redeclared as different kind of symbol", thanks for the input though, I did feel it to be better to stay away from words that may be commands.

@pancho22448 It kinda won't help, if you change both variable and function named rtcTime to buttonPressed... It's still variable and function with the same name buttonPressed after that change. Small hint: Change ONE OF THEM!

The Arduino builder doesn't create forward declarations of functions for functions used in code as callbacks. It has something to do with the occurrence of the name without the usual form of function call.
You could move the function rtcTime before setup() so it is visible for the use as parameter in attachInterrupt or you can create a forward declaration for the compiler. Your attempt to make the name of the function valid was to create a variable with this name. This way you created the error of duplicate name.
Add
void rtcTime();

before setup() function and remove int rtcTime = 0;


text:
Problem to Setting up i2c OLED wemos D1 mini shiled (64*24)
Hi
I used this shield before well. But it didn't work when I wanted to work with him last night!
this is my wireing :

Now I want to know how to test that it is healthy? Is i2c address missing or not?
I tried this code to find i2c address but no answer appeared on Arduino Serial monitor !! nothing ..
and i uploaded any more example code on Uno but OLED not worked .
//     ~~~~~~~~~~~ i2c Address Scanner ~~~~~~~~~~~

#include <Wire.h>

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

while (!Serial) {}

Serial.println ();
Serial.println ("I2C scanner. Scanning ...");
byte count = 0;

Wire.begin();
for (byte i = 8; i < 120; i++){
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0){
  Serial.print ("Found address: ");
  Serial.print (i, DEC);
  Serial.print (" (0x");
  Serial.print (i, HEX);
  Serial.println (")");
  count++;
  delay (1);
   }
  }
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
  }
  void loop() {}

.
   .
What is the problem ?

As the Wenos D1 is a 3.3V device and the Uno a 5V device, you might get in trouble when using I2C between them without level conversion

When you write "nothing", do you mean, that you really see nothing on the serial monitor, not even the "I2C scanner. Scanning..." message?

I mean it doesn't find an address and therefore doesn't show anything as an address.@chrisl

Does this mean if I use 3.3v the problem will be resolved? Can you tell what connection the i2c has to the supply voltage?@chrisl

whats this mean the 3.3v ground must be the same for both until i2c connections is done! if is 5v , what happen doesnt work i2c connections? @chrisl

I2C has to do with the supply voltage, that the lines are pulled up to the supply voltage. The Uno pulls up to 5V, the OLED shield to 3.3V. Depending on how exactly the I2C protocol is implemented in detail on both sides (which sometimes breaks the rules of the interface definition), there might flow a big current through the lines, because of the different voltages. Also it might be, that the OLED board cannot tolerate 5V. It might break. You might need a bidirectional level converter (or build one yourself with 2 MOSFETS)

The main problem is, that the module does not get any supply voltage. You connected the Unos 5V to the OLED boards 5V. But this pin doesn't seem to be connected on the OLED shield. It is marked with 5V there, because this board is a shield to be stacked onto the Wemos D1. When you do this, you have 5V on this pin from the Wemos and can access it on the OLED shield for adding further components. (This is the principle of shields. Making even unused pins available on the shield, so that these pins don't get covered by the shield)
The shield needs to be supplied through the 3.3V pin, as it is a 3.3V device and it does not have an own voltage regulator (see the schematics of the shield).
Thus the shield cannot be found, because it is not turned on. It does not have a supply voltage.

That said, you may also get into trouble because of the communication voltage. The Uno works with 5V on the I2C lines, while the OLED shield works with 3.3V. The shield might get damaged by the higher voltage. The schematics the shield don't mention part names, so I cannot know, if they are 5V tolerant (there are 2 ICs in the schematics).
If the shield is not 5V tolerant on the I2C lines, you need to use a bidirectional level converter for both lines (or you can build your own with 2 MOSFETS for each line).

Yes you're right. I connected the 3.3v to the OLED , upload a sketch on Uno and OLED worked.@chrisl


text:
Arduino acting strange with photoresistor data
So I stumbled into strange problem. I have this circuit, where I connect 2 photoresistors and bluetooth HC05 to Arduino. When one of the resistors senses bright light bluetooth sends '1' or '3' accordingly to another circuit. When dark is sensed, bluetooth sends '2'or '4'. When dark on both resistors is sensed for more than 1.5 second, then everything goes to while loop and bluetooth sends '1' and '3'. So for example, when left photoresistor senses bright light, and right darkness, then bluetooth sends '1' and '4'. At first for a couple of months everthing worked just perfectly fine and one day it just... stopped. While troubleshooting I found out, that when changing bright light/darkness mode on resistor, data, which is seen on com port, stops for a bit and goes in batches again, it does not flow continously. I changed photoresistors, everything is the same. I even changed Arduino, still nothing. Here is the code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
int fk = A0; // left photoresistor
int fd = A1; // right photoresistor
int a = 0;
int b = 0;
unsigned long dl; // time
const unsigned long p = 1500; //how many milisecs dark should be sensed

void setup()
{
    Serial.begin(9600);
    BTserial.begin(9600);
    pinMode(fk, INPUT);
    pinMode(fd, INPUT);
    dl = millis();
}

void loop()
{
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }
    while (a<1000 && b<1000)
    {
        if ((millis() - dl) >= p) //if dark is being sensed more than 1.5 sec
        {
        BTserial.write('1');
        BTserial.write('3');
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    }
}
    }

And when I use only this batch of code without while loop
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }

Everything works fine, data is flowing continously, even when light states are changing fast.
But also everything works fine, when I use only while loop standalone without previous batch. So in my opinion bad things happen in transitions between these two batches of code? But I completely cannot understand what is wrong, why it suddenly stopped working, maybe time is calculated wrongly? I realized that when I soldered bluetooth to another board, but bluetooth is not the case, as I tried the same code with bluetooth data sending part removed. Data still goes with strange batches.
I am completely lost.

your code is badly formatted ... the indentation of the code needs to be corrected .... without correct indentation, it is difficult to follow the program flow

the while loop is unnecessary ... change your thinking a bit .... your code checks each sensor and remembers the last time it sensed light .... all you have to do, is to remember the last time dark was sensed .... then simply determine the time interval between light and dark (or between light and now)

I do not understand why you need this 1.5 sec rule. If both photo resistors indicate darkness BT already sends 1 and 3 . So what is different if the darkness lasts longer than 1.5 seconds. But, there is one small difference that could explain your observations. In the if/else blocks  you use a delay(10); Perhaps your serial connection/Bluethooth is not quick enough to handle the speed up. 9600 baud is not very fast. ;-)


text:
Break a while loop with a push button (AccelStepper.h)
Disclaimer: This is my first Arduino project.
Background: I am building a "rapunzel tower" lantern for my daughter: the witch pays a visit to Rapunzel meanwhile my daughter can read a book (or still play a bit) before going to sleep.
Goal:If a button is pushed --> a stepper motor turns on and my daughter's lantern switches on (via a relay) --> the stepper motor spins to the left (+/- 5 minutes) to bring the witch to the tower--> a led in the tower room switches on and off (+/- 1 minute) --> the stepper motor spins to the right (+/- 5 minutes) to bring the witch down and the lantern switches off (and my daughter needs my sleep).
Issue If my daughter want to sleep before the witch gets down, she must be able to turn off the lantern while the witch is still on the move (up or down). However, I am unable to do so. That is, I am unable to break the while function when the button is pushed to turn off the latern.
Code
Right now, I use the following piece of code below (compiled from different sources).
I know that I use the delay function instead of the millis function, but that is for my next step. The same goes for the time the motor spins (which I still need to tweak).
Any help is welcome. Thanks.
/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: continuous rotation. More info: https://www.makerguides.com */
// Include the AccelStepper library:
#include <AccelStepper.h>
// Motor pin definitions:
#define motorPin1  3    // IN1 on the ULN2003 driver
#define motorPin2  4    // IN2 on the ULN2003 driver
#define motorPin3  5    // IN3 on the ULN2003 driver
#define motorPin4  6    // IN4 on the ULN2003 driver
// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);

// Code to trigger the light and motor
const int buttonPin = 1;   // the number of the pushbutton pin
const int ledPin =  7;     // the number of the LED pin

int relayPin = 2;          // Connected to relay
int buttonState = 0;       // variable for reading the pushbutton status

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(1000);
}
void loop() {
  buttonState = digitalRead(buttonPin);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
    digitalWrite(relayPin, LOW);
  } else {
    digitalWrite(relayPin, HIGH);
    // Let the witch go up.
      // Set the current position to 0:
      stepper.setCurrentPosition(0);
      // Run the motor forward at 500 steps/second until the motor reaches 4096 steps (1 revolution):
      while (stepper.currentPosition() != 8096) {
          stepper.setSpeed(500);
          stepper.runSpeed();
      }

    // Let the witch the light turn on and off in Rapunzel's room
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);

    // Let the witch let climb down.
      // Reset the position to 0:
      stepper.setCurrentPosition(0);
      // Run the motor backwards at 1000 steps/second until the motor reaches -4096 steps (1 revolution):
      while (stepper.currentPosition() != -8096) {
        stepper.setSpeed(-1000);
        stepper.runSpeed();
      }
  }
  delay(5);
}

while (stepper.currentPosition() != 8096) { is a loop that repeats many times ... you can check for a button press inside that loop .... btw, the stepper.setSpeed(500); should be outside of the loop

You can put a read for the button inside the while loop, but a better solution would be to get rid of the while loop entirely and let the loop function do the looping.

Thanks for the advice. I will try to get rid of the loop asap and come back to you... putting the button in the while loop did not work (the push event is registered [the led on the arduino blinks when the button is pushed and the while loop paused, but when the button is released the stepper continues instead of stopping).

Yes, it works! Thanks for the advice.