text:
How much voltage and amps for 2 SG90 servos?
Question is pretty straight forward: How much amps and voltage do I need for 2 SG90 servos? I want to use 4 but you might already know that Arduino Uno only has 2 5V ports.

Arduino Uno only has 2 5V ports ... no ... the arduino has one power regulator ... the 5 V pins are both connected together

The SG90 servo datasheet is here:
SG90 Servo Datasheet
As you can see, the voltage specification is 4.8 - 6.0 Volts.  But you do NOT want to power this or any other servo via the Arduino.  Servos are quite "noisy" electrically and this can cause instabilities with your Uno.
You want to supply power to the servo directly from a +5V power supply.
I don't see the current draw for this servo specified so you will need to do your own measurements based on the loading of the output shaft.  Be aware that these draw more current with increased load on the shaft.
As far as the control signal, the Arduino Uno can certainly drive it via its PWM outputs.

I know that I am suppose to feed the 2 servos directly from external power source but I still don't know how much voltage and current I need.

@YağızAlpErsoy, hobby servos aren't typically specified that well. The suggestion that your measure them yourself is a good one.

These are relatively low-powered servos.  The voltage is specified, use 5 Volts.  A common 5V 1A supply will likely do well here since you are just driving two servos + your Uno.

@jwh20 thank you! that's it!


text:
strcmp doesn't seem to work
I'm trying to compare a char array that I'm assembling to a string and I'm having trouble comparing the strings.
I'm getting the data for the char array as a set of bytes and I'm compiling it into a char array like this:
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  char buffer[length];
  for (int i = 0; i < length; i++)
  {
    buffer[i] = (char)payload[i];
  }

So grabbing each of the ASCII codes and converting it into a character as I add it to the buffer.
After I do that I'm trying to print the buffer to the monitor and then compare it to a string. Though it's not working:

I know I'm getting all of those extra characters in the println b/c the buffer doesn't end in 0 so print keeps reading out memory bytes till it hits the zero, but I don't know why strcmp isn't showing the buffer matching the string "ravenclaw".
I'm sure it's for the same "missing the null terminator" issue, but I'm not sure how to fix it. Help is appreciated!!

Either I don't understand your question or you're on the verge of answering it yourself.

It would be better if you put the code into your question as text, not a as a screen capture.

You seem to already understand that it's not null-terminated and that's why it's not working the way you expect.  So, I'll take a different tact for "how to fix it".
You can simply not treat the payload as a string, and instead use memcmp, as in:
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {

memcmp behaves similarly to strcmp, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify.  In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {

or any number of variations on that which might use strlen(), or a pointer rather than array (if not using sizeof) or PROGMEM with strlen_P() and memcmp_P() or... etc, etc, possibly putting this into a function so you can reuse it.

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of write() that allows you to specify the length.
Serial.write(payload, length);

Ah awesome, thanks for the extra detail. I wasn't aware of memcmp. That def seems like a better way of doing the comparison.

The easier way to simply the code is to use strcpy to create a buffer that is 1 byte longer than the length and then terminate it with \0.
void messageHandler(char *topic, byte *payload, unsigned int length) {
  char buffer[length+1];
  strcpy(buffer, (const char*) payload);
  buffer[length] = '\0';

  Serial.println(buffer);

  int matched = strcmp(buffer, "ravenclaw");
}

oh nice! I like this take on it. TBH I thought I tried this at one point and it didn't work, though I was noodling a lot at the time so I may have jacked up my code. thanks for the tip!

Ah, the snag in this one is that after casting to a const char pointer you can't add anything to it. You end up with a invalid conversion from 'const char*' to 'char',  buffer[length] = "\0" error.

@ChrisSchmitz, what you seem to have missed is that in their code they used '\0' rather than "\0", single rather than double quote.  The terminator is a single character being written into a single character of an array of characters.  It should compile any Arduino using g++, which is to say all of them that I know of; the run-time-sized local array is making use of a g++ extension.

@ChrisSchmitz However, if you want to try this way of doing it, you need to swap out the strcpy() line  and replace it with memcpy(buffer, payload, length);  Otherwise the strcpy may overflow buffer, because the payload is, again, not terminated.  So there's nothing to tell strcpy to stop, except the next '\0' it finds in memory following payload.

source: Stack Exchange

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

sort: votes


text:
Import into Arduino a vintage data bus from TMS1000
For experimentation I want to import or receive into Arduino the output data from a TMS1000 (1980s) data bus.  For model train controller Hornby Zero1, and the bus sends data to receivers, for loco number, speed, direction etc. I have all the data structure etc) Is it feasible  to import to Arduino, and export from the same Arduino back to the original bus.    Just to see it working, and then later experiment with the data in the Arduino.
What libraries would be best ?
Thanks
Charles Harris

it is feasible ... nothing else can be said without any information .... please remove the can-bus and modbus tags

The Arduino does not have a bus but you can simulate it with some latches and data buffers. The TMS1000 is a family of microcontrollers introduced by Texas Instruments in 1974. It combined a 4-bit central processor unit, read-only memory (ROM), read/write memory (RAM), and input/output (I/O) lines as a complete “computer on a chip” You will have to give a lot more information if you want a usable answer.

You're not going to find any pre-built libraries for this task which is somewhat unusual but not at all impossible.
Basically all you need to do is to connect the TMS1000 address/data and strobe lines to Arduino inputs and write yourself some relatively simple code to detect the various TMS1000 bus states and capture them when they happen.  In order to detect specific events as you have mentioned you will need to know more about the TMS1000 software that's running and what I/O devices that it's selecting.  But again, that's all pretty straightforward.
Keep in mind, however, that you are going to have to perform level shifting on ALL the inputs from the TMS1000.  This old TI chip was implemented using a PMOS (i.e. a predecessor to both NMOS and CMOS) and uses a NEGATIVE power supply instead of the more common today POSITIVE supply.
So rather than being powered by a +5V supply the way an Arduino is, the TMS1000 is powered by a -15V supply.  In this case ground is still at 0V but Vdd is -15V.  That means the I/O signals adhere to a different scheme as noted in the datasheet:

You can view the datasheet yourself at:
TMS1000 Datasheet
But what this means is that a LOW (i.e. Vil) is at -15V and a HIGH (i.e. Vih) is at 0V.  You will need to translate these voltages so that you don't damage either the TMS1000 or the Arduino and you get the correct levels on the pins that you are watching.
The TMS1000 datasheet has some suggested circuits for interfacing to 74LSxx series parts (i.e. 5V logic) which will probably get you started.  Note that the simplest method involves running the 5V logic with its VDD at 0V and it's "ground" at -5V.  While this might seem odd, the Arduino will not know the difference as voltage is always relative.

voltage is relative. should be able to come up with a setup where -15V for Hornby is GND for arduino if you really wanted to.

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


text:
ESP8266 SocketIOclient constant disconnect with Python WebServerSocket
I am writing a program that echos back the message sent to the web socket server on a host machine. When running the ESP module, the connection is established but immediately disconnects as seen in the first image. I originally thought this maybe a result to the host machines firewall, however, using my laptops connection, I was able to produce the desired echo. Is the constant disconnect a result in different protocols or something I am missing?
WebSocketServer on host machine (modeled off example)
import asyncio

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()

ESP8266 modeled in arduinoWebSockets
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

#include <Hash.h>

ESP8266WiFiMulti wiFiMulti;
SocketIOclient socketIO;

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            Serial.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            Serial.printf("[IOc] Connected to url: %s\n", payload);
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
            Serial.printf("[IOc] get event: %s\n", payload);
            break;
        case sIOtype_ACK:
            Serial.printf("[IOc] get ack: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_ERROR:
            Serial.printf("[IOc] get error: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_EVENT:
            Serial.printf("[IOc] get binary: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_ACK:
            Serial.printf("[IOc] get binary ack: %u\n", length);
            hexdump(payload, length);
            break;
    }
}

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

    //Serial.setDebugOutput(true);
    Serial.setDebugOutput(true);
    Serial.printf("[SETUP] starting up");

    Serial.println();
    Serial.println();
    Serial.println();

      for(uint8_t t = 4; t > 0; t--) {
          Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
          Serial.flush();
          delay(1000);
      }

    // disable AP
    if(WiFi.getMode() & WIFI_AP) {
        WiFi.softAPdisconnect(true);
    }

    wiFiMulti.addAP("ssid", "password");

    //WiFi.disconnect();
    while(wiFiMulti.run() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Retrying...");
    }

    String ip = WiFi.localIP().toString();
    Serial.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("local host address", 9000);
    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
//int attempts = 0;
void loop() {
    socketIO.loop();
}

First, does the default ESP8266 example work with your Python server? It's best to start with that as a reference. Next, did you change any of the library's default config, uncomment or comment out anything?
At the moment, neither device is showing that the Websocket connection was ever opened, they just show "disconnected" or "closed", so something likely happened during the setup stage that made one party drop the connection. Try adding #define DEBUG_ESP_PORT Serial to WebSockets.h (after the Arduino.h inclusion), so we can see more detailed logging from the library.

Hi @SoreDakeNoKoto , thanks for the reply. After some sleep and a deeper dive, I found a post that suggested the library was the problem. Ended up using this instead. Best

After testing the server on the host machine using an additional computer, I was able to produce the desired output. I would suspect it is an issue within the library or mis-use/understanding. I found a post that suggested the library was the problem and ended up using this library instead.
Using the example implementation , I was able to achieve the desired results.


text:
What processor can I replace on behalf of ATMEGA328P, to get more processing power for machine learning in UNO
I wanted to do a machine learning project in Arduino UNO R3. But I came to know that the processor(ATMEGA328P) isn't capable of supporting the processing power needed for machine learning. So is there any other processor that is better than ATMEGA328P for machine learning that is supported in UNO? If not any other way that I can do it?

if you replace the ATMEGA328P with something else, then you no longer have an Arduino UNO

The UNO part of this question is almost certainly a dead end.  If the "it" in "If not any other way that I can do it?" refers to machine on an Arduino(ish) board, then more details on the sort of thing you want to do are needed, that "processing power" you spoke of.  You may find that none of them are really up to the task, but it depends on the task.

@jsotola Thanks a lot

@timemage Thanks for your help

You can't just replace the processor on the UNO with something better. The 328P is pretty much the best MCU there is in the pinout for that board.
Instead you can replace the whole UNO with something more powerful.
My board of choice for AI work would have to be one based on the Kendryte K210 chip, such as the Maixduino (which is helpfully in an UNO footprint).  The K210 is a dual-core 64-bit 400MHz RISC-V CPU with embedded neural network co-processor. On the Maixduino it's also coupled with an ESP32 for WiFi/Bluetooth.  That's 2x 400MHz 64-bit cores, 2x 32-bit 240MHz cores, one low-power FSM core, and a neural network core all on one board.

I fully agree. Putting a machine-learning processor on an UNO shield is like strapping a get engine onto a Ford Pinto

@Majenko Thank you

@DuncanC +1 for the image of a Ford Pinto with a jet engine ... lol ... of course I added screaming passengers to that picture

The Arduino blog recommends this: https://store.arduino.cc/nano-33-ble-sense.
See: https://blog.arduino.cc/2019/10/15/get-started-with-machine-learning-on-arduino/
I know Arduino has been talking about machine learning for about a year or so. Here's the Google search I used to find this: Arduino machine learning.
Here's a kit you can buy too: https://store.arduino.cc/usa/tiny-machine-learning-kit.


text:
Measure the time between 2 inputs
I am making a small project, and for that, I need to measure the time between 2 inputs.
basically, a program to measure the time elapsed from when digital pin 2 is high to when it again becomes high.

Have you seen the millis() function and the time measurement in the BlinkWithoutDelay example? There are lots of tutorials about millis() on the web

The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: millis(). It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use micros() with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.
Here I would show the principle of millis()/micros(), since that is most likely what you need. In the following I will only write millis(), but all the calculations can also be done with micros(). The only difference for the calculations is the factor 1000 between milli- and microseconds.
When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with millis():
unsigned long starttime = millis(); // take note of start time
// here the event to measure
unsigned long endtime = millis(); // take note of end time
unsigned long duration = endtime - starttime; // duration of the event in ms

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:
int last_input_state = LOW;
unsigned long timestamp;

//setup here

void loop(){
    int current_input_state = digitalRead(2); // get current signal level
    if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
        unsigned long current_time = millis(); // take note of the current time
        unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
        timestamp = current_time; // update the timestamp with the current time
     }
     last_input_state = current_input_state; // update the last input state with the new measured one
}

Note:

This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high delay() calls, but you shouldn't do that either way, since that will block anything from going on.
You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING); and provide a void service_function(), which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).

You could do something like this:
unsigned long startTime;
unsigned long elapsedTime;

// Any needed setup stuff
void setup()
{
  ...
}

void loop()
{
  // Wait for input to go high
  while(digitalRead(2) == LOW);

  // Start timing
  startTime = millis();

  // Wait for input to go low
  while(digitalRead(2) == HIGH);

  // Now wait for it to go high again
  while(digitalRead(2) == LOW);

  // Now get the time interval
  elapsedTime = millis() - startTime;

  // Do whatever with the result.
  ...
}

Keep in mind that the millis() value will overflow every 50 days or so.  If you need to run this continuously, you need to check for an overflow and adjust things accordingly.

elapsedTime = millis() - startTime; even works well while millis passes 0 on "overflow". Nothing to adjust.

Altough working with millis(), this is a blocking example, due to the while statements. (Even worse that the Arduino pulseIn function, which has a timeout)

I did not see any requirement to do anything but measure the interval.  Therefore a blocking solution is ok.  Why complicate it if it's not needed?  As is so often the case, there are many many possible solutions.

So one should compare your solution to standard pulseIn.


text:
Rounding to the next upper (or lower) 0.1
I'm reading from a temperature sensor. I get float values with 2 decimals. I want to round them to nearest 0.1.
This is my sketch:
void setup() {
  Serial.begin(115200);
}

void loop() {
  float temperature = 21.81;
  float rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.81 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.79;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.79 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.77;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.77 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.70;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.70 ->");
  Serial.println(rounded_temperature);
  delay(1000);
}

This is the output:
21.81 ->21.85
21.79 ->21.75
21.77 ->21.75
21.70 ->21.75

And this is the output I would... Rounded to "0" and not "5".
21.81 ->21.80
21.79 ->21.80
21.77 ->21.80
21.70 ->21.70

temperature could be also negative

this is not an arduino question ... it is a general programming question

@jsotola OP is using the round function, which is part of the Arduino library.

Using roundf() function:
float rounded_temperature = roundf(temperature * 10) / 10;

float variables do not have a number of decimal places. They are merely an approximation anyway. Instead it's when you print that you decide how many decimals to display.
Serial.println(temperature, 1); // Print with 1 decimal place

Or to put it into a string:
char buf[8]; // Room for 7 characters plus NULL terminator
float val=23.81;

dtostrf(val, -7, 1, buf); // 7 characters with 1 decimal place and left aligned (negative width)

mmm... My trouble is that  I send that data via MQTT to HomeAssistant. I want to send them as "my format" and not with the .50

Then format it into a string and send that. Use dtostrf to format a char[].

Isn't there a native function to round to .x0 instead of .50 ?

@sineverba Even if you do "round" the float chances are it won't be rounded. Like I said - floats are only an approximation. The only way to fix it to a specific number of digits is to change it to a different format - such as text. With dtostrf().

I often store the floating point data that I get from a sensor in integer to preserve the decimal precision that I want by multiple it by 10 before casting it into an integer. It is easier and more efficient (compare to string or float) to send over to another system. This is also how many sensors representing and store the floating data (e.g. TMP275) as well.
To achieve what you want, here is what I would do:
#include <math.h>

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

  float i=21.81;
  float j=21.79;
  float k=21.77;
  float p=21.70;

  // convert to integers
  int l = (int) round(i*10);  // 218
  int m = (int) round(j*10);  // 218
  int n = (int) round(k*10);  // 218
  int o = (int) round(p*10);  // 217

  // Convert back to actual floating point for display
  Serial.println((float)l/10);  //21.80
  Serial.println((float)m/10);  //21.80
  Serial.println((float)n/10);  //21.80
  Serial.println((float)o/10);  //21.70
}

Ok.... but 21.81 rounded is 21.80, not 21.90...

I change it to use round() instead of ceil().


text:
Arduino Nano Every Vin 5V fixes I2c problems
I had problems with connecting my devices via I2C. The "requestfrom" constantly hanged and the endtransmission sometimes gave NACK responses.
After disconnecting the devices from 12V and powering one of them via USB (vin with which it was connected to the other arduino's became 3.8V) they stopped misbehaving and worked together in harmony.
How is this possible? Am I missing something? An Arduino Nano Every should be driven between 6-21V?
All devices are "Arduino Nano Every"'s. They used to get 12V directly on Vin and are connected together in a chain by Vin,GND,A5(SCK),A4(SDA)
The master is in the middle of the chain so that the distance is max 20cm.
I also tried powering them via vin with 9V and 5V. Had the same issue.
Already big thanks for the help.

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

SO... In the datasheet it says you should use 7-21V on VIN. This gave the problem. I powered the arduinos directly from 5V on the vin. This fixed all I2C problems. Haven't had any problems anymore after changing this.
cheers to all.

You're saying that the voltage on the input side of regulator... causes the internal pull-ups to change value inside of a chip on the output side of the regulator?

it doesn't make sense

Not the way I'm reading it currently anyway.

No i'm saying that I THINK there is something wrong with the voltage regulator of the every and that a higher voltage actually goes through. When using a higher voltage on the I2C bus the pull up resistors are not the right Ohm to give a good data signal. That is why it constantly quit the connection after some time.

Pure guess. But it fixed my problems to just power it via 5V on the vin.

I see, It would be good to make clear that you found that it helped (empirically) and that the business about "actually makes the resistances..." is really speculative.  It still doesn't make sense to me, but I'll grant you something may have changed.  As long as whoever reading this understands what's guess and what's not, good deal.

Is this better?

To my thinking, yes.  You're saying something factual about what you did and what you observed correlated to it.  You removed the bits that seemingly had no fact or theory behind them and had no indication that they were, as you put it "pure guess."  I call that an improvement.


text:
Ethernet Shield web server - Can't find the index.htm file
i've just got the EthernetShield and watched a tutorial on how to host a html page with it but i can't find my html page on the SD card.
#include<SPI.h>
#include<Ethernet.h>
#include<SD.h>

byte mac[] = {0xA8, 0x61,0x0A, 0xAE, 0x3A, 0xC4 };

EthernetServer server(80);

File webPage;

void setup() {
  Ethernet.begin(mac);
  server.begin();
  Serial.begin(9600);

  Serial.println(Ethernet.localIP());

  Serial.println("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println("ERROR - SD card initialization failed!");
    return;
  }
    Serial.println("SUCCESS - SD card initialized.");
    if(!SD.exists("index.htm")){
      Serial.println("ERROR - Can't find index.htm file!");
    }
      Serial.println("SUCCESS - Found  index.htm file.");
}

void loop() {
   EthernetClient client = server.available();
   if(client){
    boolean currentLineIsBlank = true;
    while(client.connected()){
      if(client.available()){
        char c = client.read();
        if(c == '\n' && currentLineIsBlank){
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          webPage = SD.open("index.htm");
          if(webPage){
            while(webPage.available()){
              client.write(webPage.read());
            }
            webPage.close();
          }
          break;
        }
        if(c == '\n'){
          currentLineIsBlank = true;
        }
        else if(c != '\r'){
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
   }
}

When i save the HTML file i can't save it with the .htm format

What you served is not 369 bytes?

Are you just confused by the mention of "Microsoft Edge"?

@timemage no its not

There are reportedly 369 bytes in the file.  So what does the file contain if not what you wanted?

@timemage the file contains only the HTML code, u can see a screenshot of my error down below , in the Answer section.

The answers you are giving don't seem terribly connected to the questions asked and I'm don't know what more I can say or ask to help you except this: Your question needs clarification.  The additional information you're providing should be edited into your question.  There's not enough information here to make me think what you're seeing is unexpected.

@timemage I'm a beginner and I can't say that I understand very well what the problem is with the file size. I simply created an html file with a simple page and then uploaded the file to the SD card. When I load the code in arduino you can also see in the picture that it does not read my file.

Hi @antisocialkid and welcome to the Arduino Stack Exchange. It would be really helpful if you could add a screenshot (or the source text) of what is inside the index.htm file on the SD card. To do this, insert the SD card into a computer and open the index.htm file in a text editor like Notepad.

Windows is hiding the extension from you.
The file you showed is either index.htm or index.html. If it's the latter, you could change the windows setting to "show extensions for know filetypes", or change the sketch so it uses index.html instead of `index.htm. I'd go with the latter, as it's the easiest.
EDIT: the SD library doesn't seem to like file extension that are longer than 3 characters. So changing the code to use "index.html" doesn't work.

I've changed the sketch but is still not working error

Did you change if(!SD.exists("index.htm")){ to if(!SD.exists("index.html")){ as well?

yes, still not working

My guess is there something weird going on with that file. How did you create it? What do you see if you right-click the file, and select properties? Especially, what does it say after "type of file"; what file extension is between the braces?

Type of file: Microsoft Edge HTML Document (.html) and I created it in Visual Studio Code. (Save as > index (with HTML extension)

Weird. The file appears fine, but somehow, the SD library can't find it on the SD card.

also the  SDcard already has the format FAT32

Maybe try it with a .txt file. I'm running out of ideas here.

finally windows let me to change the extension file to .htm and now it works !

Ahh. I think it has to do with the DOS 8.3 filename convention. It doesn't like file-extensions longer(/other) than 3.

@antisocialkid if the answer was useful to you, you should vote it up.  If it is the answer to your question, you should "accept" it.

Might be worth adding that it's probably available under its short name, which is likely INDEX~1.HTM


text:
Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?
Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.
The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).
Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?
Edit:
Both the ESP8266 and the ESP32 Updater class check for an "IMAGE_MAGIC" value in the upload header; but that is defined as "ESP_IMAGE_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.
Edit 2:
Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like <sketch_name>.<board_name>.bin, we just compare the board name as part of the uploaded filename: if (upload.filename.indexOf(MATCH) > 0) ..., where MATCH is the respective board name. As they are pin compatible, we use "d1_mini.bin" and "d1_mini32.bin".
Edit 3:
When the webserver tries to abort the upload with 403 Forbidden (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a server.client().stop(), but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.
This is not really a final solution, so I'ld appreciate any better idea.
Richard

You could just try what happens if you perform such an "illegal" update. My guess is that booting an image intended for the other MCU would fail and be marked as corrupted firmware image. If esp8266 and esp32 have different flash sizes I would expect the bootloader to recognize the faulty firmware images

At least I once OTAed a 4MB-ESP32 with an image intended for an 8MB-ESP32, which failed (the esp declined booting this image and remained on the fw-version that was installed previously)

The bords we use have the same amount of flash size (4MB), and the updater class of the ESPs seem to accept any file as long as the "magic byte" is 0xE9, but that is the same for ESP32 and ESP8266. Tested this with small text file named "fake.d1_mini.bin" wth 0xE9 as first byte - did report no error on update, but crashed on reboot.

I assume you are the one creating the OTA update.  If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.

Thank you for your answer. This was also my first idea, but finding a signature somewhere in the uploaded file is a lot of work, as you do not know where the linker puts the signature. I thought of a simpler method...

You can force the linker to place a signature at a specific location. Or you can "abuse" an unused interrupt vector.


text:
How to transfer constants from one loop to next one
#include "VernierLib.h"

VernierLib Vernier;

#define led 13

float sensorReading;

void setup() {
  Serial.begin(9600);
  Serial.println(Vernier.sensorName());
  Vernier.autoID();
}

void loop() {
  float base_temp;
  base_temp = Serial.parseFloat();
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

That's the code, I have a question. When I write the temperature to Serial, it lasts only until the end of one loop.
How to keep the same temperature in the next loop?

To keep the variable value through different iterations of a function, declare it as static. Though your code will overwrite that value, when you use Serial.parseFloat(). Though that is a programming question, not an Arduino question

@chrisl thanks, but i would like to keep the same constant for like 2, 3 loops and than change it again. How would i do that?

It is unclear to me, what exactly you mean. And why 2 or 3 loops? What are you trying to achieve?

@chrisl , i'd like to achieve that i could anytime change the constant temperature, and when i change it should stay the same until i change it again.

constants cannot be changed ... use a variable to hold changeable data

Also asked here: https://stackoverflow.com/questions/65512883/how-do-i-change-variable-after-each-2-3-loops . Please don't crosspost.

In addition to @chrisl comment, you need to use code such as if ( Serial.available() ) { base_temp = Serial.parseFloat(); }.

There are two things here you need to consider.
First is that your variable is a "local" variable. This kind of variable is created at the start of each iteration, then discarded at the end of that iteration.
There's two things you can do to "fix" this:

Make the variable "global" - that is, move the definition out of loop() to the "global" scope (put it at the top of your program). It is then only created once and never discarded.
Make the variable "static" - that is, add the static keyword to it. It is then created on the first iteration only, and never discarded.

The second thing to consider is that you have no "There is no value" concept. Every iteration you parse a new float, whether there is one there or not. And if there isn't one then it just gives you 0. So you need to come up with some way of saying "I have entered a number, so parse it". The simplest thing is just to assume that all values of 0 are "no number entered", but that of course prevents you ever entering 0 as a valid input.

A static variable is created before main() (or setup() on Arduinos) runs. It is initialized with a given explicit value or zeroed without.

@thebusybee Technically, yes, that's right. But the effect, as far as an Arduino user is concerned, is that it is created once on first run and stays around afterwards. Arduino users really don't need to know such technical minutiae just yet.

Something like this should work (untested, but you get the idea; the explanation is in the comments):
void loop() {
  static float base_temp = 21;     // Or whatever default starting value you want
  static float t = 0;              // A temporary store for Serial.parseFloat()

  t = Serial.parseFloat();         // Read t; if Serial.parseFloat() times out, it will return 0.00
  if (t != 0.00) {                 // If something else than 0.00 is in t
    base_temp = t;                 // Update base_temp with t
  }                                // Note: You can't set base_temp to exactly 0.00 with this set-up
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}

In this code 0.00 means that "no value was entered", so you can't set the temperature to exactly 0.00 with this set-up; 0.01 should work fine, though.


text:
Set TX, RX to LOW before sleeping, re-enable uart after waking up
I have an ATmega1284p and I need to have the TXD0 (i.e. pin 9) set to LOW, before going to sleep. After waking up, I want to restore UART0 communication to work as expected. Here is my code:
Serial.begin(38400,SERIAL_8N1);

*do Stuff*

Serial.end();
//pinMode(9,OUTPUT);
//digitalWrite(9,LOW);
//UCSR0B &= ~bit (RXEN0);  // disable receiver
//UCSR0B &= ~bit (TXEN0);  // disable transmitter
cli();
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
//MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
//MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above
sleep_bod_disable();  //disable brown-out detection
sei();             // guarantees next instruction executed
sleep_cpu ();              // sleep within 3 clock cycles of above
sleep_disable();

//  UCSR0B |= bit (RXEN0);  // enable receiver
//  UCSR0B |= bit (TXEN0);  // enable transmitter
//pinMode(9,OUTPUT);
//digitalWrite(9,HIGH);
//delay(100);
//pinMode(9,INPUT_PULLUP);
Serial.begin(38400,SERIAL_8N1);
delay(1000);
Serial.println("- Good Morning");

*do Stuff*

You can see in comments all the different things I tried:

Using Serial.end() and then, after waking up, Serial.begin()
Using the UCSR0B register
Using digitalWrite to set the pin to LOW and then, after waking up, either setting it to high, or setting it as input

All of the above combinations have the common problem that the cpu hangs after waking up, and the Serial is never restarted to print good morning message, neither does the program continue to execute further down.

Perhaps your terminal must be resetted as you have closed the serial connection. From my experience: Simply calling Serial.begin() does not trigger the Serial Terminal to reconnect again. I'm not sure, but the Serial.println might block then and that would be the reason your program won't be executed any further. Again; these are just guesses, but worth a try. ;-) Did the sleep mode work without the Serial shutdown? Can you try "the further processing" with out any println to see if the prints block or not? Can you recognize "further processing" without print statements?

Just a hint how to mark tried alternatives, which is easier to grasp and maintain than commenting each line: Use conditional compilation by #if 0 // try 1 ... #elif 1 // try 2 ... #endif.

Try adding delay(1000); after * do Stuff*. My guess is that there is still data being send over the serial connection when the MCU is put to sleep; leading to weird issues.

Thanks for the sugggestions. I tried those, before the solution came to me, which I posted below. Just one suggestion about @Gerben 's comment: It is indeed common to still have data before going to sleep, but the best way I found to deal with such issues is by using Serial.flush(). Of course, both would work fine

After trying many different alternatives, it turns out that my mistake was that, foolishly, I had included Serial printing inside my ISR routines, which where accessed when my interrupt fired, in order to wake my uP. As a result, Serial.print was called, with Serial being closed (before issuing the Serial.begin command to restart it), thus breaking my uP.
Extra: Just wanted to comment about using Serial.print inside ISRs. Although it can lead to unexpected problems like this one, or timing issues (ISR would take too long to execute) and is definitely a bad practice, it can sometimes be useful for debug purposes during development to print some kind of message there.
Printing a message takes long, and the ISR will return before the message is completely transmitted, with the potential to cause a lot of headache. Also, interrupts are disabled inside ISRs, so delay() is not working to do some kind of flow control. The best way to print messages in ISRs that I have come across so far, is by using Serial.flush() before exiting the ISR, making sure the message is completely transmitted.

You should keep the ISR as short as possible, just to set the flag or something. It never a good idea to use I/O access (such as Serial.print() within an ISR routine, even for debugging purpose, do it outside of the ISR based on the flag set by ISR.

I would suggest you read Nick Gammon's Interrupt.

Thanks for the suggestion, I have already read it, a great tutorial indeed. And yes, keeping only flags inside ISRs is definitely the best practice.


text:
How can I execute a string in my Arduino Uno board?
I was making a project with Arduino Uno ,
It's working is like this it connects to a key pad and a 7segment display ,and when you press a run button connected to Arduino it should run the code written.
I don't want code for display and keypad but for executing a string like we can do in python- exec("print (8)")
Please help me and ask any information you need to solve it

There's a technical answer to your question.  But a more practical answer can probably be given if you explain why you would want to do this on an UNO.

you could try forth ... it's not python, but it is interpreted ... https://arduino-forth.com/ .... you could write some forth words to emulate some of the python commands

Unless you want to implement some form of scripting engine, you can't.
Arduino code is compiled code, not interpreted code. There is no way of converting text into runnable code, since that is done by your computer at compile time, not by the Arduino at run-time.
The only thing you could possibly do is write some form of scripting engine which reads text and interprets it in some meaningful way to perform operations. That is not a trivial task, so you have to ask yourself: is this really what you want to do? Are you going about tackling your problem in the right way?

Things like reflection in higher level languages that would make this an “easier” task aren’t available in C++

As stated in Majenko's answer, you would need an interpreter running on
the Arduino. Python is too large to run on an Uno, although it can run
on some more powerful microcontrollers.
A Web search for Arduino interpreters yields quite a few promising
options. I have not tested any of them:

Firmata
Forth
another Forth-ish language
Lisp
BASIC
a C-like language

The Forth language is quite popular when you need an interpreter with
minimal footprint.


text:
How to pause a loop
any ideas on how could i code this loop so when i press a button everything stops (Vernier stops reading temperature), and then when i press the button again it (Vernier reader) stars working.
   #include "VernierLib.h"
    VernierLib Vernier;
    #define led 13
    #define button 12
    int switchState = 0;
    float sensorReading;
    void setup() {
      Serial.begin(9600);
      Serial.println(Vernier.sensorName());
      Vernier.autoID();
      pinMode(12, INPUT);
    }
    void loop() {
      static float base_temp = 0;
      static float t = 0;
      t = Serial.parseFloat();
      if (t != 0) {
        base_temp = t;
      }
      sensorReading = Vernier.readSensor();
      Serial.print(sensorReading);
      Serial.print(" ");
      Serial.println(Vernier.sensorUnits());
      Serial.print("Željena temperatura: ");
      Serial.println(base_temp);
      if (base_temp > sensorReading) {
        digitalWrite(led, HIGH);
      } else {
        digitalWrite(led, LOW);
      }
      delay(1500);
    }

Assume you did #define BUTTON 12 as I suggested.
Somewhere inside your loop you could code:
if (digitalRead(BUTTON) {        // First button press
  while (digitalRead(BUTTON));   // Wait till button release
  while (!digitalRead(BUTTON));  // Wait till second button press
  while (digitalRead(BUTTON));   // Wait till button release
}

This "hangs" from the first button press to the second button release. The code assumes your button takes pin 12 HIGH when pressed and LOW otherwise. This is a bit difficult to realize in hardware (well, not really; but you will beed an external Pull-Down resistor). The easier way will be to connect pin 12 to GND when button is pressed, and use the internal PullUp-resistor: pinMode(BUTTON, INPUT_PULLUP);. Then the logic of the while condition has to be reverted:
if (!digitalRead(BUTTON) {        // First button press
  while (!digitalRead(BUTTON));   // Wait till button release
  while (digitalRead(BUTTON));    // Wait till second button press
  while (!digitalRead(BUTTON));   // Wait till button release
}

For reading the button I suggest using the Bounce2 library. Then you can wire your button to a fitting digital pin, the other side to ground. Use
button.attach( BUTTON_PIN ,  INPUT_PULLUP );

To use the internal pullup of the Arduino. Define a global state variable, that holds, if your code should run or not.
bool code_running = true;

Then in your main code (additional to calling the update function of the library) use
if(button.fell()){
    code_running = !code_running;
}

to toggle the state variable on button presses. Then, still in void loop(), use an if statement with the state variable to execute your code:
if(code_running){
    // put your code here
}

Note, that your code should not block for long periods for this to work correctly. You should always write your code in a non-blocking way, meaning, that no function call or loop will take longer than a few ms to execute. Otherwise your button action will not be responsive enough.

Yes, i wrote it like you said, but then i get the error at button.attach( BUTTON_PIN , INPUT_PULLUP). I wrote it like this: button.attach(button, INPUT). The error says "request for member  'attach' in '12' // (i defined the button to pin 12), which is of non-class type 'int'" What does this mean?

The code that I showed is from the examples of the Bounce2 library. button is an instance of that class, not the pin number like you tried. Please refer to the examples, that come with the Bounce2 library, and learn how to use the library. Then you should be able to write the button code

You "#define button 12". So the precompiler modifies "button.attach()" to "12.attach()", thus the error message.

To avoid those errors (especially in larger programs), try to use different terminology for constants and variables/objects. Usually you will #define BUTTON 12, so button may be used as variable without errors. And do not define a pin number at the start when you do not use the definition later on - use pinMode(BUTTON, INPUT) and digitalRead(BUTTON) - it will save you hours of debugging later on.


text:
Possible impedance problem when moving to new power supply
I'm working on building an LED matrix and I'm using an LED strip to create it. I've worked through a simple wiring setup using my bench top power supply and got a strip test working.
Now that I have the actual fabrication done I want to move the power from my bench top supply to a regular wall adapter supply.
The problem I'm running into is that when I provide power from the wall supply the led strip no longer gets the data from the signal pin.While troubleshooting I connected my multimeter to the signal pin and all of a sudden the strip's first LED got the signals and started lighting up.
I'm assuming I'm running into an impedance issue, but I'm not sure why or how to solve it other than trying different resistor values on the signal pin to overcome the issue.
Here's a rough diagram. there's not a lot to it:

I couldn't find info on the forward voltage of the strip or a datasheet for it, so I turned all of the LEDs white and looked at the current draw on my bench top supply:

So the whole matrix is pulling 1.5 amps.
The trinket M0's GPIO voltage is 3.3v, so if I'm thinking about this right to figure out the resistor I need I would use ohms law:
r = V/I

So in my case:
r = 3.3/1.5 = 2.2ohm

Is that right? While I know some I still feel like a novice and I'm working alone and teaching myself, so I'm not sure if I'm thinking of everything correctly.
I also shot a video showing what's happening if that helps: https://vimeo.com/496062949
UPDATE
And actually to simplify things further, I just tried moving the trinket over to the external power supply as well and I get the same issue.
So even with this diagram:

Update
A closer look at the all-on-the-wall-adapter circuit:

The resistor is on a signal line. There should hardly be any current there. I don't thing it's anything to do with that resistor. Have you tried powering the trinket from the same 5V brick, instead of USB? I think it might be a eathing problem. The bench power supply is mains earth referenced, while the brick is probably floating. Are you also really sure the grounds are connected? Maybe there's a loose breadboard connection.

WS2811 expected a minimum of 0.7xVdd for a logic high signal, which is 3.5V. You're marginal at best even if everything is grounded properly. You should level-shift that signal. (And indeed that LED isn't a dropping resistor - your Trinket would have blown up long ago if you tried to feed 1.5A through one of its pins.)

Yeah I moved everything to the wall adapter and  I double checked the ground connection and it's good, but still have the issue. I'm adding a new pic in of the circuit.

@Mat how would i do that level shift? Is this a case where I'd need to add a transistor to provide a higher voltage signal (e.g. pull the 3.3 from the trinket's top right pin) and then control the transistor with my signal pin? Ah wait, I forgot it can't be the 3.3v pin b/c we'd need 3.5, so maybe a voltage divider coming off the 5v power?

go back to the two power supply setup ... remove the ground connection between the two power supplies ... connect a ground wire directly from the trinket to the LED strip

@jsotola, what's the reasoning behind it? Don't the grounds need to be common?

For level shifting up you need a transistor, that switches the higher voltage via the lower voltage pin. Try it, then we can go further

What happens if you replace the brick with your lab-power-supply (without the USB)? Have you measured the voltage coming out the the brick?

@ChrisSchmitz the ground is common between the triket and LED strip ... the difference is that the grounds are not connected through the power supply wires   .... my thinking is that the power supply wires could introduce a voltage drop, which would raise the ground pin of the LED strip with respect to the ground pin of the trinket


text:
button connection without connection to 5V pin
There are two types of tutorials for buttons:

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.

There is a pullup resistor you don't see in the diagram because it is internal to the Arduino. I have added it in red. To make pin 7 an input, you can write:
digitalWrite(7, INPUT_PULLUP);

, which not only makes the pin an input but also engages the internal ~20K pullup  resistor.
So, you're right about the first diagram - it looks like the pin is left floating. Without the code, or an explanatory note, the pullup resistor isn't documented. In such a diagram, once you are familiar with the processor and know that there are optional pullups on the pin-drivers, you can assume that the optional pullup will be used.

Update: I drew in the resistor assuming the red rail was connected to 5v - I should have drawn that in, too.

Just note that with the pull-up the signal is inverted from when you use a pull-down. That is; digitalRead will return LOW when the button is pressed, and HIGH when not pressed. For a beginner, this can be a bit counter-intuitive. I guess that's why a lot of tutorials use this method. It also shows the actual resistor, instead of using the internal one you can't see. Once you understand how things work, and how you shouldn't leave pins floating, you'll probably end up using the internal pull-up method, since it's easier to wire up.

Second note; some MCUs also have pull-down resistors. In that case you can use both methods, without having to add a resistor. Though with laying out a PCB, it's often easier to connect the other leg of the button to GND, that to Vcc. So I'd still prefer the pull-up method.

For inverted signals such as this, I remind myself in an end-of-line comment that the signal is active-Low, and often I'll make signal condition name, such as PRESSED in this case, and #define PRESSED LOW. As often as I take advantage of the built-in pullup, guess who still trips over his own code when skimming it quickly!

The digital pins of an Arduino UNO, or rather the AVR microcontroller used in the UNO, have optional internal pull-up resistors that can be enabled with the INPUT_PULLUP option to pinMode.  When you use INPUT_PULLUP (as opposed to INPUT) there is a functional resistor somewhere between 20kOhm and 50kOhm connected between VCC ("5V") and the digital pin.  When you account for this internal resistor enabled, the circuits in your two images are structurally mirror images of one another:

The boxed numbers here are just to clarify what nodes in the wiring diagram correspond to what nodes in the schematic representation.  Don't ask where box number 5 is; it's a mystery.  I chopped part of the original second image so a new GND connection was hand-drawn in.
In your first image (left) the code would have to enable the internal pull-up resistor to establish a default HIGH state on the digital pin.    With INPUT_PULLUP enabled you can imagine that internal resistor there when comparing with your second image (right).  Here I've drawn a resistor symbol over the board to represent the internal one when enabled.  When the button is pushed some current is drawn through that internal pull-up and the voltage at the pin falls to ground.  Note you could just as easily have an external resistor there and use plain INPUT mode.
Your second example image (right) is using an external pull-down resister to establish a default LOW state.  So when you push the button, the signal rises toward 5V/VCC or HIGH, and some current flows through the pull-down resistor. This would be used with INPUT mode rather than INPUT_PULLUP; I have not annotated an internal pull-up on the right to indicate that the pull-up is not enabled in this scenario (plain INPUT mode).  Note that if you were to enable the internal pull-up in this second configuration it would form a voltage divider with external pull-down; for the 10K external pictured this could result default voltage at the pin which is only bordering on being a proper LOW.
Some people find it less confusing to have a HIGH state when the button is pushed and also using an external resistor like this helps to explain the concept having a pull resistor altogether, because you can see it.  In practice though, it's nice to able to use the internal resistors even if they pull in a more confusing direction.  Note there do exist microcontrollers have optional internal pull-down resistors as well, but they're not as common; the UNO in particular does not have these.


text:
Wire.endTransmission(false) hanging the program after running once when using MPU6050
For this project, I was using an Elegoo Car V3 and I was trying to add a gyroscope onto it. When I run the code for the car, my loop code iterates once and it is always able to read the sensor data. But after that, the program starts hanging. I traced back the problem to the Wire.endTransmission(false) line in my code. For some reason, that line was not completing the second time.
I spent a few hours trying to find a solution online. I triple checked my wiring and still, I could not find a solution to this problem.
Thank you for taking the time to help me!
This is the output of the program
RawX= 82
RawY= 241
RawZ= -1
-----------------------------------------
AngleX= 195.41
AngleY= 216.93
AngleZ= 200.14
-----------------------------------------

And this is the code

#include <Wire.h>

const int MPU_addr = 0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int minVal = 265;
int maxVal = 402;

double x;
double y;
double z;
int c = 0;

//www.elegoo.com

//     Right motor truth table
//Here are some handy tables to show the various modes of operation.
//  ENB         IN3             IN4         Description
//  LOW   Not Applicable   Not Applicable   Motor is off
//  HIGH        LOW             LOW         Motor is stopped (brakes)
//  HIGH        LOW             HIGH        Motor is on and turning forwards
//  HIGH        HIGH            LOW         Motor is on and turning backwards
//  HIGH        HIGH            HIGH        Motor is stopped (brakes)

// define IO pin
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11

//set car speed
#define CAR_SPEED 100
typedef unsigned char u8;  //Change the name of unsigned char to u8

void forward(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void back(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void left(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void right(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void stop()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
}

int getGyroData() {
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);
    Wire.endTransmission(false);

    Wire.requestFrom(MPU_addr,6,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");

}

void turn(int degrees) {
    int *originalData;
    originalData = getGyroData();
    int originalTurn = originalData[2];

    bool notDone = true;

    while (notDone) {

        int *newVal;
        newVal = getGyroData();
        int newTurn = newVal[2];

        int change = originalTurn - newTurn;
        Serial.println(change);
    }
}

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  pinMode(IN1, OUTPUT);//before useing io pin, pin mode must be set first
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  Serial.begin(9600);

}

void loop(){
    c++;

    Serial.println(c);
    Wire.beginTransmission(MPU_addr);
    Serial.println(c);
    Wire.write(0x43);
    Serial.println(c);
    Wire.endTransmission(false);

    Serial.println(c);
    Wire.requestFrom(MPU_addr,4,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();
    Serial.println(c);

    Serial.print("RawX= ");
    Serial.println(AcX);

    Serial.print("RawY= ");
    Serial.println(AcY);

    Serial.print("RawZ= ");
    Serial.println(AcZ);
    Serial.println("-----------------------------------------");

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");
    delay(500);

}

This is a schematic of the car I found

In the comments below, @chrisl makes something explicit that I hadn't in previous edits.  Reading it first may make the below easier to interpret:

Useful fact about I2C on Arduino: Wire.endTransmission() is the
function, that actually does the I2C communication. Before that (all
the Wire.beginTransmission() and Wire.write() calls) no data will run
over the bus, just placed inside the libraries buffer. Thus a hanging
Wire.endTransmission() equals a blocked I2C bus.

On the UNO the A4 and A5 are SDA and SCL, the same signals that are available near AREF and pin 13 on the other side of the board.
So, the ultrasonic range finder in the picture is attached the signals that are needed to operate the I2C ("Wire") bus, and may easily be interfering with Wire.endTransmission(false).  One of the I2C signals is probably causing the range finger to trigger during I2C traffic.  After each trigger, the echo signal from the range finder would then interfere with the connected I2C bus signal.
You could try bit banging I2C using a library instead of the native I2C that is on A4/A5, and use that to operate your gyroscope.  According to your diagram, A0 through A3 are unused, and seem to be the only signals unused from the UNO.  Despite being "analog" pins they function as digital pins also and should work fine for bit-banging.  Getting to them may be a pain though, since the shield doesn't seem to make them available again as pins.
Or you may be able to route the ultrasonic sensor away from A4/A5 either by not plugging it into the header on the shield and instead route the signals from the plug to where an unused set of pins is available (again A0 though A3) and then updating the code accordingly.  Another possibility might be leave it plugged into the shield but bend the A4 and A5 pins to the side so they don't enter the UNO below, and use jumpers to route them from the bent pins to some other pair of available pins; you won't be able to bend them back and forth more than once or twice, so I would be careful with trying that.

Useful fact about I2C on Arduino: Wire.endTransmission() is the function, that actually does the I2C communication. Before that (all the Wire.beginTransmission() and Wire.write() calls) no data will run over the bus, just placed inside the libraries buffer. Thus a hanging Wire.endTransmission() equals a blocked I2C bus.

Yeah, I probably should have been explicit about that.  Will edit it later to incorporate your comment.

@timemage This worked like a charm! Removing the ultrasonic sensor allowed the gyro to function. Thank you for answering so quickly! I just wanted to ask you why the A4 and A5 pins are used for the SDA and SCL communications pins. Can I use any other analog pins for the Gyro?

I may try to update the answer to be more explicit that.  A pin on the AVR may have have special functions beyond being a plain GPIO pin (digitalRead/digitalWrite capable) or connected to the analog to digital converter (analogRead capable).  I2C/TWI "Wire" is a special function found only on the A4 an A5 pins of the UNO.  The ultrasonic sensor by comparison uses only generic GPIO functionality that can be had on nearly any pin.  So it makes sense to put the gyro on A4/A5 and move the ultrasonic sensor to A0-A3 when that's possible.

Using I2C/Wire without the aid of the chip's native support for I2C is what "bit banging" means essentially.

To clarify, the the fact that native I2C/Wire functionaly exists on the same pins as some analog input functionality is a matter of how the ATMega328P chip was constructed and not a design choice made for the Arduino UNO.


text:
couldn't connect to MQTT broker via esp8266/32 and pub/sub client
I want to use hiveMQ public broker in my project that's the same broker as what available in PubSubClient esp8266 examples but when I change WiFi SSID and password in example and upload it I got this output:
Connecting to <SSID NAME>
........
WiFi connected
IP address:
192.168.1.14
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...

I tried this with pubsub client v2.8/v2.6/v2.4 and esp32 latest version and esp8266 latest version and 2.3
in response to the comment as I said my code is esp8266_basic example in the PubSub client examples and here is my code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "<SSID>";
const char* password = "<PASS>";
const char* mqtt_server = "broker.mqtt-dashboard.com"; //tested with broker.mqttdashboard.com

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883); //8000 and 1883 tested
  client.setCallback(callback);
}

void setup_wifi() {

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

  WiFi.begin(ssid, password);

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

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {

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

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

on esp32 I remove pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output and
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

sections and includes
and sometimes output is like this:
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected

Obviously there is a problem but beyond that who knows?  All you have said is that this is an ESP8266 and you get getting an MQTT connection error.  Please add some additional details.

It is not at all clear what you are asking. Does your code make a succesfull MQTT connection, does it not connect, does it connect sometimes or does it disconnect sometimes? Does it work when it's connected? Why did you remove the pinMode() on the ESP32. BTW why do you use the deprecated BUILTIN_LED instead of LED_BUILTIN ?

@StarCat thanks for commenting, about removing pinMode, I do it because I just need to test it for MQTT and BUILTIN_LED makes a compiler error that says that's not declared and that's about LED and not important for connection
and absolutely board doesn't connect to the broker (some times in my tests on another version of Arduino IDE on an older system I got connection successful message but nothing published or subscribed)

rc=-4 means MQTT_CONNECTION_TIMEOUT, rc=-2 means      MQTT_CONNECT_FAILED, given that you are accessing a public-facing MQTT web service site, the chances are you would need to connect it with username and password in addition to the ClinetID, so you might need to change client.connect("ESP8266Client") to (mqttClient.connect(clientID,mqttUserName,mqttPass)).

I found this video as a problem solver, This may help you.
All MQTT Errors explained very well and Suggester Different troubleshooting techniques
https://youtu.be/CbodTTk-D18

Thanks a lot for your answer But as I mentioned that issue was made because I live in a country with network censorship. When I changed my network provider everything worked fine.
Finally after a week the first network provider I tested with fixed that issue and now everything works

all things are OK and the problem is about my network I think there blocked MQTT (cause I couldn't connect any broker and not just hiveMQ) or other related things cause also my notebook doesn't connect I changed my network provider and the problem fixed
if you ran into the same issue, check other stuff and finally check with a computer in your network (don't use things like http://www.hivemq.com/demos/websocket-client/)


text:
Node MCU code is stuck in while (WiFi.status() != WL_CONNECTED)
I am using the Node MCu V3 board ESP8266MOD
Board Manager Version: 2.7.4
Arduino IDE: 1.8.12
My code is stuck in the while (WiFi.status() != WL_CONNECTED)
Here is code:
#include <ESP8266WiFi.h>        // Include the Wi-Fi library

const char* ssid = "ESP8266TestNet";  // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "ESP8266Test"; // The password of the Wi-Fi network

void setup() {
  Serial.begin(9600); // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password); // Connect to the network

  Serial.print("Connecting to ");
  Serial.print(ssid);
  Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}

void loop() {
  delay(10000);
  Serial.println(WiFi.status());
}

After downloading the code above for setup connection I am using mobile WiFi for connection.
In the mobile settings I can see the WiFi is connected to the ESP Board but when I monitor the Serial it seems that the code is stuck in the while loop.
If I comment out the while loop the board is giving a WDT reset.
Any ideas? I have been stuck for a long time.
Here I have attached the tools setting of the Arduino IDE:

Are you on a breadboard? Those can interfer badly with wifi, though it's weird that you see the esp connect to the access point... maybe, the connection fails right after it has been established and within the one second interval you're polling the wifi state (smartphones wifi settings are typically not updated immediately). You could try to remove the 1000ms delay for a test

Make sure the SSID and password match your WiFi Access point. 2) Make sure your WiFI Access Point is operating on 2.4GHz, not on 5GHz band because ESP only supports 2.4GHz.

"I can see the WiFi is connected to the ESP Board"  - what does that mean? Does your ESP run as Access Point? And if yes, why? NB: The WDT reset occurs because in "delay(10000)" the WDT is not fed, and Soft WDT timeout is much less than 10 seconds.

the settings in Tool are not right. select NodeMcu 1.0


text:
ESP32 Compile Error - Face tracking Pan and tilt camera Arduino
I have been working on a code for a project of mine. I am making an face tracking Pan and tilt camera using the ESP32, but I am getting some errors that I do not know how to solve.
#include <ArduinoWebsockets.h>
#include "esp_http_server.h"
#include <WiFi.h>
#include "camera_index.h"
#include "esp_camera.h"
#include "fb_gfx.h"
#include "fd_forward.h"

const char* ssid = "NSA";
const char* password = "Orange";

// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 180)
{
  // calculate duty, 8191 from 2 ^ 13 - 1
  uint32_t duty = (8191 / valueMax) * min(value, valueMax);
  ledcWrite(channel, duty);
}
int pan_center = 90; // center the pan servo
int tilt_center = 90; // center the tilt servo

#define CAMERA_MODEL_AI_THINKER
#include "camera_pins.h"

using namespace websockets;
WebsocketsServer socket_server;

static inline mtmn_config_t app_mtmn_config()
{
  mtmn_config_t mtmn_config = {0};
  mtmn_config.type = FAST;
  mtmn_config.min_face = 80;
  mtmn_config.pyramid = 0.707;
  mtmn_config.pyramid_times = 4;
  mtmn_config.p_threshold.score = 0.6;
  mtmn_config.p_threshold.nms = 0.7;
  mtmn_config.p_threshold.candidate_number = 20;
  mtmn_config.r_threshold.score = 0.7;
  mtmn_config.r_threshold.nms = 0.7;
  mtmn_config.r_threshold.candidate_number = 10;
  mtmn_config.o_threshold.score = 0.7;
  mtmn_config.o_threshold.nms = 0.7;
  mtmn_config.o_threshold.candidate_number = 1;
  return mtmn_config;
}
mtmn_config_t mtmn_config = app_mtmn_config();

httpd_handle_t camera_httpd = NULL;

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

  // Ai-Thinker: pins 2 and 12
  ledcSetup(2, 50, 16); //channel, freq, resolution
  ledcAttachPin(2, 2); // pin, channel

  ledcSetup(4, 50, 16);
  ledcAttachPin(12, 4);

  ledcAnalogWrite(2, 90); // channel, 0-180
  delay(1000);
  ledcAnalogWrite(4, 90);

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if (psramFound()) {
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif
  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  s->set_framesize(s, FRAMESIZE_QVGA);

  WiFi.begin(ssid, password);

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

  app_httpserver_init();
  socket_server.listen(82);

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
}

static esp_err_t index_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "text/html");
  httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
}

httpd_uri_t index_uri = {
  .uri       = "/",
  .method    = HTTP_GET,
  .handler   = index_handler,
  .user_ctx  = NULL
};

void app_httpserver_init ()
{
  httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  if (httpd_start(&camera_httpd, &config) == ESP_OK)
    Serial.println("httpd_start");
  {
    httpd_register_uri_handler(camera_httpd, &index_uri);
  }
}

static void draw_face_boxes(dl_matrix3du_t *image_matrix, box_array_t *boxes)
{
  int x, y, w, h, i, half_width, half_height;
  fb_data_t fb;
  fb.width = image_matrix->w;
  fb.height = image_matrix->h;
  fb.data = image_matrix->item;
  fb.bytes_per_pixel = 3;
  fb.format = FB_BGR888;
  for (i = 0; i < boxes->len; i++) {

    // Convoluted way of finding face centre...
    x = ((int)boxes->box[i].box_p[0]);
    w = (int)boxes->box[i].box_p[2] - x + 1;
    half_width = w / 2;
    int face_center_pan = x + half_width; // image frame face centre x co-ordinate

    y = (int)boxes->box[i].box_p[1];
    h = (int)boxes->box[i].box_p[3] - y + 1;
    half_height = h / 2;
    int face_center_tilt = y + half_height;  // image frame face centre y co-ordinate

    //    assume QVGA 320x240
    //    int sensor_width = 320;
    //    int sensor_height = 240;
    //    int lens_fov = 45
    //    float diagonal = sqrt(sq(sensor_width) + sq(sensor_height)); // pixels along the diagonal
    //    float pixels_per_degree = diagonal / lens_fov;
    //    400/45 = 8.89

    float move_to_x = pan_center + ((-160 + face_center_pan) / 8.89) ;
    float move_to_y = tilt_center + ((-120 + face_center_tilt) / 8.89) ;

    pan_center = (pan_center + move_to_x) / 2;
    Serial.println(pan_center);
    ledcAnalogWrite(2, pan_center); // channel, 0-180

    tilt_center = (tilt_center + move_to_y) / 2;
    int reversed_tilt_center = map(tilt_center, 0, 180, 180, 0);
    ledcAnalogWrite(4, reversed_tilt_center); // channel, 0-180

  }
}

void loop()
{
  auto client = socket_server.accept();
  camera_fb_t * fb = NULL;
  dl_matrix3du_t *image_matrix = NULL;

  while (true) {
    client.poll();
    fb = esp_camera_fb_get();
    image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3);

    fmt2rgb888(fb->buf, fb->len, fb->format, image_matrix->item);

    box_array_t *net_boxes = NULL;
    net_boxes = face_detect(image_matrix, &mtmn_config);

    if (net_boxes) {
      draw_face_boxes(image_matrix, net_boxes);
      free(net_boxes->score);
      free(net_boxes->box);
      free(net_boxes->landmark);
      free(net_boxes);
    }

    client.sendBinary((const char *)fb->buf, fb->len);

    esp_camera_fb_return(fb);
    fb = NULL;
    dl_matrix3du_free(image_matrix);
  }
}

The error that occured was in this section of code:
static esp_err_t index_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "text/html");
  httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
}

I got this error in the compiler:
‘index_ov2640_html_gz’ was not declared in this scope

Any ideas on why this happened? Thanks.

That variable is not declared in the code, that you show. What is it and whete did you eant to declare it?


text:
l298n voltage loss when motor attached
Im trying to power a brushless DC Motor (Tamiya 300054358) through the l298n attached to an Arduino.
The l298n is powered by an external 9V source and the logic of the l298n is powered by the Arduinos 5V, wich is also powered by the 9v.
Both components using the same ground.
The code looks good and i can successfully adjust the power-output for the motor between 6-9V.
As soon as is attach the Motor, the volage drops do somewhere around 0-1V and the motor isnt turning.
When i attach the motor directly to the power source, it runs fine, so the power should be enough. (in the original RC car its powered by an 7V battery).
I tried some smaller motors just to be sure and the problem is similar. The motor is turning, but very slowly.
I also tried to connect the batterypack instead of the extern power source just ending up with the same result.
Do you have any ideas, where the problem could be at?
Thanks in advance

The problem is in the H driver. You lose about 1.4 volts on each leg so your loss from the battery is about 2.8 volts. The internal driver transistors are in a darlington configuration. If the bridge were Power MOS instead of bipolar transistors your voltage would be dependent on the resistance of the MOSFETs. Typically a few tenths of a volt in total. If your 9V source is a battery you probably are not getting the 9V you are expecting.

From an L298N datasheet:

TOTAL DC CURRENT UP TO 4 A

From motor's "datasheet":

I'm no expert in electric motors and driving them, not even sure I'm novice level, but I just don't see you driving a motor anything near this current draw with this part.  If by some miracle you can, it will be horribly inefficient owing to the losses associated with the voltage drops that Gil mentions.
For a motor that operates with this much current I would expect a practical h-bridge setup to have discrete mosfets, perhaps mounted to a heatsink.

ah okay. So if im getting this right, i need a Mosfet witch is capable of handling 150A.
So something like this?
https://www.reichelt.de/mosfet-n-ch-150v-150a-680w-0-011r-sot223b-ixfn180n15p-p257219.html
As you can see im quite new to this and im just not sure with these numbers.
Thanks for your help!

I would like to address some of this, but I really can't answer it well, less so in a comment.  Probably the best thing to do is to ask about appropriate driving circuity for that motor on the electronics SE.  If you want to try to ask here, it would probably be similar, but less open ended, e.g. "is there an Arduino-friendly shield/module that can handle this motor's current requirements?"; I don't know how well that will go though.

I will just caution you that there's a lot more to it than picking a FET by datasheet where the large current shown in the datasheet is greater or equal to your motor current.  That number is often a maximum current for some pulse usage scenario which may not match how you're actually trying to use the FET.  And I'm sure there are other factors to consider.

thanks for your advice! I really should try to get into these things deeper first.


text:
SIM7000E Waveshare can't do anything
Can someone help me? I'm using a sim7000e from Waveshare. One week ago it was working normally, but now it doesn't work at all; it even can't read the RX-TX communication.
#include <SoftwareSerial.h> //koneksi ke modem

#define TINY_GSM_MODEM_SIM7000
#define TINY_GSM_DEBUG SerialMon
#define BAUD 9600
#define SerialMon Serial

const byte rxpin = 2;
const byte txpin = 3;

SoftwareSerial SerialAT(rxpin, txpin); // RX, TX

That's  my code for connecting to the Arduino. I believe it from my Arduino, but I don't know if something wrong from Arduino.
My 5V (sim7000E) to 5V (arduino mega2560), GND to GND.
Because I'm using Putty on USB for reading my AT-cmd it doesn't and has some trouble.

Your rxpin on Arduino Mega2560 connect to which pin on SIM7000E?

Rx2=TX sim
Tx3=RX sim

I'm having similar issues, although it could well be my fault!
I can't see any coding sending AT commands, or waiting for responses in your example.
Try running your TX pin to your RX pin on your Arduino (take the SIM7000e out of the equation completely).  If your code works, then the issue is elsewhere.
I've tried connecting via USB and that seems through a terminal.  I was able to connect to a mobile network using the AT command
AT+CSTT="cmnet"

Just to add further context, the Raspberry PI header pins use a lower TTL voltage.   Connecting to the other headers at the end of the board will give you compatible UART levels.
Why your board has stopped working suddenly is a bit of a mystery, without proper context of pinouts,connectivity, power, etc.


text:
incompatible types in assignment of 'const String' to 'char [32] using server.arg
I am trying to create a class and getting getting the error
incompatible types in assignment of 'const String' to 'char [32]

when I declare
char inString[32];

and try to set it as
inString = server.arg("x");

I tried
inString = server.arg(sizeof("x"));

and got the same error.
full code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

const char* ssid = "myssid";
const char* password =  "password";

char inString[32];

void webpage() {
  server.send(200, "text/html", "<form  name='frm'  method='post'><input type='text' name='x'   ><input type='submit' value='Submit'>   </form>");
}
void response(){
  if(server.hasArg("x") && (server.arg("x").length()>0)){ // TODO check that it's not longer than 31 characters
    Serial.print("User entered:\t");
    Serial.println(server.arg("x"));
    inString = server.arg("x");
    server.send(200, "text/html", "
Successful
Home");
  } else {
    server.send(400, "text/html", "
HTTP Error 400

Bad request. Please enter a value.
");
  }
}

void setup() {

    Serial.begin(115200);
    WiFi.begin(ssid, password);  //Connect to the WiFi network

    while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

        delay(500);
        Serial.println("Waiting to connect...");

    }

    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());  //Print the local IP

    //server.on("/body", handleBody); //Associate the handler function to the path
    server.on("/",HTTP_GET, webpage);
    server.on("/",HTTP_POST,response);

    server.begin(); //Start the server
    Serial.println("Server listening");

}

void loop() {

    server.handleClient(); //Handling of incoming requests

}

how to I match my datatypes when using server.arg?
The other post I find related to a pointer which I am not using.

server.arg returns String so use String inString;

@Juraj Worked like a champ! Post it as an answer and I'll give proper thanks.


text:
Program ESP01 and keep it after reboot
I am bit of a noob when it comes to ESP programming. I have an ESP01 and a USB programmer for it, but every time I unplug it, it resets, which makes me wonder how can I make it battery-powered since every reboot resets the program.

What do you mean by 'reset the program'? The uploaded program should be retained on the esp01 and start running again after a reset/reboot.

Are you sure, that the program was correctly written to the ESP? How do you see, that the program is not working?

I wrote a simple blink program which made it blink when it was programmed.. But once i remove the usb programmer with the esp on, the turns off due to loosing power and when i then plug it in. I start as it was reset.. I flash it using arduino

It stops blinking in the intended frequency

if you have io 0 to ground it always goes into flashing mode. you have to pull-up io 0

The ESP-01 ... and all ESP8622 ... have two modes for operation.

Flash mode / Boot load mode - on bootup (at the time an electrical current is first applied, or after the reset pin is grounded), if the GPIO0 (GPIO Zero) pin {On the ESP-01 this is the 7th pin} is connected to ground, the chip goes into non-run, receive program mode.  This is where you load the compiled program.

Normal - on bootup (as above), but GPIO0 is NOT ground, then the ESP-01 goes into run mode.

I had it in flash mode all the time.


text:
Why do I get different results when compiling the same code with different ide?
I have a basic code about reading true rms.I compiled the same code with arduino ide and atmel studio, then ran it in a proteus simulation.I'm trying to measure how long the read_rms() function takes.
My mcu:attiny84
1.experiment)I have added board to arduino ide with board manager.And I chose attiny84 and internal 1Mhz from tools menu in arduino menu.
The result was that the read_rms() function took 23.25 milliseconds.
2.experiment)I compiled the same code without any changes in Atmel Studio.Device,attiny84 selected.
The result was that the read_rms() function took 44 milliseconds.
44 miliseconds vs 23.25 miliseconds. Why?
Note:The following settings are selected in the proteus.Internal RC Osc. 8 Mhz,and CKDIV8=Programmed.
My code:
#define F_CPU 1000000UL
#include <avr/io.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
const uint8_t muxbits = 1<<MUX3 | 1<<MUX2 | 1<<MUX1 | 1<<MUX0;

void adc_init()
{
    ADMUX = 0;    //Vcc_ref_
    ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS0); //adc_enable_and_prescaler_8_ 125000 Hz (1000000/8)
    //first_try
    ADCSRA |= (1<<ADSC);
    while ((ADCSRA & (1<<ADSC)) != 0);
}

uint16_t adc_read(uint8_t channel)
{
    ADMUX = (ADMUX & ~muxbits) | channel;
    // start_single_convertion
    ADCSRA |= (1<<ADSC);

    // wait for conversion to complete
    while ((ADCSRA & (1<<ADSC)) != 0);

    return (ADC);
}

double read_rms()
{
    uint16_t i=0;
    uint16_t a_data=0;
    uint32_t sum=0;
    float avarage=0;
    double rms=0;
    for(i=0;i<200;i++)
    {
        a_data=adc_read(1);

        sum=sum+(a_data*a_data);
    }
    avarage=(float)sum/200;
    rms=sqrt((double)avarage);

    return rms;

}

int main(void)
{

    DDRA|=(1<<7);
    PORTA &=~ (1<<7);
    adc_init();

    while(1)
    {

    read_rms();
    PORTA ^= (1<<7);// TOOGLE_PA7   for_measure_time_of_read_rms()_with_oscilloscope

    }
}

Impossible to tell. Maybe Atmel studio is using actual double-precision values for double whereas Arduino uses only float (single precision).

It's not impossible to tell. You could compare the assembler generated by both. I'm not very familiar with AVR assembler, so I wouldn't be the best choice to do that analysis, but  I'm sure somebody on this board could suss it out.

You could also get something of a fuzzy confirmation on whether float vs double is responsible by just altering your code to make use of float types everywhere.  This includes using sqrtf rather than sqrt.  As said, there may still be other differences, so the timing results may not completely converge.

Different compilers produce different machine code.
As Majenko pointed out, the Arduino IDE's compiler, which happens to be GCC, uses float even when you write double.
The Atmel Studio creates double for double, using twice as much bits.
Calculating with more bits takes longer.

I did float.the result is the same again.And I did sqrtf instead of sqrt.

Did you look into the generated assembly? There might be some implicit conversions to double, or Atmel's compiler uses the standard sqrt() even for sqrtf().

no I haven't examined.But,Why would there be such a thing?Instead of sqrt I typed sqrtf because I didn't want to use double numbers unnecessarily. As for the main problem, I think it's related to compiler configurations. But I haven't figured it out yet.