body:
    #include <Keypad.h>

    const int ROW_NUM = 4; //four rows
    const int COLUMN_NUM = 3; //three columns

    const int PIN_RED = 2;
    const int PIN_GREEN = 3;
    const int PIN_BLUE = 4;

    const int MOTOR_PIN1 = 5;
    const int MOTOR_PIN2 = 13;

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

    byte pin_rows[ROW_NUM] = {12, 11, 10, 9};
    byte pin_column[COLUMN_NUM] = {8, 7, 6};

    Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );

    const String password_1 = "6113";
    const String password_2 = "4613";
    String input_password;

    void setup(){
      Serial.begin(9600);
      input_password.reserve(32); // maximum input characters is 33, change if needed
    }

    void loop(){
         loop_RGB();
         loop_DCMOTOR();
    }

    void loop_RGB(){
      char key = keypad.getKey();

      if (key){
        Serial.println(key);

        if(key == '*') {
          input_password = ""; // reset the input password
        } else if(key == '#') {
          if(input_password == password_1) {
            Serial.println("password is correct");

      analogWrite(PIN_RED,   255);
      analogWrite(PIN_GREEN, 0);
      analogWrite(PIN_BLUE,  0);

      delay(1000); // keep the color 1 second

      analogWrite(PIN_RED,   0);
      analogWrite(PIN_GREEN, 255);
      analogWrite(PIN_BLUE,  0);

      delay(1000); // keep the color 1 second

      analogWrite(PIN_RED,   0);
      analogWrite(PIN_GREEN, 0);
      analogWrite(PIN_BLUE,  255);

      delay(1000);
          } else {
            Serial.println("password is incorrect, try again");
          }

          input_password = ""; // reset the input password
        } else {
          input_password += key; // append new character to input password string
        }
      }
    }

    void loop_DCMOTOR(){
      char key = keypad.getKey();

      if (key){
        Serial.println(key);

        if(key == '*') {
          input_password = ""; // reset the input password
        } else if(key == '#') {
          if(input_password == password_2) {
            Serial.println("password is correct");

         digitalWrite(MOTOR_PIN1, HIGH);
         digitalWrite(MOTOR_PIN2, LOW);
         delay (3000);

          } else {
            Serial.println("password is incorrect, try again");
          }

          input_password = ""; // reset the input password
        } else {
          input_password += key; // append new character to input password string
        }
      }
    }

title: I want to have separate Keypad passcodes to light up an RGB and run a DC Motor in one code. 6113 for RGB and 4613 for the DC Motor

Answers: 2

body:
write 3 functions, one to receive the password, one to run the DC motor, one to drive the LED. Now in the function to receive the password use an array of 4 bytes to store the password and the 'x' button to clear the array. The function should run a for loop to receive all the 4 digits and the "x" key should break the loop and clear out the array.
You can write the RGB and Motor driver function as per your needs.
In the main loop, you should receive the password and then process this password to run the RGB or motor using a if-else condition.
For any further query feel free to clarify.

body:
In this program, the functions `loop_RGB()` and `loop_DCMOTOR()` are
taking turns to try to read the password. If you hit `#` after typing
the password for the LED, and `loop_DCMOTOR()` happens to to read your
key press, it will tell you the password is wrong, and reset what you
have typed.

As already stated in a comment and an answer, the solution is to read
the keypad in only one place. You could write a dedicated function for
this, but I would instead just put this code in loop:

```c++
void loop() {
    char key = keypad.getKey();

    if (key) {
        Serial.print("key pressed: ");
        Serial.println(key);
        if (key == '*') {  // '*' means reset the input
            input_password = "";
        } else if (key == '#') {  // '#' means validate the input
            if (input_password == password_1) {
                Serial.println("Corect RGB LED password.");
                actuate_LED();
            } else if (input_password == password_2) {
                Serial.println("Corect motor password.");
                actuate_motor();
            } else {
                Serial.println("Incorrect password.");
            }
            input_password = "";  // reset the input
        } else {
            input_password += key;  // append new character
        }
    }
}
```

Here, `actuate_LED()` and `actuate_motor()` are supposed to be small
functions that do the device actuation and nothing more. They do not
concern themselves with the keypad or a password.


body:
I am using MAX7219 8 digit 7 segment displays with Arduino Mega2560. Now, I have to physically space out the displays far from each other. Hence, after a certain distance the displays on the far end start flickering. So, can we setup 2 individual daisy chains using the MAX7219 module with Arduino Mega2560.

Thanks for helping out in advance.

title: How to create 2 individual daisy chains using the MAX7219 Module and Mega2560

Answers: 0


body:
[Here][1] I asked about how to add an hysteresis on ADC readings. The answer received was very good and it worked out of the box.

Still I'm having troubles trying to generalize the `resample` function in order to map the input values to a different range of output values, where the lower rail is **not** zero.

If the lower rail was zero, it would be enough to change the shifts with a multiplication/division for `1024 / max`. But I cannot understand how to handle the lower rail when `min > 0`.

My attempt:

    int Menu::resample(int adc, int *value, byte min, byte max)
    {
        // sanity checks omitted: min < max and max < 128

        double m = 1015.0 / (max - min); // 1015 = 1023 - 8 (1 LSB of low-res output)
                                         // otherwise it reaches 126 even if max = 127
        int q = min << 3;

        int lowerTest = (q + *value * m) - ADC_HYSTERESIS;
        int higherTest = (q + (*value + 1) * m) + ADC_HYSTERESIS;

        int lowerOutput = min + (adc + ADC_HYSTERESIS) / m;
        int higherOutput = min + (adc - ADC_HYSTERESIS) / m;

        if (adc < lowerTest) *value = lowerOutput;
        else if (adc >= higherTest) *value = higherOutput;

        if (*value > max) *value = max;
        if (*value < min) *value = min;
        return *value;
    }

There is something wrong in my math, since the comparison always falls under the first `if` (i.e. `*value = lowerOutput`).

May you help me to fix this code so I can have an hysteresis on any scaled output?

**Note**: instead of using a static variable for value as in the answer, I use a `struct`:

    slider.value = resample(adc, &slider.lastValue, slider.min, slider.max);

where:

    typedef struct
    {
        int value;
        int lastValue;
        int min;
        int max;
    } slider_t;

    slider_t slider;

  [1]: https://arduino.stackexchange.com/q/93117/54202

title: Hysteresis and scaling range

Answers: 1

body:
First, a couple of comments about this first attempt.

There is no point in storing in `slider_t` both `lastValue` and `value`.
The way this is used, both fields are always updated with the same
value: `lastValue` is updated by pointer inside `resample()`, while
`value` is updated by assigning it the value returned by `resample()`. I
would suggest removing the field `lastValue` and either:

1. providing `value` by value (rather than by pointer) to `resample()`,
   or

2. providing a reference to a `slider_t` as the only parameter.

The first approach is better if you want to avoid `resample()` and
`slider_t` being tightly coupled.

Next, there is a mix between `int` and `byte` types. If you want to save
memory, and improve consistency, I would use `byte` for all low-res
values living in the output domain of `resample()`. Actually, I would
use `uint8_t`, which is the same, only more standard.

Then, there are a few things I do not understand in this code:

* Why `1015`? It seems to me this number should be dependent on the
  width of output range.

* Why `min << 3`? Again, this is a division by 8, while the proper
  factor should be probably be output-range dependent.

Now, for the solution, I would try this approach:

* Compute the minimum and maximum possible output values consistent with
  the provided input, accounting for the hysteresis.

* Constrain the output to remain within this bracket.

In code:

```c++
uint8_t Menu::resample(int adc, uint8_t value, uint8_t min, uint8_t max)
{
    value = constrain(value, min, max);  // just in case...
    uint8_t lower = map(adc - ADC_HYSTERESIS, 0, 1024, min, max+1);
    uint8_t upper = map(adc + ADC_HYSTERESIS, 0, 1024, min, max+1);
    return constrain(value, lower, upper);
}
```

Some points worth noticing:

1. I do not know whether this was originally intended, but the Arduino
   function `map(x, in_min, in_max, out_min, out_max)` does a poor job
   at mapping the interval [`in_min`, `in_max`] to [`out_min`,
   `out_max`]. It does, however, do a good job at mapping [`in_min`,
   `in_max`) to [`out_min`, `out_max`) (mind the semi-open intervals).
   This is why the four last parameters of the call to `map()` are (0,
   1024, min, max+1), rather than (0, 1023, min, max).

2. The first call to `constrain()` can be removed if the caller bears
   the responsibility of guaranteeing this precondition.

3. If the precondition is valid (or, like here, enforced), it will also
   hold for the returned value, provided `adc` is within [0, 1024).

This method would be called like this:

```c++
slider.value = resample(adc, slider.value, slider.min, slider.max);
```


body:
I hooked my ESP8266 Wi-Fi module to an ESP-12E Motor Shield and connected it to an RC car. It works fine when connected to my laptop (Goes forward, backward, left, and right. Though the car doesn't seem to turn a lot because of low power). I connected it to a 7.4v power supply, and it works fine, except it only moves forward and only turns right. Doesn't turn the motors the other direction.

I followed this [tutorial][1]. In case, you'd want the code.

I did have a change of code though, this is the only code I changed

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    // These are the pins used to control the motor shield

    #define STEER_MOTOR_POWER D2 // Motor A
    #define STEER_MOTOR_DIRECTION D3

    #define DRIVE_MOTOR_POWER D1 // Motor B
    #define DRIVE_MOTOR_DIRECTION D4

    int drivePower = 1000;

    uint8_t driveDirection = LOW;

    int steeringPower = 1000;

    uint8_t steerDirection = LOW;

    // ----------------
    // Set your WiFi SSID and Password here
    // ----------------
    const char* ssid = "xxxxx";
    const char* password = "xxxxxxxxxxx";

    ESP8266WebServer server(80);

    void setup(void){

      pinMode(DRIVE_MOTOR_POWER, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
      pinMode(DRIVE_MOTOR_DIRECTION, OUTPUT);
      pinMode(STEER_MOTOR_POWER, OUTPUT);
      pinMode(STEER_MOTOR_DIRECTION, OUTPUT);

      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(100);

      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      Serial.println(WiFi.macAddress());

      if (MDNS.begin("WifiCar")) {
          Serial.println("MDNS Responder Started");
          analogWrite(DRIVE_MOTOR_POWER, 10);
          digitalWrite(DRIVE_MOTOR_DIRECTION, driveDirection);
          delay(2000);
          analogWrite(DRIVE_MOTOR_POWER, 0);
      }

        server.on("/car/controls/front", [](){
          Serial.println("front");
          analogWrite(DRIVE_MOTOR_POWER, drivePower);
          digitalWrite(DRIVE_MOTOR_DIRECTION, driveDirection);
          delay(100);
          server.send(200, "text/plain", "front");
        });

        server.on("/car/controls/back", [](){
          Serial.println("back");
          analogWrite(DRIVE_MOTOR_POWER, drivePower);
          digitalWrite(DRIVE_MOTOR_DIRECTION, !driveDirection);
          delay(100);
          server.send(200, "text/plain", "back");
        });

        server.on("/car/controls/stopDirection", [](){
          delay(100);
          Serial.println("stopDirection");
          analogWrite(DRIVE_MOTOR_POWER, 0);
          delay(100);
          server.send(200, "text/plain", "stopDirection");
        });

        server.on("/car/controls/right", [](){
          Serial.println("right");
          analogWrite(STEER_MOTOR_POWER, steeringPower);
          digitalWrite(STEER_MOTOR_DIRECTION, steerDirection);
          delay(100);
          server.send(200, "text/plain", "right");
        });

        server.on("/car/controls/left", [](){
          Serial.println("left");
          analogWrite(STEER_MOTOR_POWER, steeringPower);
          digitalWrite(STEER_MOTOR_DIRECTION, !steerDirection);
          delay(100);
          server.send(200, "text/plain", "left");
        });

        server.on("/car/controls/stopSteering", [](){
          delay(100);
          Serial.println("stopSteering");
          analogWrite(STEER_MOTOR_POWER, 0);
          delay(100);
          server.send(200, "text/plain", "stopSteering");
        });

      server.begin();
      Serial.println("HTTP Server Started");
    }

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

  [1]: https://www.youtube.com/watch?v=0zs-A_fC3Yg&t=133s&ab_channel=BrianLough

title: ESP8266 + NodeMCU Motor Shield spinning motor only in one direction

Answers: 0


body:
I made a simple test circuit to help me understand the [L293D](https://www.arduino.cc/documents/datasheets/H-bridge_motor_driver.PDF) H-bridge that comes with the Arduino starter kit.

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

Digital output pins of the Arduino are wired to the input pins on the H-bridge. Arduino code alternately sends 1/0 and 0/1 down those two output pins, basically (as I understand it) creating an extremely low frequency alternating current in the two output pins on the H bridge. Two LEDs are wired in parallel to the output pins, in opposite directions, so they flash, demonstrating the alternating nature of the current.

The project I'm working on from the starter kit right now is the Zoetrope ([page 102](https://www.eitkw.com/wp-content/uploads/2020/03/Arduino_Projects_Book.pdf)), and in that project the L293D is used to control a motor. The Arduino's 5V is connected to Vss and a 9V battery is connected to Vs.

So I'm a little surprised that I got it to work without using the Vs and Vss pins at all. What are they for? I did try swapping the LEDs out for the motor and it doesn't work (not enough power, I guess). But if I hook the 5V on the Arduino up to the Vs pin, it does! Hooking the 5V up to only the Vss pin, however, is not enough to power the motor.

So I sort of get the idea that without Vs and Vss current, the current from the input pins is enough to light the LEDs, but what I don't understand is:

1. If the voltage on the input pins isn't enough to drive the motor, how come connecting the 5V to the Vs pin is? It's the *same* voltage as is on the input pins.

2. What is the Vss pin for?

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

title: What are the Vs and Vss pins on an L293D chip for?

Answers: 1

body:
As you can see in the linked L293D PDF

**VS** is Supply Voltage (here connect the power source for motor)

**VSS** is Logic Supply Voltage (here connect the power source for the L293D chip logic - usually the same source as for +5V for Arduino)

2. The VSS suplies energy for the L293D to work correctly (like the Enable pin, inputs and such)

Also as you can see on the **BLOCK DIAGRAM** there are some mysterious diodes connected in little unusual way - at least on first look. When everything is well powered and normal, there are closed and do not conduct any current.

But if the voltage on (say) OUT1 became negative, then the lower diode connected to ground would start lead current and pull the OUT1 to the ground.

Similary if the voltage on OUT1 became higher, then the **VS** power source, then the top diode would open and drag the OUT1 down to the VS voltage.

It is for secure the internal circuits to work in sane environment. And if there is a motor (if any other inductance as relay or so), then there will be such peaks.

Similar security diodes are probably also on all input pins. (It is usual in logical circuits to limit input voltage in such way.) As you did not connect the VS to any power, when you send +5V (logical one) to any input pin, it was "pulled down" to VS via some such diode. This effectively "pulled up" the VS near the voltage on the pin and with VS powered the internal logic of L293D begin work, so magic happened.

1. There may be even some similary secured connection between VS and VSS, so some power from your Arduino output pin **leaked** by **long** and **non-planed** way to your LEDs and made them shine. LEDs do not need much current.

When you connected the motor instead, the long way proved to be too long and to have too much rezistence along it, that (nearly) all the voltage was distributed along it and on the motor was nearly nothing - and nearly no current was able go thru. Which is luck, as Arduino output pins have limit of 20 mA of current (or so).

When you conected +5V on the VS pin, there is much shorter way from it to motor and also with a lot less resistance along it, so there was enought voltage and enought current for the motor, so it was able to run.

Try it and measure the resistence of your motor - you will see, it will be nearly nothing, compared to the R=220 you used with the LEDs.

While it may not be visible in such simple example like this, you really **should** power the VSS so the logic there would work reliable.


body:
I have a ESP32-CAM AIThinker which I have programmed using Arduino IDE to stream video.  I have another board ESP8266-12e that I am using on a MQTT system that turns on and off the ESP32 as well as sending it the Name and password of my local network to sign in.  When the ESP32-CAM is on and streaming I can access it on my local network and by port forwarding in my Router I can sign in and view it from anywhere.  I have built a Mac and Android app which will access and stream the ESP32 displaying it inside the app.
I would rather NOT port forward my router.  Is there a way to add some code to the ESP32 so that I could use Apple TV, or the Android equivalent, or HomeKit, to open the port associated with the ESP32 so it can be accessed outside my local network?  Port forward is not real secure and I would like to avoid it if possible.

I have added some code to try to POST the jpg-stream to my WIX website where I added a page with an image.  However even though the website got the POST and it was valid I received a response code 403 FORBIDDEN this is the full response.

    10:25:03.026 -> 403
    10:25:03.026 ->
    10:25:03.026 -> <title>403 Forbidden</title>
    10:25:03.026 ->
    10:25:03.026 ->
403 Forbidden

    10:25:03.026 ->
nginx
    10:25:03.026 ->
    10:25:03.026 ->

Here is the code currently running on the ESP32-CAM;

    #include "src/OV2640.h"
    #include <WiFi.h>
    #include <WebServer.h>
    #include <time.h>
    #include "FS.h"                // SD Card ESP32
    #include "SD_MMC.h"            // SD Card ESP32
    #include <WiFiClient.h>
    #include <EEPROM.h>
    #include <string.h>
    #include <stdio.h>
    //ADDED FOR POST
    #include <HTTPClient.h>

    int know;
    #define CAMERA_MODEL_AI_THINKER
    #include "camera_pins.h"
    //for reconnect
    unsigned long previousMillis = 0;
    unsigned long interval = 30000;
    //stuff to bring in string
    const byte numChars = 100;
    char receivedChars[numChars];
    char tempChars[numChars];        // temporary array for use when parsing
    // variables to hold the parsed data
    char messageFromPC[numChars] = {0};
    float floatFromPC = 0;
    char ssidString[numChars] = {0};
    float floatFromPC2 = 0;
    char pskString[numChars] = {0};
    char IP[numChars] = {0};
    char zone[numChars] = {0};
    char myChar[numChars]= {0};
    char myChar2[numChars]= {0};
    char myChar3[numChars]= {0};
    char myChar4[numChars]= {0};
    boolean newData = false;
    //end stuff ti bring in string
    String f;
    int addr = 0;
    OV2640 cam;

    WebServer server(XX);

    const char HEADER[] = "HTTP/1.1 200 OK\r\n" \
                          "Access-Control-Allow-Origin: *\r\n" \
                          "Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n";
    const char BOUNDARY[] = "\r\n--123456789000000000000987654321\r\n";
    const char CTNTTYPE[] = "Content-Type: image/jpeg\r\nContent-Length: ";
    const int hdrLen = strlen(HEADER);
    const int bdrLen = strlen(BOUNDARY);
    const int cntLen = strlen(CTNTTYPE);

    void handle_jpg_stream(void)
    {
      char buf[32];
      int s;

      WiFiClient client = server.client();

      client.write(HEADER, hdrLen);
      client.write(BOUNDARY, bdrLen);

      while (true)
      {
        if (!client.connected()) break;
        cam.run();
        s = cam.getSize();
        client.write(CTNTTYPE, cntLen);
        sprintf( buf, "%d\r\n\r\n", s );
        client.write(buf, strlen(buf));
        client.write((char *)cam.getfb(), s);
        client.write(BOUNDARY, bdrLen);
      }
    }

    const char JHEADER[] = "HTTP/1.1 200 OK\r\n" \
                           "Content-disposition: inline; filename=capture.jpg\r\n" \
                           "Content-type: image/jpeg\r\n\r\n";
    const int jhdLen = strlen(JHEADER);

    void handle_jpg(void)
    {
      WiFiClient client = server.client();

      cam.run();
      if (!client.connected()) return;

      client.write(JHEADER, jhdLen);
      client.write((char *)cam.getfb(), cam.getSize());

    }

    void handleNotFound()
    {
      String message = "Server is running!\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET) ? "GET" : "POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      server.send(200, "text / plain", message);
    }

    void setup()
    {

      Serial.begin(57600);
      Serial.print("setup");

    delay(10000);

    //RESET EEPROM COMMENT OUT
    if(Serial.available()){
    delay(2000);

      recvWithStartEndMarkers();

        if (newData == true) {
            strcpy(tempChars, receivedChars);
                // this temporary copy is necessary to protect the original data
                //   because strtok() used in parseData() replaces the commas with \0
            parseData();
            showParsedData();
            newData = false;
        }
    }
    //TO HERE
        delay(10000);
        Serial.print("network");
        Serial.print(ssidString);
        Serial.print("pass");
        Serial.print(pskString);
        Serial.print("time zone");
        Serial.print(zone);

    if(ssidString[0] != '\0'){
     EEPROM.begin(512);  //Initialize EEPROM

      // write appropriate byte of the EEPROM.
      // these values will remain there when the board is
      // turned off.

     EEPROM.write(addr, 'A');    //Write character A
      addr++;                      //Increment address
      EEPROM.write(addr, 'B');    //Write character B
      addr++;                      //Increment address
      EEPROM.write(addr, 'C');    //Write character C

      //Write string to eeprom

      //RESET EEPROM SWITCH THESE TWO
     String www =  ssidString +String(",") + String(pskString) + String(",")+String(zone)+String(",");
     //String www =  newString +String(",") + String(oldString) + String(",")+String(zoneString)+String(",");
      Serial.print (www);

    for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
      {
        EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
      }

      EEPROM.commit();
      //Read string from eeprom           //Increment address
      //COMMENT OUT NEXT BRACKET RESET EEPROM
    }
    //RESET EEPROM COMMENT OUT NEXT SECTION
    else if(ssidString[0] == '\0'){
       EEPROM.begin(512);
        Serial.println("WHAT"); //Goto next line, as ESP sends some garbage when you reset it
      Serial.print(char(EEPROM.read(addr)));    //Read from address 0x00
      addr++;                      //Increment address
      Serial.print(char(EEPROM.read(addr)));    //Read from address 0x01
      addr++;                      //Increment address
      Serial.print(char(EEPROM.read(addr)));    //Read from address 0x02
      addr++;   //Increment address
      Serial.print(char(EEPROM.read(addr)));    //Read from address 0x03

      //Read string from eeprom
      String www;
      //Here we dont know how many bytes to read it is better practice to use some terminating character
      //Lets do it manually www.circuits4you.com  total length is 20 characters
      for(int i=0;i<100;i++)
      {
        www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
      }

     Serial.println("this");
      Serial.print(www);  //Print the text on serial monitor

      www.toCharArray(myChar,100);
        char * token = strtok(myChar,",");
        char * token2 = strtok(NULL,",");
        char * token3 = strtok(NULL,",");

    Serial.println("one");
     Serial.print(token);
     Serial.println("two");
     Serial.print(token2);
     Serial.println("three");
     Serial.print(token3);

    strcpy(myChar2,token);
    strcpy(myChar3,token2);
    strcpy(myChar4,token3);

    //RESET EEPROM COMMENT OUT TO HERE
    }

    #define SSID1 ssidString
    #define PWD1 pskString

      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;

      // Frame parameters
      //  config.frame_size = FRAMESIZE_UXGA;
      config.frame_size = FRAMESIZE_VGA;
      config.jpeg_quality = 12;
      config.fb_count = 2;

    #if defined(CAMERA_MODEL_ESP_EYE)
      pinMode(13, INPUT_PULLUP);
      pinMode(14, INPUT_PULLUP);
    #endif

      cam.init(config);

      IPAddress ip;

      WiFi.mode(WIFI_STA);
      if(ssidString[0] != '\0'){
       // digitalWrite(33,LOW);
      WiFi.begin(ssidString, pskString);
      Serial.println("zone");
      Serial.print(zone);
     know = atoi(zone);
      }
      else if(ssidString[0] == '\0'){
         WiFi.begin(myChar2, myChar3);
         Serial.println("myChar4");
          know = atoi(myChar4);
         Serial.print(myChar4);
      }

      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(F("."));
      }
      String rrr = String("/") + String(zone) + String("/") + String ("1");
      Serial.print("rrr");
      Serial.println(rrr);
      ip = WiFi.localIP();
      Serial.println(F("WiFi connected"));
      Serial.println("");
      Serial.println(ip);
      Serial.print("Stream Link: http://");
      Serial.print(ip);
      Serial.println(rrr);//userName
      server.on(String(rrr), HTTP_GET, handle_jpg_stream);
      server.on("/jpg", HTTP_GET, handle_jpg);
      server.onNotFound(handleNotFound);
      server.begin();
      Serial.print("loop");

    delay(1000);

    }

    void loop()
    {

     if (WiFi.status() == WL_DISCONNECTED){

      if(ssidString[0] != '\0'){

      WiFi.begin(ssidString, pskString);
      Serial.println("zone");
      Serial.print(zone);
     know = atoi(zone);
      }
      else if(ssidString[0] == '\0'){
         WiFi.begin(myChar2, myChar3);
         Serial.println("myChar4");
          know = atoi(myChar4);
         Serial.print(myChar4);
      }
       while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(F("."));
      }}
      unsigned long currentMillis = millis();

      if((WiFi.status()!= WL_CONNECTED) & (currentMillis-previousMillis >= interval)){
        Serial.print(millis());
        WiFi.disconnect();
        WiFi.reconnect();
        previousMillis = currentMillis;
      }
     else if (WiFi.status() == WL_CONNECTED){

//THIS IS THE CODE I ADDED TRYING TO POST VIDEO

    HTTPClient http;
      http.begin ("https://www.creatucate.com/video-1");
      http.addHeader("Content-Type","image/jpeg");

      int httpResponseCode = http.POST("POSTING from ESP32");

      if(httpResponseCode>0){
        String response = http.getString();
        Serial.println(httpResponseCode);
        Serial.println(response);
      }
      else{
        Serial.print("Error on sending POST: ");
        Serial.println(httpResponseCode);
      }

   //END NEW CODE

    server.handleClient();

    }}
        //more new stuff for string
        void recvWithStartEndMarkers() {
            static boolean recvInProgress = false;
            static byte ndx = 0;
            char startMarker = '<';
            char endMarker = '>';
            char rc;

            while (Serial.available() > 0 && newData == false) {
                rc = Serial.read();

                if (recvInProgress == true) {
                    if (rc != endMarker) {
                        receivedChars[ndx] = rc;
                        ndx++;
                        if (ndx >= numChars) {
                            ndx = numChars - 1;
                        }
                    }
                    else {
                        receivedChars[ndx] = '\0'; // terminate the string
                        recvInProgress = false;
                        ndx = 0;
                        newData = true;
                    }
                }

                else if (rc == startMarker) {
                    recvInProgress = true;
                }
            }
        }

        //============
        //RESET EEPROM COMMENT OUT ALL THE REST
        void parseData() {      // split the data into its parts

            char * strtokIndx; // this is used by strtok() as an index

            strtokIndx = strtok(tempChars,",");      // get the first part - the string
            strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

            strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
            strcpy(ssidString,strtokIndx);

            strtokIndx = strtok(NULL, ",");
            strcpy(pskString,strtokIndx);
            strtokIndx = strtok(NULL, ",");
            strcpy(zone,strtokIndx);

        }

        //============

        void showParsedData() {
            Serial.print("Message ");
            Serial.println(messageFromPC);
            Serial.print("water level ");
            Serial.println(floatFromPC);
            Serial.println(ssidString);
            Serial.print("battery level ");
            Serial.println(floatFromPC2);
            Serial.println(pskString);
            Serial.print("time zone is ");
           Serial.println(zone);

        }

If this is not the correct place for this question please advise me.  I am not even sure this can be done but I hope so.

title: How can I access ESP32-CAM from outside local network other than port forwarding?

Answers: 0


body:
I am trying to change the blue LED on my ESP8266. I can do this (sort of...)
In the setupWifi() function below, there is a loop that is supposed to rapidly blink the LED while wifi is connecting.  The only way I can flash the blue light is if the print statement (Serial.print(".");) is present.  If I remove this (and even increase the delay) the blue light will not flash.  If the print statement is present, it works as expected.

The other issue I have is when I click the web page to turn the light on or off.  The values print correctly, but the LED only blinks briefly on in both cases.

My questions are:
1) Why am I only able to change the led when there is a print statement in the loop while waiting for wifi connectivity?
2) Why am I unable to change the led in the main loop?

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <SoftwareSerial.h>

#define SECONDS_PER_MINUTE 60
#define SECONDS_PER_HOUR 60 * SECONDS_PER_MINUTE
#define SECONDS_PER_DAY 24 * SECONDS_PER_HOUR
#define SECONDS_PER_WEEK 7 * SECONDS_PER_DAY

#define LED_PIN 1
#define TIME_UPDATE SECONDS_PER_WEEK

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

const long utcOffsetInSeconds = -4 * SECONDS_PER_HOUR;

SoftwareSerial ESPserial(2, 3); // RX | TX
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
ESP8266WebServer server(80);

uint8_t ledStatus = LOW;
uint8_t lastLedStatus = ledStatus;
unsigned long lastUpdate = 0;

void updateTime() {
  time_t epochTime = timeClient.getEpochTime();

  if (epochTime > lastUpdate + TIME_UPDATE) {
    Serial.println("Syncing time with server");
    timeClient.update();
    time_t epochTime = timeClient.getEpochTime();
    struct tm *ptm = gmtime ((time_t *)&epochTime);

    int hour = timeClient.getHours();
    int minute = timeClient.getMinutes();
    int second = timeClient.getSeconds();
    int day = ptm->tm_mday;
    int month = ptm->tm_mon+1;
    int year = ptm->tm_year+1900;

    Serial.printf("Time synched at: %d/%d/%d %d:%d:%d\n", day, month, year, hour, minute, second);
    lastUpdate = epochTime;
  }
}

void setupSerial() {
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);
  ESPserial.end();
  ESPserial.begin(9600);
  Serial.println("Serial Port Initialized");
  ESPserial.println("AT+GMR");
}

void setupWifi() {
  bool ledState = HIGH;
  Serial.println("Connecting to WIFI");

  WiFi.mode(WIFI_STA);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
    digitalWrite(LED_PIN, ledState);
    ledState = !ledState;
  }

  Serial.println("WIFI connected");
  Serial.println(WiFi.localIP());
}

void setup() {
  pinMode(LED_PIN, OUTPUT);
  timeClient.begin();
  setupSerial();
  setupWifi();
  delay(100);

  server.on("/", handleOnConnect);
  server.on("/led1on", handleLedOn);
  server.on("/led1off", handleLedOff);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  updateTime();
  server.handleClient();

  if (lastLedStatus != ledStatus) {
    Serial.printf("Writing %u\n", ledStatus);
    digitalWrite(LED_PIN, ledStatus);
    lastLedStatus = ledStatus;
  }
}

void handleOnConnect()  {
  server.send(200, "text/html", SendHTML(ledStatus));
}

void handleLedOn() {
  ledStatus = HIGH;
  Serial.printf("Turning LED: %u\n", ledStatus);
  // digitalWrite(LED_PIN, ledStatus);
  server.send(200, "text/html", SendHTML(ledStatus));
}

void handleLedOff() {
  ledStatus = LOW;
  Serial.printf("Turning LED: %u\n", ledStatus);
  // digitalWrite(LED_PIN, ledStatus);
  server.send(200, "text/html", SendHTML(ledStatus));
}

void handleNotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(uint8_t ledStatus){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>LED Control</title>\n";
  ptr +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
  ptr +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;} h3 {color: #444444;margin-bottom: 50px;}\n";
  ptr +=".button {display: block;width: 80px;background-color: #1abc9c;border: none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 4px;}\n";
  ptr +=".button-on {background-color: #1abc9c;}\n";
  ptr +=".button-on:active {background-color: #16a085;}\n";
  ptr +=".button-off {background-color: #34495e;}\n";
  ptr +=".button-off:active {background-color: #2c3e50;}\n";
  ptr +="p {font-size: 14px;color: #888;margin-bottom: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +="<h1>ESP8266 Web Server</h1>\n";
  ptr +="<h3>Using Access Point(AP) Mode</h3>\n";

   if(ledStatus
  )
  {ptr +="<p>LED1 Status: ON</p><a class=\"button button-off\" href=\"/led1off\">OFF</a>\n";}
  else
  {ptr +="<p>LED1 Status: OFF</p><a class=\"button button-on\" href=\"/led1on\">ON</a>\n";}

  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}
```

title: Problem changing the state of the blue LED on an ESP8266

Answers: 0


body:
Heyo everyone !

I'm in a project where I need to send a signal if I detect vaccuum.
I'm sending the signal on PIN 9 but I soon realized that I was only getting 1V.

Tought I was alternating between signal/no_signal but the log provided me with constant and consistent values.

Then I started doubting about my board so I made PIN 10 always output. Under the same load as PIN 9 (I switch the cable connecting from PIN 9 to the circuit, to PIN 10 to the circuit ), I get a good 5V. Thus, I exclude any load problem.

Regarding the PIN output issue, you can all see that it's not missing.

My last hypothesis is that there's some sort of sorcery with my code that I don't know and couln't find on the internet...

Any idea on what might be going on ?

```
// Constant
const int BL1 = 9;// BINARY LED 1 pin
const int TEST = 10;// BINARY LED 1 pin
const int AP = A0;// ANALOG PRESSOSTAT pin
const int P = 85;// TRIGGER PRESSURE value

// Variables
int LS1 = LOW;  // LED 1 STATE
float RPV = 1; // Raw Pressostat Voltage (0-1024)
float PV = 1; // Pressostat Voltage (V)
float PDP = 20; // Pressostat Deduced Pressure (kPa)

// Initialization of pins at startup
void setup() {
  pinMode(AP, INPUT); // ANALOG PRESSOSTAT pin set as INPUT
  pinMode(BL1, OUTPUT);// BINARY LED 1 pin set as OUTPUT
  pinMode(TEST, OUTPUT);// BINARY LED 1 pin set as OUTPUT
  pinMode(LED_BUILTIN, OUTPUT);// LED_BUILTIN pin set as OUTPUT
  Serial.begin(9600);
}

void loop() {
    digitalWrite(TEST, HIGH);
    RPV = analogRead(AP);
    PV = (RPV/1024)*5;
    PDP = (-1)*(PV-1)*(-101/4);
    Serial.print("Pression: ");
    Serial.print(PDP);
    if ( PDP > P ){
      int LS1 = HIGH;  // LED 1 STATE
      digitalWrite(BL1, HIGH);
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.print(" | LED: 1");
      }
    else {
      int LS1 = LOW;  // LED 1 STATE
      digitalWrite(BL1, LOW);
      digitalWrite(LED_BUILTIN, LOW);
      Serial.print(" | LED: 0");
    }
    digitalWrite(BL1, LS1);
    Serial.print(" | Trigger: ");
    Serial.println(P);

  }
```

title: Pin outping 1V instead of expected 5V, not hardware related

Answers: 2

body:
Here's a working script (I went back to PWM pin, if that matter at all)

```
void loop() {
  ...// unrelated code
  if (PDP > P) {
    LS1 = HIGH;                               // LED 1 HIGH
    digitalWrite(BL1, LS1);
    digitalWrite(LED_BUILTIN, LS1);
    Serial.print(LS1);
  }
  else {
    LS1 = LOW;                                // LED 1 STATE
    digitalWrite(BL1, LS1);
    digitalWrite(LED_BUILTIN, LS1);
    Serial.print(LS1);
  }
  ...// more unrelated code
}
```

body:
I'll reduce it a little

    void loop() {
        // ... doesn't matter
        if ( PDP > P ){
          int LS1 = HIGH;            // shadows global variable (creates local variable that won't exist after })
          digitalWrite(BL1, HIGH);
        } else {
          int LS1 = LOW;             // again shadows global variable
          digitalWrite(BL1, LOW);
        }
        digitalWrite(BL1, LS1);      // LS1 is still LOW

      }

Mistery solved


body:
I'm using a MacBook Pro 2013 Late with OpenCore Patcher. Currently Ventura 13.3.1 is installed. Before this version was installed, I had no problem using arduino on my MacOS computer. But right now, when I plug in my Arduino Nano Clone, the computer suddenly freezes and does not respond to any interaction. I have to press and hold the power button to restart the computer.

I tried to plug in another board called NodeMCU which has CH340 chip likewise I did with the arduino, same trouble happened again. So at that point I was guessing it was a CH340 driver problem or something about it. To test my theory, I plugged in my Raspberry Pi Pico and it worked perfectly. So it's probably CH340 chip problem but I could not find any solution in web. May there is a system integrity problem with OpenCore which the version is not compatible with the current operation system version.

If anyone can help me with this issue I'd be really appreciated, since I have a project which must be completed within 3 weeks.

title: MacOS Ventura freezes/crashes when i plug in my Arduino Nano Clone

Answers: 0


body:
I have been using this device very little but it was use to work, and it also gave me the same issue in the past, the somewhat I was able to upload again.

I tried to use the reset button, and short GRD with RST pins, but nothing helped.
The device is recognised as **Arduino MRK1000** and connected.
I also tried to specify **Arduino Zero (Native USB Port)**.
*Under Tools > Get Board* Info I get:
````
BN: Arduino MKR1000
VID 0x2341
PID: 0X804E
SN: 414C4E1[...]
````

**My issue:**\
When I try to upload the sketch (even empty) it hangs forever, or some times it shows the same message shown when you unplug the device while uploading.
````
No device found on COM5
Failed uploading: uploading error: exit status 1
````
The serial monitor is unable to connect
````
Sketch uses 33108 bytes (12%) of program storage space. Maximum is
262144 bytes. Global variables use 3552 bytes (10%) of dynamic memory,
leaving 29216 bytes for local variables. Maximum is 32768 bytes.
No device found on COM5 Failed uploading: uploading error: exit status 1
````

**Attempted resolution actions:**\
I tried to use the reset button, and short GRD with RST pins, but nothing helped.
I tried multiple USB ports, different PC, different cable.

**For information about the device:**\
https://github.com/Makerfabs/Maduino-Zero-4G-LTE
https://wiki.makerfabs.com/Maduino_Zero_4G_LTE.html

**Requests:**\
If you could guide me, maybe I can try to "factory reset" the MCU, or maybe try to connect in a different way.\
I read about the bootloaders but I don't know how they work and I don't want to try alone and make worse.\
The manufacturer didn't reply to my messages,on GitHub I didn't receive any reply either, so this is one last attempt before I throw this into the bin.\
If anyone can recommend al alternative board with GPS and LTE/4G connectivity would be a plus.

title: Maduino (Arduino Zero) at91samd21g18 - Unable to connect to the serial port

Answers: 1

body: As suggested by Juraj (thank you), **pushing the reset button twice** allowed me to upload an empty sketch and "revive" an otherwise unusable device.


body:
I designed PCb for relay Switching using gps signal for that i am using atmaga 328P-AU and Neo 6M but after connecting gps module its not showing long, lat. i also checked power supply in module pin it shows 4.96V and RX, TX connection are also properly soldered.

i tested simple code to see the uart data in module and it should be something regardless of satelite connection but it shows nothing.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(4, 5); //(RX, TX) check correct pin assignments.

    void setup() {

    mySerial.begin(9600);

    Serial.begin(9600);

    Serial.println("GPS start");

    }

    void loop() {

    while (mySerial.available()) {

    Serial.write(
    mySerial.read());

    }

    }

in serial monitor it only shows "GPS start" when i press reset button

Schematic

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

my pcb layout

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

Actual PCB
[![enter image description here][3]][3]

So far i have tried this things but didnt get any result.

1.swapping RX,TX pins.

2.changing GPS module.

3.kept gps module in balcony for more than 4 hours.

4.connection checked more than 10 times.

  [1]: https://i.stack.imgur.com/iWdlA.png
  [2]: https://i.stack.imgur.com/A70yZ.png
  [3]: https://i.stack.imgur.com/6z2XK.jpg

title: GPS module NEO M8M not responding with Atmega 328P

Answers: 0


body:
through the code that I've listed below, the idea was to have a sensor that detects objects in different ranges, if they're quite close, a light strip will turn on yellow with no buzzer. If they're very close, the light strip will turn red and buzzer will buzz rapidly. However in our case, the buzzer keeps buzzing constantly even though there's no object in the vicinity of the sensor.
Below are our code for the input:

```lang-cpp
#include <Adafruit_NeoPixel.h>

#define TRIGGER_PIN_LEFT 8
#define ECHO_PIN_LEFT 9
#define TRIGGER_PIN_RIGHT 4
#define ECHO_PIN_RIGHT 5
#define NUM_PIXELS 8
#define POTENTIOMETER_PIN A0
#define PIEZO_PIN 10
#define TILT_PIN 6

Adafruit_NeoPixel strip1(NUM_PIXELS, 3, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(NUM_PIXELS, 2, NEO_GRB + NEO_KHZ800);

void setup() {
  pinMode(TRIGGER_PIN_LEFT, OUTPUT);
  pinMode(ECHO_PIN_LEFT, INPUT);
  pinMode(TRIGGER_PIN_RIGHT, OUTPUT);
  pinMode(ECHO_PIN_RIGHT, INPUT);
  pinMode(PIEZO_PIN, OUTPUT);
  pinMode(TILT_PIN, INPUT);
  strip1.begin();
  strip1.show();
  strip2.begin();
  strip2.show();
  Serial.begin(9600);
}

void loop() {
  long duration1, distance1, duration2, distance2;
  int speed = analogRead(POTENTIOMETER_PIN);
  int tilt = digitalRead(TILT_PIN);

  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_LEFT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  duration1 = pulseIn(ECHO_PIN_LEFT, HIGH);
  distance1 = (duration1/2) / 29.1;

  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_RIGHT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  duration2 = pulseIn(ECHO_PIN_RIGHT, HIGH);
  distance2 = (duration2/2) / 29.1;

  if (distance1 < 200 && distance1 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 255, 0);
    }
    strip1.show();
  } else if (distance1 < 200 && distance1 > 50 && tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance1 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 0, 0, 0);
    }
    strip1.show();
  }

  if (distance2 < 200 && distance2 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 255, 0);
    }
    strip2.show();
  } else if (distance2 < 200 && distance2 > 50&& tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance2 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 0, 0, 0);
    }
    strip2.show();
  }
  Serial.print("Tilt=");
  Serial.println(tilt);
}
```

title: Buzzer keeps buzzing even though the sensor doesn't detect anything

Answers: 0


body:
it has been a week that I'm struggling with the arduino to measure the RMS Voltage value. By OSC I can see that the RMS voltage value changes around 3V. But I can't see it by serial port. I think my sampling or conversion has problem and I can't find it. I really appreciate it if anyone can take a look at my codes and suggest anything.

    float readRMS_new(int pin, int vref) {
      int numReadings[100];
      const unsigned long samplingInterval = 2;  // Interval between RMS calculations in milliseconds
      unsigned int readingsSum = 0;   // Sum of squared readings
      unsigned int readingsCount = 0; // Number of readings taken
      unsigned long lastSamplingTime = 0;  // Time of the last RMS calculation
      float rmsVoltage = 0;
      float finalVoltage = 0;
      float circuitGain = 4.31;  // Gain of the circuit

      unsigned long currentTime = millis();  // Current time

      // Check if it's time to perform an RMS calculation
      if (currentTime - lastSamplingTime >= samplingInterval) {
        lastSamplingTime = currentTime;  // Update the last sampling time

        // Perform RMS calculation
        for (int i = 0; i < 100; i++) {
          numReadings[i] = analogRead(pin);
          readingsSum += pow(numReadings[i] - vref, 2);
          readingsCount++;
        }

        // Calculate RMS voltage
        float rms = sqrt(readingsSum / readingsCount);
        rmsVoltage = rms * 0.0048;
        finalVoltage = rmsVoltage * circuitGain;

        if (finalVoltage > 0.0f) {
          // Print RMS voltage
          Serial.print("RMS Voltage: ");
          Serial.println(finalVoltage, 3);  // Print with 3 decimal places
        }

        // Reset variables for the next RMS calculation
        readingsSum = 0;
        readingsCount = 0;

        return finalVoltage;
      }

      return 0.0f;  // Return 0 if it's not time to perform an RMS calculation
    }

Regards

Farzaneh

title: RMS Voltage Value

Answers: 2

body:
There are multiple issues with this piece of code:

1. Local variables, i.e. variables defined inside functions or braced
   blocks, are created each time the execution enters the function or
   block, and destroyed when it leaves it. Thus, `lastSamplingTime` will
   always be zero when it is checked. If you want the variable to
   preserve its value across invocations of the function, you have to
   either make it global or qualify it as `static`.

2. There is no point in storing the readings in an array, as you never
   read back any element of the array other than the one you just
   stored. The array is then eating memory for no good reason.

3. The Arduino will not be able to take more than one reading every
   112 µs, or 100 readings in 11.2 ms. There is no point
   in trying to ensure a 2 ms interval between RMS calculations.

4. There is no point in counting the readings: you know you are taking
   100 of them.

5. You should avoid using `pow()` for squaring an integer: this is a
   floating-point function which is prone to rounding errors.

6. Maybe the most serious issue: on the Mega, an `unsigned int` is
   16-bits, and cannot store numbers larger than 65,535. `readingsSum`
   is very likely going to overflow and give you a meaningless result.

7. Returning zero to mean “no data available” is probably not a very
   good choice, as zero is also a perfectly valid result. You should
   consider returning an impossible value, like `-1` (an RMS reading
   cannot be negative).

Here is how I would write the computation of the RMS value:

```c++
long readingsSum = 0;
for (int i =0; i < 100; i++) {
    long reading = analogRead(pin) - vref;
    readingsSum += reading * reading;
}
float rms = sqrt(readingsSum / 100);
```

Note that `reading` is of type `long` in order to avoid the squaring to
overflow.

body:
Thank you all for your time dedication. Finally increasing the sampling and optimize the same codes I could achieve my goals. I will post the functioning code for those who might need it.

```
float readRMS(int pin, int vref) {

  int lecturas[200]; // declaring the matrix

  float suma = 0; // sum of the squares

  float rms = 0;  // squares mean

  float volt = 0;  //

  float Volt_Final = 0;

  for (int cont = 0; cont < 200; cont++) {

    lecturas[cont] = analogRead(pin);

    delayMicroseconds(200);
  }
  for (int j = 0; j < 200; j++) {

    //Serial.println(lecturas[j]);

    suma = suma + pow((lecturas[j] - vref), 2);

    //Serial.println(suma);
  }
  rms = sqrt((suma / 200));

  volt = (rms / 1024) * 5;

  //Serial.println(volt);

  //suma=0;

  // Reset variables for the next RMS calculation

  rms = 0;

  lecturas[200] = 0;

  //Volt_Final = (volt * 4.31); //real voltage with circuit gain

  return volt;
}
```


body:
i'm trying to create a program that given a configuration (i've used multiple struct nested) i need in loop() to check for each output if they need to be on or off and set the output accordingly

let me explain the configuration (i'm not sure that this is the best way to make and store this config, suggestions are appreciated)
```
struct Period
{
    String name;
    String type;
    String value;
};

struct State
{
    String name;
    Period periods[2];
};

struct Output
{
    String name;
    int pin;
    int forcePin;
    State states[2];
};

Output outputs[4];
```
now i populate the first object (this is something that need to be editable by the user and i was thinking to store it in the EEPROM, for now in the setup() i do this
```
    outputs[0].name = "OUTPUT 1";
    outputs[0].pin = 27;
    outputs[0].forcePin = 25;
    outputs[0].states[1].name = "STATE 1";
    outputs[0].states[1].periods[0].name = "day";
    outputs[0].states[1].periods[0].type = "BOOL";
    outputs[0].states[1].periods[0].value = "ON";
    outputs[0].states[1].periods[1].name = "night";
    outputs[0].states[1].periods[1].type = "BOOL";
    outputs[0].states[1].periods[1].value = "OFF";
    outputs[0].states[0].name = "STATE 2";
    outputs[0].states[0].periods[0].name = "day";
    outputs[0].states[0].periods[0].type = "BOOL";
    outputs[0].states[0].periods[0].value = "ON";
    outputs[0].states[0].periods[1].name = "night";
    outputs[0].states[0].periods[1].type = "BOOL";
    outputs[0].states[0].periods[1].value = "OFF";
```
then in the loop i have few function that determinate the state and period and i call this function that should manage all the outputs
globalState in loop read from an input and set the variable
globalPeriod check the time and set if night or day
```
void manageOutputs()
{
    for (Output out : outputs)
    {
        Serial.println(out.name);
        Serial.println(out.pin);
        Serial.println(out.forcePin);
        if (digitalRead(out.forcePin) == LOW)
        {
            Serial.println("forced on set output");
            digitalWrite(out.pin, HIGH)
            continue;
        }

        Serial.println(out.states[globalState].name);
        Serial.println(out.states[globalState].periods[globalPeriod].name);
        Serial.println(out.states[globalState].periods[globalPeriod].type);
        Serial.println(out.states[globalState].periods[globalPeriod].value);
        if (out.states[globalState].periods[globalPeriod].type.equals("BOOL")) {
            if (out.states[globalState].periods[globalPeriod].value.equals("ON")) {
                digitalWrite(out.pin,HIGH);
            } else {
                digitalWrite(out.pin,LOW);
            }
        }
    }
}
```
i have multiple type of output in mind for example TIMER (so in the value field i would have some parameter to call another function that will alternate the output on and off for the time given) will have something like "15:10" so it will stay 15 minutes on and 10 minutes off, or a condition (for example if VAR1 > 50) so the field value would have "VAR1:>:50" so it will turn on only if the condition is met. So i will have a switch case where now i check if BOOL.

now that i hope that i have explained the situation, i would like to know if it's a good way to have 3 nested struct or if there is a better solution considering the necessity to have it stored in EEPROM, and if this is a good way to have this kind of condition like this or if there is a better way.
Considering also that in the future i would like to make a webpage or an api to update this kind of configuration from a pc (maybe using a esp-8266 for that, that is also connected to the arduino, or do everything with an esp32, but i would like first to have the basic loop working and then i will make the "UI")

thanks a lot

title: manage some output based on some parameter and rtc

Answers: 1

body:
There are many uses of the `String` class in these code snippets. Using
strings is quite natural in some higher-level languages. On an Arduino,
however, I would strongly advise you against this for two reasons:

1. String objects use dynamic memory, which is not friendly to the small
   amount of RAM available on a typical Arduino.

2. Saving a String to EEPROM is not trivial: you do not want to save the
   String object (it contains a pointer that would not make sense in
   EEPROM context), and you instead have to save the character array it
   refers to. This could involve handling complex memory allocation
   withing the EEPROM.

Instead of a string meant to handle one of a predefined set of values
(`"BOOL"`, `"TIMER"`, ...), use an `enum`. This is similar to an `int`,
where each possible value has been given a name (`TYPE_BOOL` is 0,
`TYPE_TIMER` is 1, ...). Instead of a string holding numbers, store the
numbers themselves. In essence, you want to create a data storage format
that is friendly to the binary nature of the CPU. If you really have to
store strings, e.g. for names (are those `name` fields really useful?
they do not look so in the provided example), limit their length and
store them as fixed-size character arrays.

The `period::value` field is interesting in that it can store different
kinds of information depending on the `type` field. For such a situation
the appropriate data structure is a [discriminated union][]. A `union`
is like a `struct` except that all fields share the same memory space
and only one can be valid at a time. In a discriminated union, the
`union` is accompanied by  a `ytpe` field that tells us which is the
valid field.

Applying those principles to your problem could give this kind of data
structure:

```c++
// All the possible Period types.
enum Type {
    TYPE_BOOL,
    TYPE_TIMER,
    // etc.
};

// This is a discriminated union.
struct Period
{
    Type type;
    union {  // one union member per possible type.
        bool bool_value;  // valid when type == TYPE_BOOL
        struct {
            int on_time;
            int off_time;
        } timer_value;  // valid when type == TYPE_TIMER
        // etc.
    };
};

struct State
{
    Period periods[2];
};

struct Output
{
    int pin;
    int forcePin;
    State states[2];
};
```

These data structures can be trivially saved in EEPROM, as they are
self-contained: they hold no pointers to data stored in dynamic memory.

Then, in `manageOutputs()`, you will read a period's `bool_value` only
when `type` is `TYPE_BOOL`, it's `timer_value` only when `type` is
`TYPE_TIMER`, etc:

```c++
void manageOutputs()
{
    for (Output out : outputs)
    {
        if (digitalRead(out.forcePin) == LOW) {
            digitalWrite(out.pin, HIGH);
            continue;
        }
        Period &period = out.states[globalState].periods[globalPeriod];
        switch (period.type) {
            case TYPE_BOOL:
                if (period.bool_value) {
                    digitalWrite(out.pin, HIGH);
                } else {
                    digitalWrite(out.pin, LOW);
                }
                break;
            case TYPE_TIMER:
                digitalWrite(out.pin, HIGH);
                delay(period.timer_value.on_time);
                digitalWrite(out.pin, LOW);
                delay(period.timer_value.off_time);
        }
    }
}
```

[discriminated union]: https://en.wikipedia.org/wiki/Tagged_union


body:
I cannot connect to a MQTT broker from a NodeMCU, when using SSL.

This is the error message:

> Attempting MQTT connection...failed, rc=-4 try again in 5 seconds.

When connecting to the same broker via other software like MQTTX or IOT MQTT panel, it does work fine, just the NodeMCU doesn't connect. What does work is using a local IP and port 1883, but as soon as I use the public mqtt broker IP and port 8883, the NodeMCU cannot connect.

I am probably overlooking something. Is it necessary to include the server certificates in the arduino code?

This is the mosquitto.conf:

    persistence true
    persistence_location /var/lib/mosquitto/
    log_dest file /var/log/mosquitto/mosquitto.log

    include_dir /etc/mosquitto/conf.d
    password_file /etc/mosquitto/passwd

    listener 1883
    listener 8883
    certfile /etc/mosquitto/certs/server.pem
    keyfile /etc/mosquitto/certs/server.key

And here is the sample Arduino Code.

    #include "ESP8266WiFi.h"
    #include "PubSubClient.h"
    #include <SPI.h>
    #include <Wire.h>

    const char* ssid = "MyWiFi";
    const char* password = "MyBassword";

    const char* mqtt_server = "MyMqttServer";
    const char* mqtt_username = "MyUser";
    const char* mqtt_password = "MyBassword";
    int mqtt_port = 8883;

    const char* mqtt_id = __DATE__ " " __TIME__;  //compile date that is used for a mostly unique identifier

    WiFiClient espClient;
    PubSubClient client(espClient);

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

    void setup_wifi()
    {
        delay(10);
        WiFi.begin(ssid, password);

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

        Serial.println("WiFi connected");
        Serial.println(WiFi.localIP());
    }

    void setup_mqtt()
        {
            client.setServer(mqtt_server, mqtt_port);
            client.setCallback(callback);

            Serial.println("Modbus RTU Master Online");
        }

    void callback(char* topic, byte* payload, unsigned int length)
        {
            Serial.print("Message arrived [");
            Serial.print(topic);
        }

    void reconnect()
        {
            // Loop until we're reconnected to MQTT
            while (!client.connected())
                {
                    Serial.print("Attempting MQTT connection...");
                    // Attempt to connect
                    if (client.connect(mqtt_id, mqtt_username, mqtt_password))
                        {
                            Serial.println("connected");
                        }
                    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()
    {
        delay(1000);

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

        client.loop();
    }

title: How to connect to MQTT broker from NodeMCU with SSL?

Answers: 0


body:
I've got an **ESP-07s** and I used an example code from the internet. When I power it and the program starts, it should just connect to my Wifi network. It has a simple webpage that should be locally accessible in my Wifi network.

I'll start by giving the code:
```
// Load Wi-Fi library
#include <ESP8266WiFi.h>

const char* ssid     = "MyWifiNetworkName";
const char* password = "MyWifiPassword";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output16State = "off";
String output0State = "off";

// Assign output variables to GPIO pins
const int output16 = 16;
const int output0 = 0;

unsigned long currentTime = millis();
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output16, OUTPUT);
  pinMode(output0, OUTPUT);
  pinMode(2, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output16, LOW);
  digitalWrite(output0, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  bool ledOn = true;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("~");
    digitalWrite(2, ledOn ? HIGH : LOW);
    ledOn = ! ledOn;
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.accept();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /16/on") >= 0) {
              Serial.println("GPIO 16 on");
              output16State = "on";
              digitalWrite(output16, HIGH);
            } else if (header.indexOf("GET /16/off") >= 0) {
              Serial.println("GPIO 16 off");
              output16State = "off";
              digitalWrite(output16, LOW);
            } else if (header.indexOf("GET /0/on") >= 0) {
              Serial.println("GPIO 0 on");
              output0State = "on";
              digitalWrite(output0, HIGH);
            } else if (header.indexOf("GET /0/off") >= 0) {
              Serial.println("GPIO 0 off");
              output0State = "off";
              digitalWrite(output0, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");

            // Web Page Heading
            client.println("<body><h1>Example</h1>");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("<p>GPIO 16 - Status " + output16State + "</p>");
            // If the output5State is off, it displays the ON button
            if (output16State=="off") {
              client.println("<p><a href=\"/16/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/16/off\"><button class=\"button button2\">OFF</button></a></p>");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("<p>GPIO 0 - Status " + output0State + "</p>");
            // If the output4State is off, it displays the ON button
            if (output0State=="off") {
              client.println("<p><a href=\"/0/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/0/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
```

When I power it, one of the following cases happen:

**Case 1**

It just connects within, say 3 seconds. This is the desired case. It prints its IP address to the serial output, and when I navigate to its IP, the webpage loads and everything works. Of course, this is as how it should be.

**Case 2**

It keeps "trying" to connect, and after 1 ~ 2 minutes it is connected, but then the following weird thing happens. It seems to be connected, and when I look in the list of devices that are connected to my router (via router's web interface) it shows the ESP is connected, and has the IP `192.168.2.34`.
[![enter image description here][1]][1]
As shown in my code, the ESP also prints its IP to the serial output as soon as it is connected. In the normal situation (case 1) this IP starts with `192.168.x.x`, and this is expected, since all devices shown in the connected devices list have an IP that starts with the same range. But in this case, the IP shown in the serial output is something like "`169.254.200.23`". Also, the ESP's webpage is not accessible.
So: router shows ESP as connected, having IP `192.168.2.34`, while the ESP itself prints a totally different IP (`169.254.200.23`). The webpage is at none of the given IP's acessible.

**Case 3**

It just doesn't connect. But I guess this could also be case 2 but then with an indefinitely "trying time" that I haven't waited.

- Router settings have never been changed. Everything is kept default as it was when we got it from our internet provider.
- I read on the internet an ESP can give problems when the WIfi channel 13 / 14 are used.
The router has set this to automatically choose a channel, and when I look in the router's web interface during a *case 2*, the channel was 1.
- There's no MAC filtering.
- The wifi signal strength at the location of the device is excellent.
- The router sends both the 2.4 and 5 GHz signals.

It's a 1 / 10 chance that case 1 (desired) occurs.

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

title: ESP-07s only connects to my wifi very occasionally

Answers: 0


body: I'm actually new to using arduino , and trying to make a simple car, using two dc motors, a l298n and an arduino, the problem is that a 9v battery doesn't seem enough to just power the l298n and one dc motor , but in the internet some people use an 4AA battery which is 6v and power the arduino 4 dc motors and the l298n so how ?

title: are 4AA batteries (6V) power my arduino

Answers: 3

body:
The name [Arduino][1] refers to dozens if not hundreds of different board and processor designs. Since a specific board / processor was not asked about we can only talk in generic terms.

Almost all Arduinos run at either 5 Volts or 3.3 Volts and contain a regulator to convert a wide range of Voltages to this value. That said, these regulators need a minimal drop between the input voltage and the desired regulated voltage in order to operate.  Some require less and are referred to as [LDO or Low Drop Out regulators][2].

As a worse case, consider if this Arduino does not use an LDO regulator and operates at 5 Volts. The difference between the 6 Volt input and Arduino operating Voltage is only 1 Volt. Further, consider if the batteries were not fresh and were only supplying, say, 5.5 Volts. Finally, consider if one or both motors started drawing heavy current from the batteries causing a further drop in Voltage. Any of these cases could cause the Arduino to reset / behave unexpectedly.

Consider trying to use the 9 Volt battery to power the Arduino and the 6 Volt battery to power the motors.

  [1]: https://learn.sparkfun.com/tutorials/what-is-an-arduino/all
  [2]: https://en.wikipedia.org/wiki/Low-dropout_regulator

body:
I understand you situation completely as I had also previously experienced the same problem. 9 V batteries are not enough to get the job done.

Therefore, I suggest you to use two 3.7 V Batteries. These batteries are a great alternative and had solved my problem. I hope it will do the same to you.

body:
To properly answer your question instead of taking a SWAG as I did would Be for you to post links giving technical information on each of the hardware devices and which Arduino you are using.

Nine Volt (smoke alarm) batteries do not have enough power to properly power an Arduino. Use some larger cells. There are so many places that show this improper configuration, it just will not last if it even works for a short while. Great for the battery manufacturers.

You can also purchase a SEPIC converter for a few bucks, this is a combination Buck/Boost converter. You set the output voltage you want and it will maintain it as long as you're getting the minimum voltage from the battery, even if the battery is at 3.5V and the output is at 5V. The input will range from about 3V to 30V and it will maintain its setpoint. This range is dependent on the device you pick.

The L298N is about the worce choice you can make for the motor driver. It has darlington bipolar outputs, that drop about 1.4 volts per lead or 2.8 - 3.2 volts to the motor depending on the load. That voltage drop is burnt up as heat and is doing nothing useful. Purchase an H-Bridge that is large enough to drive the motor that has MOSFET outputs, you will be much happier with that.

For batteries use whatever is convenient, the SEPIC converter solves that problem. Best to pick them to power the motor and use the SEPIC to power the Arduino Vin pin at about 7.5V. Doing it via the Vin is not as efficient as doing a 5V direct but you get the additional filtering on that input circuit. A lot depends on which Arduino we are talking about. Since you did not mention one I am assuming either a UNO or Nano.


body:
i trying to interface ATSAMD21G18A-U to NEO-M8N-0-10 gps by using UART.
my problem is here, i  need to use pin 25(rx) and 26(tx) of arduino to interface. i have tried below. but getting

```
error:C:\Users\lenovo\AppData\Local\Temp\.arduinoIDE-unsaved2023420-9788-1he85tu.af3\sketch_may20a\sketch_may20a.ino:1:10: fatal error: SoftwareSerial.h: No such file or directory
 #include <SoftwareSerial.h>
          ^~~~~~~~~~~~~~~~~~
compilation terminated.

exit status 1

Compilation error: SoftwareSerial.h: No such file or directory

```

**Code:**
```lang-cpp
#include <SoftwareSerial.h>

SoftwareSerial gpsSerial(25, 26); // RX, TX pins for GPS module

void setup() {
  Serial.begin(9600); // Serial monitor for debugging
  gpsSerial.begin(9600); // GPS module communication
}

void loop() {
  if (gpsSerial.available()) {
    char c = gpsSerial.read();
    Serial.print(c); // Print GPS data to Serial monitor
  }
}
```
I tried to download library but not able find. I am newbie to arduino.

title: Arduino M0 pro(ATSAMD21G18A-U) to NEO-M8N-0-10 gps interface issue

Answers: 0


body:
I am at my wits end and hope somebody here can provide some much-needed guidance.
My platform is an Asus ROG AMD laptop running Windows 11.
I recently decided to try working with Arduinos and purchased a Nano Every direct from Arduino.  I installed the Arduino IDE and when I plugged in the Every it showed up in Device Manager under Ports using the FTDI driver (I suspect that the driver was installed when I installed the IDE).
I had some problems with the Every and decided to try a straight Nano. I purchased one from Micro Center and when I plug it in it also appears in Device Manager under Ports, again using the FTDI driver.  When the Arduino IDE could not communicate with the Nano (I did change board and port) I realized that the unit uses an inexpensive Chinese comm chip was told by Micro Center support that I needed to install the CH340 driver.  As recommended I downloaded the driver installation package from wch-ic.com.  When I ran that installation it reported that the driver was already installed, and I do see two ch341ser.inf_amd64_xxxx entries in Windows\System32\DriverStore\FileRepository.
My problem is that I cannot figure out how to make the Nano use the CH340 driver.  When I try to update the driver in Device Manager it tells me that the current driver is the best one.  When I try to force an update by using "Let me pick from a list", browsing to one of the ch341ser.inf_amd64_xxxx folders in DriverStore\FileRepository and selecting CH341SER.INF I am presented with a set of possible models (CH330, CH340, CH340K, CH341, CH341A).  I was unable to find any guidance on which to select, so I (probably unwisely) experimented.  When I choose CH340 or CH341 the update process begins but my laptop abruptly restarts and afterwards the Device Manager entry in Ports is still using the FTDI driver.
I don't know why the CH340 upodate fails and causes a restart.
I don't know if I should try to delete the FTDI driver (and in fact am uncertain how to go about doing that).
I would greatly appreciate whatever help anyone can provide.

IDE output:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\bobwi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf

avrdude done.  Thank you.

Failed uploading: uploading error: exit status 1

title: Problem using CH340 driver for Nano

Answers: 0


body:
When running two threads, one for blinking led once every second, one for sweeping the servo 180 degrees. The servo just vibrates.

When I tested adding a serial printout in the run servo for loops for the pos variable it worked but a bit jerky. Any idea what could be the problem?

    #include <Arduino.h>
    #include <pt.h>
    #include <Servo.h>

    // put function declarations here:
    static struct pt pt1;
    static struct pt pt2;
    Servo myservo;
    int pos = 0;

    static int protothreadBlinkLED(struct pt *pt) {
      static unsigned long lastTimeBlink = 0;
      PT_BEGIN(pt);
      while(1) {
        lastTimeBlink = millis();
        PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
        digitalWrite(LED_BUILTIN, HIGH);
        lastTimeBlink = millis();
        PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
        digitalWrite(LED_BUILTIN, LOW);
      }
      PT_END(pt);
    }

    static int protoThreadRunServo(struct pt *pt) {
      static unsigned long lastServoUpdate = 0;
      PT_BEGIN(pt);
      while(1) {
        lastServoUpdate = millis();
        for(pos = 0; pos < 180; pos += 1) {
          PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
          myservo.write(pos);
        }
        for(pos = 180; pos >= 1; pos -= 1) {
          PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
          myservo.write(pos);
        }
      }
      PT_END(pt);
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(LED_BUILTIN, OUTPUT);
      myservo.attach(9);
      PT_INIT(&pt1);
      PT_INIT(&pt2);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      protothreadBlinkLED(&pt1);
      protoThreadRunServo(&pt2);
    }

title: Problem when running Servo library with thread (Protothreads)

Answers: 0


body:
I recently got a wemos d1 mini and now am trying to connect it to my IPhone 13's hotspot, however it doesn't connect, I tried to run the wifiscan example - and it doesn't even detect it there.

I tried connecting it to my home router - and this worked hence I have no ideas on fixing it, so any help would be appreciated!

title: Mobile hotspot with wemos d1 mini

Answers: 1

body:
By default the iPhone hotspot is 5GHz only, which is why your ESP8266 can't see it. The ESP8266's WiFi radio is 2.4GHz only.

To enable 2.4GHz on the iPhone hotspot, turn on the "Maximize Compatibility" button under "Settings | Personal Hotspot". Then 2.4GHz devices should be able to connect to the phone.

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

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


body:
I have a slave arduino connected to a master arduino mega (through UART) and to a RPi (through USB). The slave arduino is set to monitor various SHT85 (through I2C) and NTC sensors. What I would like to do is to have the slave arduino respond to both commands from the master and the RPi.

The code I have works ok for the NTCs but it is sometimes problematic for the SHT sensors. From times to times (every ~10 minutes) some of the sensors do not send back all requested bytes. The functions I am using to write and read are the following:

    //
    // I2C write
    void cmdI2Cwrite(int address, char *cmd) {
      Wire.beginTransmission(address);

      int c = 0;
      for (int i = 0; i < strlen(cmd); i += 2) {
        sscanf(&cmd[i], "x", &c);
        Wire.write(c);
      }

      if (Wire.endTransmission() != 0) {
        MySerial->println(F("end trasmission failed"));
      }

      if(address == 112)
      {
        if(cmd[1] == '0')
        {
          MySerial->println(F("OK - unlocked"));
          IsLocked = false;
          }
        else
        {
          MySerial->println(F("OK - locked"));
          IsLocked = true;
        }
      }
      else
      {
        MySerial->println(F("OK"));
      }
    }

and for read:

    // I2C read
    void cmdI2Cread(int address, unsigned int nBytes) {
      delay(15);
      Wire.requestFrom(address, nBytes);

      unsigned char c;
      char cstr[4];

      // check if the same number of bytes are received that are requested.
      if (Wire.available() != nBytes) {
        MySerial->println("Requested bytes not returned");
      }

      for (unsigned int i = 0; i < nBytes; i++) {
          c = Wire.read();
          sprintf(cstr, "x", c);
          MySerial->print(cstr);
      }
      MySerial->println();
    }

The command: Wire.available() != nBytes is sometimes satisfied and basically I receive no response from the SHT

Both the master and Rpi serials are set to a baud rate of 115200.

I have tried changing cables, shielding cables, reducing the baud rate, implementing some kind of lock mechanism

the problem doesn't seem to appear when I disconnect either the RPi or the master from the slave (so it seems there is some kind of cross talk.. not sure)

Any help would be appreciated

Thank you

title: slave arduino receiving commands from two serials

Answers: 0


body:
I am trying to use a [Waveshare 4.2inch e-paper display][1] with an [Adafruit Feather Adalogger M0][2], but am having issues with two separate instances of `#define GET_STATUS` being defined differently in different locations. More specifically, in the [Demo Library (download)][3] for the Waveshare display, one of the files (epd4in2.h) defines GET_STATUS as 0x71. However, in a file (USBCore.h) I downloaded from the board manager in the ArduinoIDE to be able to support the Feather Adalogger, GET_STATUS is defined as 0.

I've tried messing with the values to see if making them match (both as 0x71 and both as 0) would solve the issue, but it didn't change anything. I can't find any information about what GET_STATUS in general, so I'm unsure what I can even try to fix this issue. Furthermore, I can't find any instances of GET_STATUS being used, so I'm unsure what its significance even is. So, basically, my questions are: 1) what is the significance of GET_STATUS, and 2) how can I reconcile it being used differently in two different places?

Below is the code I'm trying to run (it's the demo code from Waveshare), and the libraries other than "<SPI.h>" are in the demo library download from Waveshare.

```
#include <SPI.h>
#include "epd4in2.h"
#include "imagedata.h"
#include "epdpaint.h"

#define COLORED     0
#define UNCOLORED   1

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Epd epd;

  if (epd.Init() != 0) {
    Serial.print("e-Paper init failed");
    return;
  }

  /* This clears the SRAM of the e-paper display */
  epd.ClearFrame();

  /**
    * Due to RAM not enough in Arduino UNO, a frame buffer is not allowed.
    * In this case, a smaller image buffer is allocated and you have to
    * update a partial display several times.
    * 1 byte = 8 pixels, therefore you have to set 8*N pixels at a time.
    */
  unsigned char image[1500];
  Paint paint(image, 400, 28);    //width should be the multiple of 8

  paint.Clear(UNCOLORED);
  paint.DrawStringAt(0, 0, "e-Paper Demo", &Font24, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 100, 40, paint.GetWidth(), paint.GetHeight());

  paint.Clear(COLORED);
  paint.DrawStringAt(100, 2, "Hello world", &Font24, UNCOLORED);
  epd.SetPartialWindow(paint.GetImage(), 0, 64, paint.GetWidth(), paint.GetHeight());

  paint.SetWidth(64);
  paint.SetHeight(64);

  paint.Clear(UNCOLORED);
  paint.DrawRectangle(0, 0, 40, 50, COLORED);
  paint.DrawLine(0, 0, 40, 50, COLORED);
  paint.DrawLine(40, 0, 0, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledRectangle(0, 0, 40, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 200, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 200, paint.GetWidth(), paint.GetHeight());

  /* This displays the data from the SRAM in e-Paper module */
  epd.DisplayFrame();

  /* This displays an image */
  epd.DisplayFrame(IMAGE_BUTTERFLY);

  /* Deep sleep */
  epd.Sleep();
}

void loop() {
  // put your main code here, to run repeatedly:

}
```

When I run the code, I get the following messages
```
In file included from /home/beingpool/Arduino/epd4in2-demo/epd4in2-demo.ino:28:
/home/<user>/Arduino/libraries/epd4in2/epd4in2.h:64: warning: "GET_STATUS" redefined
   64 | #define GET_STATUS                                  0x71
      |
In file included from /home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/Arduino.h:157,
                 from /home/beingpool/.var/app/cc.arduino.IDE2/cache/arduino/sketches/96EFEDEA56FF573B678089A960FFC685/sketch/epd4in2-demo.ino.cpp:1:
/home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/USB/USBCore.h:23: note: this is the location of the previous definition
   23 | #define GET_STATUS     0
      |
```

[1]: https://www.waveshare.com/wiki/4.2inch_e-Paper_Module
[2]: https://www.adafruit.com/product/2796
[3]: https://www.waveshare.com/w/upload/3/39/E-Paper_code.7z

title: Having issues understanding what "#define GET_STATUS" does

Answers: 1

body:
There is no generic meaning in `GET_STATUS`. Apparently both libraries use the very same identifier for their own different purpose.

If you do not use `GET_STATUS` in your sketch, you can remove the definition before the inclusion of "epd4in2.h", like this:

```c++
#include <SPI.h>
#undef GET_STATUS
#include "epd4in2.h"

// ...
```


body:
```
AT+CIPSEND=65
link is not valid

ERROR

OK

OK

OK

OK
STATUS:2

OK
\x0BQ\xADUART_DEF=115200,8,1,0,0ATE0
AT+CWMODE=3
AT+CIPMUX=0
AT+CIPMODE=0
AT+CIPSTATUS
AT+CIPSTART="TCP","api.thingspeak.com",80
AT+CIPSTATUS
CONNECT

OK
STATUS:3
+CIPSTATUS:0,"TCP","52.0.107.28",80,38071,0

OK

OK
> AT+CIPSEND=65
GET api.thingspeak.com/update?api_key=M
Recv 65 bytes
E5K4JWXT2ZBSBZ8&field1=0

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Tue, 23 May 2023 05:45:13 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
</body>
</html>
CLOSED
```

title: what is 400 bad request and how to solve this

Answers: 1

body:
The server name does not belong to the `GET` request line: it has to be
provided in the `Host` request header.

Try something this:

```c++
server.println("GET /update?api_key=ME5K4JWXT2ZBSBZ8&field1=0 HTTP/1.0");
server.println("Host: api.thingspeak.com");
server.println();  // empty line means "end of request headers"
```


body:
I am currently using an evalkit Nina W106-00B board that incorporates an ESP32.

I am desperately trying to implement OTA (Over-The-Air) updates.

I started by modifying my partitions.csv file, which looks like this (without OTA) and works well:

nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 1M,
storage, data, spiffs, , 0xF0000,

The "factory" partition corresponds to my .bin file containing the code.
The "storage" partition corresponds to my .bin file containing the web pages and .js files.

I tried to modify it so that when I add a new .bin file containing the code, it goes into the "ota_0" partition, for example, and then boots without using the "factory" partition.

This is what it looks like now:

nvs, data, nvs, 0x9000, 0x6000,
otadata, data, ota, 0xf000, 0x2000,
phy_init, data, phy, 0x11000, 0x1000,
factory, app, factory, 0x20000, 1M,
storage, data, spiffs, 0x120000, 0xF0000,
ota_0, app, ota_0, 0x210000, 1M,
ota_1, app, ota_1, 0x310000, 1M,

I can compile and flash it, but when I start my board, an error message appears in the logs:

ELF file SHA256: 73241a5f6639ca7a

Rebooting...
ets Jul 29 2019 12:21:46

rst:0xc (SW_CPU_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1256
load:0x40078000,len:13276
ho 0 tail 12 room 4
load:0x40080400,len:3032
entry 0x40080598

assert failed: do_core_init startup.c:339 (flash_ret == ESP_OK)

Backtrace: 0x40081ee2:0x3ffe3a90 0x4008a4bd:0x3ffe3ab0 0x40090fdd:0x3ffe3ad0 0x400d2a13:0x3ffe3bf0 0x400d2abe:0x3ffe3c10 0x4008165e:0x3ffe3c40 0x4007927e:0x3ffe3c90 |<-CORRUPTED

This message keeps looping, and the board attempts to restart without success.

How should I modify my partitions.csv file for it to work correctly?

Thanks,
Zapsalis

title: How to set OTA on ESP 32

Answers: 0


body:
I want to use a color sensor for my Arduino project with Arduino Uno to detect the colors red, green, blue, orange, yellow purple of leaves of paper and then light my RGB led in those colors. I have no errors in my code, but it fails for some reason :( Can someone help me?

here is the code:

    #define s0 8
    #define s1 9
    #define s2 10
    #define s3 11
    #define sensorOut 12

    #define LED_RED 3
    #define LED_GREEN 5
    #define LED_BLUE 6

    // Variabelen voor de kleurwaarden
    int red;
    int green;
    int blue;

    const int RED_COLOR = (255, 0, 0);
    const int GREEN_COLOR = (0, 255, 0);
    const int BLUE_COLOR = (0, 0, 255);
    const int ORANGE_COLOR = (255, 165, 0);
    const int PINK_COLOR = (255, 105, 180);
    const int PURPLE_COLOR = (128, 0, 128);
    const int YELLOW_COLOR = (255, 255, 0);

    int color = 0;

    void setup() {
      // Zet de seriële communicatie op
      Serial.begin(9600);

      // Initialiseer de pinmodi
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);
      pinMode(sensorOut, INPUT);

      pinMode(LED_RED, OUTPUT);
      pinMode(LED_GREEN, OUTPUT);
      pinMode(LED_BLUE, OUTPUT);

      // Zet de frequentie van de kleurensensor op 20% (rode filter)
      digitalWrite(s0, HIGH);
      digitalWrite(s1, LOW);
    }

    void loop() {
      // Lees de kleurwaarden
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      red = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
      delay(20);
      digitalWrite(s3, HIGH);
      blue = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
      delay(20);
      digitalWrite(s2, HIGH);
      green = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
      delay(20);

    // Controleer op verschillende kleuren
    if (red > green && red > blue) {
      color = RED_COLOR; // Rood
    } else if (green > red && green > blue) {
      color = GREEN_COLOR; // Groen
    } else if (blue > red && blue > green) {
      color = BLUE_COLOR; // Blauw
    } else if (red > green && red > blue && green > blue) {
      color = YELLOW_COLOR; // Geel
    } else if (red > green && red > blue && blue > green) {
      color = ORANGE_COLOR; // Oranje
    } else {
      color = 0; // Geen herkende kleur
    }

      // Controleer op verschillende kleuren
      if (color == RED_COLOR) {
        setColor(255, 0, 0); // Rood
      } else if (color == GREEN_COLOR) {
        setColor(0, 255, 0); // Groen
      } else if (color == BLUE_COLOR) {
        setColor(0, 0, 255); // Blauw
      } else if (color == ORANGE_COLOR) {
        setColor(255, 165, 0); // Oranje
      } else if (color == PINK_COLOR) {
        setColor(255, 105, 180); // Roze
      } else if (color == PURPLE_COLOR) {
        setColor(128, 0, 128); // Paars
      } else if (color == YELLOW_COLOR) {
        setColor(255, 255, 0); // Geel
      } else {
        // Geen herkende kleur, zet de led uit
        setColor(0, 0, 0);
      }

      delay(500); // Wacht 500 milliseconden voordat je de volgende kleur controleert
    }

    // Hulpmethode om de RGB-waarden in te stellen
    void setColor(int red, int green, int blue) {
      analogWrite(LED_RED, red);
      analogWrite(LED_GREEN, green);
      analogWrite(LED_BLUE, blue);
    }

title: Arduino-project with color sensor and rgb-led

Answers: 1

body:
Reading your code, I see three points:

1. Your constants are not assigned the values that you think. `const int RED_COLOR = (255,0,0);` sets the integer constant to the value `0`, i.e. the last value of a comma-separated sequence, [see here][1]. Instead, enumerate your color constants, i.e. set red=1, blue=2, etc. Or define a struct with three integer components.
2. The variable `color` will never be assigned the values `ORANGE_COLOR`, `PURPLE_COLOR` nor `YELLOW_COLOR`, because of the way you structured the expressions in the if-then-else block. If `red > green && red > blue`, the program will never even check whether `red > green && red > blue && blue > green`, because it already entered the first block. And `PURPLE_COLOR` is not listed in the upper if-else-block at all. Also, I would expect some `CYAN_COLOR` somewhere in there to cover the shades between green and blue.
3. What is the exact type of the color sensor? It seems strange to me that it transmits its data via the length of a pulse. If it doesn't, `pulseIn()` is the wrong method to use. If it really does, you may have a race condition here: I guess that writing to the pins `s2`/`s3` triggers the sensor to start the "data pulse", in which case `digitalRead(sensorOut)` may already return the "pulse state" instead of the "pre-pulse state" and therefore waits for a different pulse than it should. You'd need to first read `sensorOut` into a variable, then set `s2`/`s3`, then read your data via `pulseIn` using the variable you set before.

But without having the datasheet of the sensor/knowing the protocol of the sensor, this is all very volatile guesswork. Please improve your question by adding the sensor type (and maybe a wiring diagram) alongside an explanation of what you mean by "it fails". How exactly does it fail? Which part works and which doesn't?

You can also glean more insight into the state of your sketch by writing measured values to the serial monitor using `Serial.println`.

  [1]: https://stackoverflow.com/questions/69515298/assigning-tuple-to-an-int-variable-and-printing-the-variable