message:
DS3231 Clock project shows right date but wrong day

Heeya Guys!
Today I created a project with the help of instructables site. I followed the on screen steps and everything. Uploaded the sketch and it works like a charm, but there's one problem.

Everything works correctly but not the "Day", i.e as of today its Friday, 9 April 2021, the clock shows the correct time and date but it tells that today is "Tuesday" in place of Friday. I don't know why this is happening.
Any help would be appreciated :)
Here's the code that I'm using:

```c++
/*Arduino Clock by AnthoTRONICS
* Last edit: March 22,2019
*/
// Libraries you'll need (Same as the ones in the guide:
// TAKE NOTE OF THE VERSIONS!!!

// MD Parola 3.0.1: https://github.com/MajicDesigns/MD_Parola // click the link to download the library
// MD_MAX72XX 3.0.2: https://github.com/MajicDesigns/MD_MAX72XX //click the link to download the library
// DS3231 1.0.2: https://github.com/NorthernWidget/DS3231 // click the link to download

/*CODE:*/
// Header file includes
// These are for the matrix
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#include "Font_Data.h"

//These are for the clock
#include <DS3231.h>
#include <Wire.h>
DS3231 Clock;

bool Century=false;
bool h12;
bool PM;
byte  dd,mm,yyy;
uint16_t  h, m, s;

#define MAX_DEVICES 4 // Set the number of devices
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE,CS_PIN, MAX_DEVICES);

#define SPEED_TIME 75 // speed of the transition
#define PAUSE_TIME  0

#define MAX_MESG  20

// Global variables
char szTime[9];    // mm:ss\0
char szMesg[MAX_MESG+1] = "";

uint8_t degC[] = { 6, 3, 3, 56, 68, 68, 68 }; // Deg C
uint8_t degF[] = { 6, 3, 3, 124, 20, 20, 4 }; // Deg F

char *mon2str(uint8_t mon, char *psz, uint8_t len)

// Get a label from PROGMEM into a char array
{
  static const __FlashStringHelper* str[] =
  {
    F("Jan"), F("Feb"), F("Mar"), F("Apr"),
    F("May"), F("Jun"), F("Jul"), F("Aug"),
    F("Sep"), F("Oct"), F("Nov"), F("Dec")
  };

  strncpy_P(psz, (const char PROGMEM *)str[mon-1], len);
  psz[len] = '\0';

  return(psz);
}

char *dow2str(uint8_t code, char *psz, uint8_t len)
{
  static const __FlashStringHelper*  str[] =
  {
  F("Sunday"), F("Monday"), F("Tuesday"),
  F("Wednesday"), F("Thursday"), F("Friday"),
  F("Saturday"), F("Sunday")
  };

  strncpy_P(psz, (const char PROGMEM *)str[code-1], len);
  psz[len] = '\0';

  return(psz);
}
// Time Setup: Code for reading clock time
void getTime(char *psz, bool f = true)
{
  s = Clock.getSecond();
  m = Clock.getMinute();
  h =Clock.getHour(h12,PM); //24hr Format
  sprintf(psz, "d%cd", h, (f ? ':' : ' '), m);
  //12hr Format
  //uncomment if you want the clock to be in 12hr Format
  /*if (Clock.getHour(h12,PM)>=13 || Clock.getHour(h12,PM)==0)
  {
    h = Clock.getHour(h12,PM) - 12;
  }
  else
  {
    h = Clock.getHour(h12,PM);
  }*/

}

void getDate(char *psz)
// Date Setup: Code for reading clock date
{
   char  szBuf[10];

   dd=Clock.getDate();
   mm=Clock.getMonth(Century); //12
   yyy=Clock.getYear();
   sprintf(psz, "%d %s d",dd , mon2str(mm, szBuf, sizeof(szBuf)-1),(yyy + 2000));
 //strcpy(szMesg, "29 Feb 2016");
}

void setup(void)
{
  P.begin(2);
  P.setInvert(false); //we don't want to invert anything so it is set to false
  Wire.begin();

  P.setZone(0,  MAX_DEVICES-4, MAX_DEVICES-1);

  P.setZone(1, MAX_DEVICES-4, MAX_DEVICES-1);
  P.displayZoneText(1, szTime, PA_CENTER, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT);

  P.displayZoneText(0, szMesg, PA_CENTER, SPEED_TIME, 0,PA_PRINT , PA_NO_EFFECT);

  P.addChar('$', degC);
  P.addChar('&', degF);

}

void loop(void)
{
  static uint32_t lastTime = 0; // millis() memory
  static uint8_t  display = 0;  // current display mode
  static bool flasher = false;  // seconds passing flasher

  P.displayAnimate();

   if (P.getZoneStatus(0))
  {
    switch (display)
    {
      case 0:    // Temperature deg C
      P.setPause(0,1000);
      //P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_UP);
      P.setTextEffect(0, PA_MESH, PA_BLINDS);
      display++;
      dtostrf(Clock.getTemperature(), 3, 1, szMesg);
      strcat(szMesg, "$");
      //strcat(szMesg, "26.5$");

        break;

      case 1: // Temperature deg F
        //P.setTextEffect(0, PA_SCROLL_UP, PA_SCROLL_LEFT);
        P.setTextEffect(0, PA_OPENING, PA_GROW_DOWN);
        display++;
        dtostrf((1.8 *Clock.getTemperature() )+32, 3, 1, szMesg);
        strcat(szMesg, "&");

   // strcpy(szMesg, "71.6&");

        break;

      case 2: // Clock

     P.setFont(0, numeric7Seg);
     P.setTextEffect(0, PA_PRINT, PA_NO_EFFECT);
     //Sleep Mode
     //Uncomment to enable Sleep Mode and adjust the hours to your needs
     /*if (h==12 || h<8)//Time intervals (in this case, from 12AM to 8AM)
     {
      P.setIntensity(0); //Set display brightness to lowest setting
     }
     else
     {
      P.setIntensity(6); //Set display brightness to 6 (15 is the brighest)
     }*/
     P.setPause(0,0);

     if (millis() - lastTime >= 1000)
    {
    lastTime = millis();
    getTime(szMesg, flasher);
    flasher = !flasher;
    }
    if(s==00&& s<=30){
    display++;
    P.setTextEffect(0, PA_PRINT, PA_SCROLL_UP);
    }

    //  strcpy(szMesg, "36 % RH");

        break;

      case 3: // day of week

        P.setFont(0,nullptr);
        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        display++;
        dow2str(Clock.getDoW()+1, szMesg, MAX_MESG); // Added +1 to get correct DoW

       //dow2str(5, szMesg, MAX_MESG);
        break;
      default:  // Calendar

        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        display = 0;
        getDate(szMesg);
        break;
    }

    P.displayReset(0);
  }

}
```

body:
The library seems to be [addressing device register 3][1].
According to the [DS3231 datasheet][2] this register has valid values 1-7, with 1 being Sunday.

You have:

```c++
dow2str(Clock.getDoW()+1, szMesg, MAX_MESG);
```

1-7 becomes 2-8.  And then, how `dow2str`:

```c++
strncpy_P(psz, (const char PROGMEM *)str[code-1], len);
```

2-8, become array indices 1-7.

Your array is:
```c++
  static const __FlashStringHelper*  str[] =
  {
  F("Sunday"), F("Monday"), F("Tuesday"),
  F("Wednesday"), F("Thursday"), F("Friday"),
  F("Saturday"), F("Sunday")
  };
```

The indices here start at 0, so everything is off-by-one.  But, I don't know how you get Tuesday out of Friday.  If you cut your code down to something smaller that is testable without the display code, just using `Serial`, you'll probably get better answers.

  [1]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.cpp#L226
  [2]: https://datasheets.maximintegrated.com/en/ds/DS3231.pdf


sender: user

sender: assistant

body:
I did this project and my weekday was off by 1, always a day earlier I fixed this by removing the Sunday at the beginning of the list and moving it to the end why you had two Sunday entries I do not know. That fixed my issue. I do not know why yours is showing Tuesday for Friday though.

char *dow2str(uint8_t code, char *psz, uint8_t len)
{
  static const __FlashStringHelper* str[] =
  {
    F("Monday"), F("Tuesday"),
    F("Wednesday"), F("Thursday"), F("Friday"),
    F("Saturday"),F("Sunday")
  }


message:
Communication between two Arduinos using ENC28J60?

How can I connect and send data between two Arduinos using ENC28J60 ethernet adapters on both of them? Is there any guide or example code for me to take a look from or any library I can use to achieve this communication?

I have one Arduino connected to an ultrasound sensor and the other to a relay module so that one Arduino measures the distance between certain objects and send the distance to the other Arduino, which then processes it to check if it is within a certain limit. If not then it turns on the relay. I could have used two ESP32 with one in AP mode but the range is not enough and serial communication is not possible, as the cables are fragile and the distance is too large. Also I couldn't find another way of sending the data.

I'm open to any suggestion, even changing the method of communication. Or using of any other ethernet module.

body:
You can use my EthernetENC library. See the examples of Arduino Ethernet library on how to use Ethernet libraries for Arduino.

EthernetClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. EthernetServer listens on a port. If server is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a EthernetClient object wrapping the socket. Everything you write or print to a EthernetClient is send to that one remote socket.

If the client board creates a EthernetClient and connects it to IP address and port of the EthernetServer on your 'server' board, then you get there a EthernetClient from server.available() and this two EthernetClient objects are connected. What you write/print on one side you read only from the EthernetClient object on the other side.

client socket
```
   if (client.connect(serverIP, PORT)) {
     client.print("request\n");
     String response = client.readStringUntil('\n');
     Serial.println(response);
     client.stop();
   }
```

server side
```
   EthernetClient client = server.available();
   if (client && client.connected()) {
     String request = client.readStringUntil('\n');
     Serial.println(request);
     client.print("response\n");
     client.stop();
   }
```


message:
Is it possible to use the same power source for the arduino and a high current

I've need to control some leds which draw 300mA with an arduino (actually an atmega) and after some searching I think the following is the circuit I need, but I'm not really sure if the power source for the LEDs can be the same as for the arduino.[![enter image description here][1]][1]

R1 = 1k

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

body: If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.


message:
What is the difference between serial begin() and wire.setClock() for I2C communication?

I am a new Arduino IDE user and have a simple question below

For I2C transmission speed setting, there are serial begin() and wire.setClock(). Some sample codes just use Serial.begin() without Wire.seClock(), some use both as shown below. What is the real differences between them? When to use just serial and when to use both of them? Thanks.

    void setup() {
      Serial.begin(9600);          // start serial communication at 9600bps

      Wire.begin();                // join i2c bus (address optional for master)

      Wire.setClock(400000); //Increase  I2C clock rate to 400 kHz
    }

body:
`Serial` has nothing to do with `Wire`/I2C communication. The examples only have this, because mostly they use `Serial` out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).

If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to `Serial` out.


body:
Serial.begin starts the communication on USB or RX/TX pins. It has nothing to do with Wire library and I2C communication.

I2C clock speed determines the speed of communication on the I2C bus. Wire.begin() among other settings, sets the I2C clock speed to some default value.

Wire.setClock() allows to set a different clock speed. This should be supported by all devices on the I2C bus or clock speed can be changed before communicating with a specific device on the bus.

Wire.setClock should be called after Wire.begin because Wire.begin sets the clock speed to some default.


message:
Is there a way to go to the start of the void loop() function kind of like a "continue" keyword in c in loops?

<!-- language-all: cpp -->
I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the `void loop()` function with an `exit(0)` to terminate the program analogous to `break` keyword in C language.
Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the `void loop()` function.

body:
In the loop() function, `return` will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling `loop()` again.

Another way to accomplish the same thing is to write everything in your `setup()` function, including whatever kind of loop construct you want, and use `break;` and `continue;` statements as you're used to:

    void setup(){
       // pinMode() & digitalWrite() calls
       // Initialize the Serial port if you need to
       // Any other one-time setup
       //
       // Everything happens here:
       for( .... ){
          // loop contents here
          if( whatever ){
             continue;
          }
          else if( something_else ){
             break;
          }
       }
    }

    // This just stalls forever when setup() ends:
    void loop(){
       ;
    }


message:
ESP32S v1.1 NodeMcu vs ESP32 DevKitV1

I have two different ESP32 development boards labelled "ESP32S v1.1 NODEMCU" (A) and "ESP32 DEVKITV1" (B).  From what I can tell they have the same major components, but their pins and general layout are quite different. I assume they are both knock-offs.

[![ESP32S v1.1 NODEMCU][1]][1]

[![ESP32 DEVKITV1][2]][2]

When uploading from the Arduino IDE, both read the same revision number and features:

    Chip is ESP32-D0WDQ6 (revision 1)
    Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
    Crystal is 40MHz

From what I can tell NodeMcu has something to do with the firmware for the ESP8266 ([wiki][3])?  Also, it seems my ESP32S NodeMcu board doesn't have the standard pin layout for ESP32 boards.

What exactly is this NodeMcu board and what are the differences between the two?

  [1]: https://i.stack.imgur.com/rCx7E.png
  [2]: https://i.stack.imgur.com/5yhC9.png
  [3]: https://en.wikipedia.org/wiki/NodeMCU

body:
The [DevKit][1] is a development board by ESP32 manufacturer [Espressif][2] to demonstrate ESP32 usage and to support prototyping.

The NodeMcu is a board by [NodeMcu][3] intended for the NodeMcu Lua language firmware.

There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.

You can use both development boards with the ESP32 "Arduino boards support package".

  [1]: https://www.espressif.com/en/products/devkits/esp32-devkitc
  [2]: https://www.espressif.com/
  [3]: https://www.nodemcu.com/index_en.html


message:
Init a calss inside a class

I'm building a monitoring IP class, `IPmonitoring`, that using an SPIFFS class that I wrote, `flashLOG`. Inside `IPmonitoring` I have 2 instances of `flashLOG` (code below).

My sketch have several instances of `IPmonitoring` for several servicesI wish to monitor. I Wish that `connectionLOG` and `disconnectionLOG` have unique and automated names.

For example if I'm monitoring a service called `MQTT` its connect and disconnect log will be `MQTT_discolog.txt` and `MQTT_conlog.txt`. In my code below, `filename1` and ` filename2` are consts.

    class IPmonitoring
    {
    private:
            char *_IP;
            char *_nick;

            flashLOG connectionLOG;
            flashLOG disconnectionLOG;

    public:
            IPmonitoring(char *IP, char *nick, char *filename1 = "/conlog.txt", char *filename2 = "/disconlog.txt")
                : connectionLOG(filename1), disconnectionLOG(filename2)
            {
                    _IP = IP;
                    _nick = nick;
            }

**EDIT1 - example how to use class**

my goal is that `filename1` for example will be `MQTTbroker_connlog.txt` meaning a combination of `_nick` and a suffix,

    IPmonitoring MQTT_service("192.168.3.200","MQTTbroker");

    void setup()
    {
    MQTT_service.start();
    }

    void loop()
    {
    MQTT_service.loop();
    }

body:
You have three options for the file names and generally.

1) constant string a.k.a. string literal
2) string buffer global or on stack with scope valid while the string is used
3) dynamically allocated string on heap

with 2) and 3) you can then build a string with C str or sprintf functions

option 3) is alright on MCU if you create these file names only at startup, not if you create them repeatedly as the sketch is running

If you choose option 3) you can build the strings in the constructor of IPmonitoring class, but you can't build the string in the member initialization part of the constructor. You have to add setters to `flashLOG` class and after building the strings for file names set them to the `flashLOG` instance with the setters.


body:
Judging from your example usage, you want the filenames to be built by
the `IPmonitoring` constructor. However, since that class cannot know in
advance how much space is needed for the file names, you are left with
two choices:

1. Let those file names be data members: arrays of `char` of some fixed
   size. This will impose a limit on the maximum file name length.

2. Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:

```c++
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};
```

Note the destructor, which is needed to avoid memory leaks, unless all
the instances of the class are statically allocated (which would be good
to avoid memory fragmentation). You may want to implement a copy
constructor and a copy assignment operator, as per the [rule of
three][].

[rule of three]: https://en.wikipedia.org/wiki/Rule_of_three_(C++_programming)


message:
LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board

As I am learning the Arduino coding, I want to see if my program can turn on the LED light. I have tried all the things, but the code does not start the LED light I have installed on the board.

The code compiles successfully and upload on the board, but nothings happens after that. See the output logs as below:

**See all the configuration of board as below:**

**The board I have:**
UNO+WiFi R3 ATmega328P+ESP8266 CH340G Board compatible with Arduino

https://robocraze.com/uno-wifi-r3-atmega328p-esp8266-ch340g-board-compatible-with-arduino

**Board switch settings:**

5,6,7 => ON (to upload the code from Arduino IDE)

**Yellow LED installed:**

13 => Positive, GND => Negative

**Board setup:**

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

**Arduino IDE Setup:**

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

  [1]: https://i.stack.imgur.com/e6Oep.jpg
  [2]: https://i.stack.imgur.com/om58Q.png

**Program:**

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

    void loop()
    {
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);
      delay(2000);
    }

**Output logs after uploading the code:**

    esptool.py v2.8
    Serial port COM8
    Connecting....
    Chip is ESP8266EX
    Features: WiFi
    Crystal is 26MHz
    MAC: ec:fa:bc:3e:2e:6f
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Flash params set to 0x0340
    Compressed 261472 bytes to 193134...
    Wrote 261472 bytes (193134 compressed) at 0x00000000 in 17.1 seconds (effective 122.1 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting via RTS pin...

As you can see, the last message is **Hard resetting via RTS pin....**

Would anyone please tell me what is happening here? Why the program does not start the LED light even after everything looks fine?

Any help would be greatly appreciated.

Thanks.

body:
The [Uno+WiFi board][1] is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.

The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).

To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

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

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.

  [1]: https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html
  [2]: https://i.stack.imgur.com/DpNEK.png


message:
How to change Windows 10 Device Manager so Arduino NANO COM3 can operate on COM4

The Arduino ATmega328 NANO uses COM3 on my WINDOWS 10 computer,
but COM3 is NOT available.

QUESTION:
Please explain in detail how I can change this Arduino NANO
to operate on COM4

body: In device manager, right click on the device and select "Properties". Then go to the tab "Connection properties" and click on "Advanced". There you can change the COM port number assignment for a particular device.


body: In general, Windows assigns COM ports to USB devices when they are plugged in the first time.  If you have multiple USB sockets, the same physical device will be assigned a different COM port when plugged into different sockets.  Is it possible that you have changed your setup and are now using a different USB socket?  Try the others to see if that works.


message:
When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module?

I recently found this model with the ID 'HW-0519' on it. It can be found online ([HW-0519 in Aliexpress][1]) and is sold for the purpose of converting UART to RS485 communication using Arduino devices. The MAX485 module ([MAX485 in Banggood][2]) is the more commonly used module for this purpose and has been used in many projects. The MAX485 has the following pins DI (data in), RO (receiver out), DE (Data Enable), RE (Receiver Enable), VCC, GND and the 'A' and 'B' pins for the RS485 device (Shown below).

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

The HW-0519 module, has a slightly different pin configuration, and I can't seem to wrap my head around it. It has Tx and Rx pins, which I am guessing match up with RO and DI respectively, but don't have enable pins. They have the VCC and GND pins along with the 'A' and 'B' pins, but also come with this pin marked in Chinese. I translated it using Google translate and it translates to something similar to 'Ground'. Which is not connected to the GND pin though (Shown below).

[![enter image description here][4]][4]

Does anyone know whether I can use the HW-0519 module in the same manner as the MAX485? If so, are there any libraries written for this module? I want to use the module for communication with a pH sensor like the one in [this link][5].

  [1]: https://www.aliexpress.com/item/32817749136.html
  [2]: https://sea.banggood.com/2Pcs-5V-MAX485-TTL-To-RS485-Converter-Module-Board-p-948302.html
  [3]: https://i.stack.imgur.com/MprWM.jpg
  [4]: https://i.stack.imgur.com/wUGOT.jpg
  [5]: https://www.seeedstudio.com/RS485-Soil-Moisture-Temperature-EC-Sensor-S-Soil-MTEC-02-p-4633.html

body:
I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.

It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module [here][1]. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.

  [1]: http://pdacontrolen.com/basic-modbus-rtu-master-rs485-test-with-esp32-xy-k485-pzem-016-without-libraries/


body:
I have the HW-0519 (bought as https://www.amazon.co.uk/gp/product/B0BCFLTLGJ/ at £9.98 for 8x in 2023-09) and it matches the picture above quite closely enough. It is a variant, and the first difference I see is the (?) polyfuses JK075 above are T010 on mine.

I picked this because it has protection components on the board which others don't have - including the MAX485 board from Banggood linked above.

Both boards lack mounting holes but the MAX485 board has pins which (if they align?) might assist breadboard usage. For me, the prototyping phase will start with epoxying HW-0519 to a Lego brick.

I found a circuit diagram at https://easyeda.com/modules/HW-0519-TTL-to-RS485-converter_c4836920e8ec45b3924add8ac2acbe57 for something similar which helped me work out what's what. I'm not going to steal a copy and upload here but it looks like https://web.archive.org/web/*/https://image.easyeda.com/components/c4836920e8ec45b3924add8ac2acbe57.png .
* Starting at the A+ / B- lines,
* fuses F1 and F2 of type "108L" (presumably polyfuse type),
* 120Ω bus termination R14 across,
* then an SM712 asymmetric TVS protection chip https://www.semtech.com/products/circuit-protection/rs485/sm712 ,
* finally the pull-up resistors 4k6 and MAX348 chip named U6.

My board is a cousin of the circuit diagram I found.
* chips are named U2 (unmarked SOIC14, maybe 74HC04) and anon unmarked SOIC8,
* its TVS protection is done as three chunky 2-pin diodes marked WK as in the HW-0519 above,
* bus termination resistor is R9 and **you have to short R0 to terminate the bus**, so one at each end but not in the middle, in the usual way.
* TVS protection comes to that third bus pin 球大(??) which I think is "earth big (something)"

Note that the bus ground is *not* connected to the logic ground GND on the 4-pin connector. You need to **provide bus ground separately** and maybe from a different source after considering fault currents.


message:
Why my arduino board does not blink properly?

I have two files

blink1.cpp
```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

[![Blink1][1]][1]

blink2.cpp
```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

[![Blink2][2]][2]

------

The difference between these two files are the definition of only a few unused ports in blink2.

I compile and upload them to the board by

```
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex
```

The first one does not blink properly but the second one does. What is the problem of the first code?

  [1]: https://i.stack.imgur.com/3zQOj.gif
  [2]: https://i.stack.imgur.com/Jkb5t.gif

body:
There are a couple of issues here.

One of them has already been raised in a comment:

```diff

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {
```

The more serious issue is in the command line you used to compile the
program. When compiling for an Uno, you should add the option
`-mmcu=atmega328p`. This way the compiler knows which version of the C
runtime it should add to your program. Otherwise the compiler will
include no runtime at all.

The C runtime does some important initializations. For example, it
clears the register `r1`, which is _required_ by the ABI, and _assumed_
to be the case by the compiler. For example, when you write `*portB =
(int8_t) 0x00;`, the compiler copies `r1` to the port, without first
clearing it. Another important role of the C runtime is to call
`main()`. Without it, the program will start by executing whichever
function happens to be at the start of the flash. Unless you program in
assembly, you have no control over that. If the first function happens
to be `main()`, the program may work as expected. If it is another
function, that function may then return to the bootloader. Any seemingly
innocuous change in the program can then change the behavior.

Then a few minor issues, that should not prevent the program from
working:

* `int8_t` is meant to be a signed type. If you want the unsigned
  version, use `uint8_t` instead. Sure, these are your own type
  definitions, but creating a type that conflicts with a standard type
  can only create confusion. Best option is to drop the definition and
  include `<stdint.h>` instead.

* Whereas `port_type` should certainly be a “pointer to volatile” data,
  there is no point in making the pointer itself volatile. That can only
  hinder valid optimizations.

* `portB` and `ddrB` should be `const`, and that may allow the compiler
  to better optimize them. But why not use `PORTB` and `DDRB` from
  `<avr/io.h>`?


message:
Why SSD1306 OLED display get scrambled text when printing messages from separate tasks in RTOS? (revised)

ESP32 with RTOS, test app with 2 independent tasks. Each prints a message to OLED display.
Why text gets frequently scrambled? Mutex have been used to share display resource.

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

    #define DEBUG_ESP              //comment out to deactivate debug console verbose
    #ifdef DEBUG_ESP
      #define pDBGln(x) Serial.println(x)
      #define pDBG(x)   Serial.print(x)
    #else
      #define pDBG(...)
      #define pDBGln(...)
    #endif

    //create handle for the mutex. It will be used to reference mutex
    SemaphoreHandle_t  xMutex;

    //*********************************SSD1306 OLED Display
    #define I2C_SDA              14
    #define I2C_SCL              15
    #include <Wire.h>
    #include <Adafruit_SSD1306.h>
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
    //*****************************************************

    void setup() {

      // create mutex and assign it a already create handler
      xMutex = xSemaphoreCreateMutex();

      Wire.begin(I2C_SDA,I2C_SCL);
      Serial.begin(115200);

       // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        pDBGln("SSD1306 allocation failed - Halt");
        for(;;); // Don't proceed, loop forever
      }else{
        // Show initial display buffer contents on the screen --
        // the library initializes this with an Adafruit splash screen.
        display.setTextSize(1);
        display.setTextColor(SSD1306_WHITE);
        display.setCursor(0, 0);
        display.clearDisplay();
      }

        xTaskCreatePinnedToCore(
            task01,             /* Function to implement the task */
            "task01",           /* Name of the task */
            10000,              /* Stack size in words */
            NULL,               /* Task input parameter */
            1,                  /* Priority of the task */
            NULL,               /* Task handle. */
            0);                 /* Core where the task should run */

        xTaskCreatePinnedToCore(
            task02,             /* Function to implement the task */
            "task02",           /* Name of the task */
            10000,              /* Stack size in words */
            NULL,               /* Task input parameter */
            1,                  /* Priority of the task */
            NULL,               /* Task handle. */
            1);                 /* Core where the task should run */
    }

    void loop() {}

    void task01( void * parameter ){
      while(1){
        printToDisplay("Task01..............");
        vTaskDelay(1500);
      }
    }

    void task02( void * parameter ){
      while(1){
        printToDisplay("Task02..............");
        vTaskDelay(2500);
      }
    }

    void printToDisplay(String text){
      bool myMutex;
      while(1){
        // take mutex
        myMutex = xSemaphoreTake(xMutex, portMAX_DELAY);
        if(myMutex){
          static byte   lineCounter = 0;
          static String displayText[8];
          if(lineCounter>7){
            for(int i=0;i<7;i++){
              displayText[i] = displayText[i+1];
            }
            displayText[7] = text;
            display.clearDisplay();
            display.setCursor(0, 0);
            for(int i=0;i<8;i++){
              display.println(displayText[i]);
            }
          }else{
            displayText[lineCounter] = text;
            display.println(displayText[lineCounter]);
            if(lineCounter<8){lineCounter++;}
          }
          display.display();

          // release mutex
          xSemaphoreGive(xMutex);
          break;
        }
      }
    }

The code below uses no RTOS and works perfectly: (my project requires RTOS)

    #define DEBUG_ESP              //comment out to deactivate debug console verbose
    #ifdef DEBUG_ESP
      #define pDBGln(x) Serial.println(x)
      #define pDBG(x)   Serial.print(x)
    #else
      #define pDBG(...)
      #define pDBGln(...)
    #endif

    byte lineCounter = 0;

    //*********************************SSD1306 OLED Display
    #define I2C_SDA              14
    #define I2C_SCL              15
    #include <Wire.h>
    #include <Adafruit_SSD1306.h>
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
    //*****************************************************

    void setup() {

      Wire.begin(I2C_SDA,I2C_SCL);
      Serial.begin(115200);

       // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        pDBGln("SSD1306 allocation failed - Halt");
        for(;;); // Don't proceed, loop forever
      }else{
        // Show initial display buffer contents on the screen --
        // the library initializes this with an Adafruit splash screen.
        display.setTextSize(1);
        display.setTextColor(SSD1306_WHITE);
        display.setCursor(0, 0);
        display.clearDisplay();
      }
    }

    void loop() {
      pDBGln("Start Display Test...");
      task01();
      task02();
    }

    void task01(){
      printToDisplay("Task01..............");
      delay(500);
    }

    void task02(){
      printToDisplay("Task02..............");
      delay(500);
    }

    void printToDisplay(String text){
      static byte   lineCounter = 0;
      static String displayText[8];
      if(lineCounter>7){
        for(int i=0;i<7;i++){
          displayText[i] = displayText[i+1];
        }
        displayText[7] = text;
        display.clearDisplay();
        display.setCursor(0, 0);
        for(int i=0;i<8;i++){
          display.println(displayText[i]);
        }
      }else{
        displayText[lineCounter] = text;
        display.println(displayText[lineCounter]);
        if(lineCounter<8){lineCounter++;}
      }
      display.display();
    }

  [1]: https://i.stack.imgur.com/JD6cJ.jpg
  [2]: https://i.stack.imgur.com/Ab7tB.jpg

body:
This is a formal answer to the question based on the comments between Paulo Borges and Majenko.

----

The ESP32 is dual core, meaning that it comes with 2 Xtensa LX6 32-bit microprocessors: core 0 and core 1.

The issue is not a bug in your code but rather that you are running your threads on Core 0 instead of Core 1.

In the ESP, the Core 0 is used for the RF communications. Even with the mutex protection, it is highly likely that your tasks are having timing issues.

Move Task01 and Task02 into Core 1 and your program will run without any display issues.


message:
Get production count for current minute

I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds.  I have a system for detect real-time product output and get it to the Arduino using digital input pin.

I wrote below codes and for that.
what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.

**My question is, Is there any easy and efficient way for do this without using few variables ?**

        #define countSensor 8  //count sensor input

        uint8_t records[60];
        uint8_t countSensorState = 0;
        uint8_t totalCount = 0;
        uint8_t countOfLastSec = 0;
        uint8_t lastCount = 0;
        uint8_t lastMinCount;
        uint32_t preMills = 0;

        void setup() {
          Serial.begin(9600);
          //init sensor input pin
          pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

          //clear random value of memory locations
          for (int i = 0; i < 60; i++) {
            records[i] = 0;
          }

        }

        void loop() {
          //get count at falling edge
          if (digitalRead(countSensor)^ countSensorState) {
            if (!digitalRead(countSensor)) {
              totalCount++;

            }
            countSensorState = digitalRead(countSensor);
          }
          //get count of last second
          if (millis() - preMills > 1000) {
            preMills = millis();
            countOfLastSec = totalCount - lastCount;
            lastCount = totalCount;
            //record last 60s counts
            //--shift back a second in the array
            for (int i = 0; i < 59; i++) {
              records[i] = records[i + 1];
            }
            //--record current second in array at 59th index
            records[59] = countOfLastSec;
            //get last 60s count
            for (int i = 0; i < 60; i++) {
              lastMinCount += records[i];
            }
            Serial.println(lastMinCount);
          }

        }

body:
As I said in a comment, if you really need to compute that moving sum,
you absolutely need to store the last 60 one-second counts in memory.
That being said, there are a few small issues with this code for which I
would have some suggestions:

* There is no point in storing `totalCount`. You do not really use it,
  and it will eventually overflow.

* You do not need to explicitly initialize all globals to zero, as that
  is implicitly done by the runtime: it is a requirement of the
  language.

* Your are calling `digitalRead(countSensor)` three times in a row. The
  logic for counting edges is sound as long as the three calls yield the
  same result, but that is not guaranteed. It is safer to only read the
  pin once per loop iteration.

* Similarly, the two calls to `millis()` can yield different results,
  and that will make your timings slightly off.

* The condition `millis() - preMills > 1000` will only fire when
  1001 milliseconds have elapsed. Because of the way `millis()` works,
  sometimes you will miss the 1001th millisecond, and process on the
  1002nd millisecond. In order to avoid accumulating these small timing
  errors, it is best to update `preMills` by always adding exactly 1000.

* As pointed out by jsotola, you do not need to shift the array: you can
  instead reuse the array cell that holds the data you do not need
  anymore.

* You do not need to perform the whole sum every time. You can instead
  update the previously computed sum by removing the count of the second
  that falls off the current one-minute window, and adding the count of
  the current second.

Here is my attempt at applying all the above suggestions. Warning: it
has not been tested.

```c++
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

void setup() {
    Serial.begin(9600);
    pinMode(countSensor, INPUT_PULLUP);
}

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}
```


message:
Is it safe to connect VCC to a data pin on Attiny chips?

I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

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

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

body:
As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.

It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).


message:
Automate capturing photograph on ESP32-CAM

I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs **automatically** for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.

body:
Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera
The project has different things, but definetelly doing what you asked, captures photo by external event, command...


message:
Is it advisable to use Serial.write in an ISR when loop() routinely uses Serial.read?

I do not know much electronics.

I have Nano v3 as I2C master, it reads 5-byte packets (of delimtted data) from PC's USB port, processes it and forwards it.

I now need to implement a way to signal PC if something went wrong down the line. I don't want to clutter I2C channel and its just a flag so I think interrupt is best for my purpose.

While writing the ISR function I am not sure if its advisable to write data using Serial, because loop might have read 2-3 bytes of the 5-byte message packet. And I don't know if it will overwrite data coming from PC or what...

**What will happen if I Serial.write(0x1) (suddenly, in an ISR function) while loop() was reading data from same Serial**?

I don't know how to test this myself.

body:
Reading and writing of serial data are separate functions. When you `.write()` you just append the data to the TX buffer. When you `.read()` you just take the next character from the RX buffer.

All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.

That said, you *really* shouldn't use `Serial` inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in *your* ISR then the sending can never happen until you leave your ISR.  For the odd occasional byte it's not really a problem, but if the TX buffer fills up `Serial.write()` will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.

So it's best to avoid any `Serial` operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in `loop()` to report anything.


message:
Can I use an accelerometer to measure the velocity of a car in a curve?

I am making an application that is used to measure the velocity, it has an accelerometer that measures the component acceleration in the XYZ-axis. When the car is moving just straight the measurement is ok, as only linear components are involved.

My doubt came when the car is on a curve, I am not sure if the accelerometer can measure correctly in such situation or if it is necessary to apply a gyroscope to measure any missing component.

The code snippet for measure the total acceleration is shown below, I measure the acceleration in each axis and I remove the gravitational to finally calculate the velocity and the speed

        float AccTotal_X = ((AcX - grav_X)*9.81);
        float AccTotal_Y = ((AcY - grav_Y)*9.81);
        float AccTotal_Z = ((AcZ - grav_Z)*9.81);

        float Vx = vx_0 + AccTotal_X*dt;
        vx_0 = Vx;
        float Vy = vy_0 + AccTotal_Y*dt;
        vy_0 = Vy;
        float Vz = vz_0 + AccTotal_Z*dt;
        vz_0 = Vz;

        speed_dt = sqrt(pow(Vx,2)+pow(Vy,2)+pow(Vz,2))*3.6;

body:
I found out the answer to the question in the following article [**SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments**][1]

  [1]: https://ieeexplore.ieee.org/document/6847999

According to the article

> When a vehicle makes a turn, it experiences a centripetal force, which
> is related to its speed, angular speed and turning radius. Thus, by
> utilizing the accelerometer and the gyroscope, we can derive the
> tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.

The equation to measure the tangential velocity is:

**v = Rω** (1),

Where **v** is the tangential speed, **R** the radius of the curve and **ω** the angular speed.

As the centripetal acceleration is given by **a = ω²R** (2), reformulating (2) and substituting in (1), it is obtained:

**v = a/ω** (3).

Both **a** and **ω** are given by the accelerometer and the gyroscope respectively.


message:
connect USB keyboard to Arduino using clk and data wires

Edit:
What I'm looking for is some kind of library which could be used with an arduino to read the HID protocol output from the Data+ and Data- cables of the USB.

==========
If I cut the cable of a usb keyboard, plug in power and ground can I use the clk and data wires to read keystrokes into the Arduino? If so any pointers to libraries and schematics?

Simple I instructions? The "for dummies" version?

***EDIT***

Following some of the suggestions below I found this:

https://github.com/julianschuler/USBKeyboard

Which looks like what I want to do, basically hook up the lines into the arduinio and read from the keyboard using the HID protocol in this library.

***EDIT 2***

That doesn't do what I want. Does anyone know how this could be accomplished?

body:
USB doesn't have data and clock lines. It has a pair of data lines with inverted polarity (D+ and D-). The USB protocol is considerably more complex than you seem to imagine.

**However** there is a caveat: some keyboards have the ability to work in *IBM PS/2* mode. For this you will need a USB to PS/2 adaptor (pictured below) and then use the [PS2Keyboard.h](https://github.com/PaulStoffregen/PS2Keyboard) library. Your mileage may vary, though, as not all keyboards will work.

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

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


message:
Calling class member from .h file

In `.ino` file I have a class defined (called `IPmonitoring`).Also, inside the same `.ino` file, I call a `.h` file ( which is located "above" class `IPmonotoring`).

When I try to call members of `IPmonitoring` inside .h file - I get an error, which usually I solve using `extern`, but seemingly it is not the same for classes.

What should be done ?

Guy

body:
You need to re-think your layout, and your usage of the .h file.

* You should never have code in a .h file unless it is either `inline` or part of a `template` class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.

For example your IPmonitoring class would be *declared* in a .h file, and *defined* (or *implemented*) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you `#include` the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with `extern`.

In the Arduino world it is common to create a single instance of the class in the class's .cpp file and `extern` it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.

This is how most libraries are written.

For example:

```c++
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

```

And:

```c++
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}
```

And finally:

```c++
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}
```


message:
read first line from sd card and save the position for again reading from sd card

I am reading sd card .txt file, I want to read the first line then how to save the position of the pointer for the next line read?

body:
You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.

If you really *do* need to you can use the `.position()` and `.seek()` functions:

Save the location:
```c++
uint32_t pos = myFile.position();
```

Recall the location:
```c++
myFile.seek(pos);
```

Documentation:

* https://www.arduino.cc/en/Reference/FilePosition
* https://www.arduino.cc/en/Reference/FileSeek


body:
File myFile = SD.open("test.txt", O_RDWR);

    if (myFile) {

      while (myFile.available()) {
        int i = 0;
        while (i < myFile.size()) {
          inputString =  myFile.readStringUntil('\n');
          //Serial.print(inputString);
          if (myFile.readStringUntil('\n')) {

I have set a size for the loop, every time it returns "I want it to read a new line" but it skips, what could be the reason?

To help with this question, I wanted to show the process I did on the same question. Thank you, I will ask the question elsewhere.
I am sending from the serial port when the end of the line is not read twice, during each reading. I'm sending line by line


message:
In multidimensional arrays, can you use variable arrays or their names instead of the actual data?

Referring to this thread
https://arduino.stackexchange.com/questions/43173/how-to-declare-and-use-variabled-arrays-inside-arrays

Example

```
byte array[2][4] = { {1,2,3,4}, {5,6,7,8} };
Serial.println(array[0][2]); is equal to '3'.
```

Instead of using {1, 2, 3, 4} and {5, 6, 7, 8} I want to be able to declare separate arrays for each of them and just put the name.

Another big issue is putting arrays of different sizes for each entry and it would be wrong to do so. Is this really not possible? Do I have to use some other concept instead if I want to have an array that contains entries of arrays that have different sizes? I heard about pointers but not familiar with that.

Example,

```
byte arrayX[3] = {1, 2, 3}
byte arrayY[4] = {5, 6, 7, 8}

byte array[2][4] = { arrayX , arrayY };
```

Take note that the code was not taken from the link I mentioned, I just used the same array names. Also I changed arrayX from the link to 3 entries because I want to emphasize the part of my question if it is possible if arrays have different sizes and you would just use the biggest size?

Now I think this is wrong and I haven't tested it currently but I want to ask if there is a solution that makes use of what I have mentioned? The site I linked to gave a solution which feels very redundant in terms of declaration and I would not want that. This is the solution mentioned there.

```
byte arrayZ[2][4] = {
  {arrayX[0],arrayX[1],arrayX[2],arrayX[3]},
  {arrayY[0],arrayY[1],arrayY[2],arrayY[3]}
};
```

The issue I had when searching the internet is the same as the link. "Surfed on the internet to find a bunch of examples but the only difference is that they don't use arrays that have been declared to have a name inside array."

body:
Two-dimensional arrays come in two "flavours". Actually, multi-dimensional arrays are possible in any combination of these.

- All elements in a rectangular grid, at least from the abstract view of the programming language;
- A one-dimensional array of one-dimensional arrays.

If you declare:

    byte array[n][m];

then you have reserved space for "n times m" bytes. From the programmer's view it is a rectangular grid, actually all bytes are in sequence in a one-dimensional array. This is because the memory of our computers are commonly organized as a big one-dimensional array of bytes. The compiler generates the correct calculation for the offset into this array, multiplying one index with the size of the width (or length, depending on your mental model) and adding the other index.

You can initialize such an array with the nested set of curly braces like this:

    byte array[n][m] = {
        { /* ... */ },
        /* ... */
    };

But you cannot initialize it as you show.

Otherwise, if you declare

    byte* array[n];

then you have reseved space for "n" pointers to bytes, that is a one-dimensional array of pointers. Each of these pointers can point to a different or the same one-dimensional array of bytes, or to no array at all if it's `nullptr`.

Now you can set up the array as you like:

    byte arrayX[m1] = { /* ... */ };
    byte arrayY[m2] = { /* ... */ };

    byte* array[n] = { arrayX, arrayY, /* ... */ };

The arrays `arrayX` and `arrayY` (and any further) don't need to have the same length. Each can have its own length. But beware, you need to trace the length somehow to avoid out-of-bounds accesses. And of course, you need to check or be sure that a pointer is not null before dereferencing it.

In both cases you can access a single element with:

    byte element = array[i][j];
    array[k][l] = 23;

This is because the syntax with the brackets is equivalent to the dereferencing operator:

    x[y] == *(x + y)

_Note 1: Since Arduinos are programmed in C++, there is another option. You can use references instead of pointers. Because it is really hard to create a null reference, some see it as a safety measure against null pointers._

_Note 2: Again, since Arduinos are programmed in C++, you can implement an own class that provides the `operator[]`. With this option you can do any magical stuff, but it might break the user's expectation. Be careful if you go that route._


message:
Serial plotter looks different and doesnt print graph

When I open my serial plotter to get the graph for my HC-SR04 sensor it doesn't show anything. My plotter looks different too. I have attached images below as well.

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

[![This is what it shows][2]][2]

  [1]: https://i.stack.imgur.com/xdbuk.png
  [2]: https://i.stack.imgur.com/TUIj1.png

Only those numbers on the **top-most** move with time.(100,200,300)
Here's my code:

```c++
int trigPin = 12;
int echoPin = 11;

int pingTravelTime;
float pingTravelDistance;
float distToTarget;

int baudRate = 9600;

int dT = 10;
int dT2 = 500 ;

String msg1 = "The distance is equal to ";
String msg2 = "cm";

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(dT);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(dT);
  digitalWrite(trigPin, LOW);

  pingTravelTime = pulseIn(echoPin, HIGH);

  pingTravelDistance = pingTravelTime * ((765. * 5280. * 12.) / (3600. * 1000000));
  pingTravelDistance = 2.54 * pingTravelDistance;
  distToTarget = (pingTravelDistance / 2);

  Serial.println(msg1 + distToTarget + msg2);

  delay(dT2);
}
```

What do I do??

body:
The serial plotter expects you to send numbers, and only numbers. If it
reads any other text, like for example

“The distance is equal to 9.88cm”

It assumes these are the names of the columns of data that are to
follow. So it chooses one color for each column and prints the color key
on top of the graph.

> What do I do??

Just remove the prose and print only the numbers. You may print
something like “distance(cm)” in `setup()` if you want to have the key
displayed, but that is not required.


message:
What does an Arduino do if the serial connection is closed on the other end?

I have a simple method that simply waits for an input, computes a response, and sends it:

    void loop() {
      if (Serial.available() > 0){
        input = Serial.read();

        if (input == 10){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);

          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);

          duration = PulseDuration(echoPin, HIGH, 6000);
          distance = duration * 0.00034/2;  // 0.00034 m/us is speed of sound

          Serial.println(distance, 4);
          }
      }
    }

My question: What happens to the arduino if I close the serial connection from the receiving end while it's printing out data (in the last line of the loop)?

Context and motivation:

The program works well most times. I can open a python program that sends the requests and prints out the reply using pyserial. After I close the python side and reopen it, connection is set and I can start listening on the side nicely just like the first time. Sometimes, however, when I try to restart the python program, I get a connection error saying that the port is already opened (I'm running in Windows.. there are tons of posts about this problem, but none of them have been helpful). Some other times, when connecting with the python program (which connects with `connection = serial.Serial(self.arduino_port, 9600, timeout=0)` it just blocks and doesn't connect, it doesn't give the "port already opened" error, and it doesn't advance to the next statement.
I am confident I did close the previous python run before attempting a new one (process explorer shows no active python programs running, it also shows no open processes using a serial handler). I'm not here to solve that problem directly, though, just to ask a related question.

I'm also confident running `connection.close()` does not terminate the arduino program, as I have been able to restart my python program without having to reset the arduino or anything, suggesting the arduino kept running its loop after I closed the connection on the python side.

All that to say that my latest hypothesis is that these issues arise when I close the serial connection `connection.close()` while the arduino is printing, but because the port is closed, that Arduino is stuck and cannot do the Serial.println(), as the USB never asks to flush the data in its buffer.
Is this possible/does it make sense? What happens to the arduino if I close the serial connection while it's printing out data?

I'm not posting my python program here as it's not directly relevant to the question and I can't seem to make a minimum reproducible program that doesn't expose confidential code.

body:
That's some strange Intel monstrosity. It's impossible to know what it does or how. Intel's foray into the Arduinosphere was brief and somewhat abortive.

In general though (for most cores) the DTR signal (and sometimes the RTS signal too) of the CDC/ACM protocol is used to "gate" the serial data - if it's asserted then serial data gets sent through to the host PC. If it's not asserted then it just gets thrown away.

I have seen cores where if DTR is not asserted the data gets buffered until the TX buffer is full and then blocks, but that is rare.

You might find your answer if you delve into the core's source code, but you may find that big chunks of it are hidden away in closed source pre-compiled libraries, and the fact it seems to run some custom RTOS means it'll be even more obfuscated. YMMV...


message:
2 instanced of ESP8266Ping

I'm using `ESP8266Ping` lib inside my `iot` lib which hanldes Wifi connectivity and MQTT messages. Since it create its own instance called `Ping` when calling `#include <ESP8266Ping.h>`- it had to be place in `iot.cpp`.

I writing another library, `IPmonitor` which checks clients on the network (using pings), I wanted to use `ESP8266Ping` again.

My sketch file, create an instance of `iot` and `IPmonitor` for check/ log errors on monitored clients.

But I get error of using the same library twice.

I guess that since `ESP8366Ping.h` library is defined it creates an instance of the class ( see mark below ):

    class PingClass {
      public:
        PingClass();

        bool ping(IPAddress dest,   byte count = 5);
        bool ping(const char* host, byte count = 5);

        int averageTime();

      protected:
        static void _ping_sent_cb(void *opt, void *pdata);
        static void _ping_recv_cb(void *opt, void *pdata);

        IPAddress _dest;
        ping_option _options;

        static byte _expected_count, _errors, _success;
        static int _avg_time;
    };

    #include "ESP8266Ping.impl.h"
    PingClass Ping;                     // <----- This

    #endif

How can it be solved ?

body:
With that library... you can't. All the code is in one big monolithic .h file. As you well know by now that is a big no-no. The author should be given a big slap on the wrists.

The closest you could do without re-writing the whole library is to just copy the class definition from the outer .h file and create an `extern` to the existing object - maybe make your own copy of the `ESP8266Ping.h` file without the `#include "ESP8266Ping.impl.h"` and `PingClass Ping;` (the latter of which you change to an `extern`).


message:
Obtaining angular velocity from quaternion data (BNO055)

I'm able to get quaternion data from the BNO055 sensor, and would like to convert these to angular velocity for my project. I know you can pull the gyroscope directly for the data, but from what I understand using quaternions and converting those is more robust?

I found a function that does this in a Adafruit repository for the sensor. However, I'm not sure what the Delta time variable should be equal to, in relation to the sample frequency. Could anyone advise?

Here is the function code:

      Vector<3> toAngularVelocity(double dt) const {
        Vector<3> ret;
        Quaternion one(1.0, 0.0, 0.0, 0.0);
        Quaternion delta = one - *this;
        Quaternion r = (delta / dt);
        r = r * 2;
        r = r * one;

        ret.x() = r.x();
        ret.y() = r.y();
        ret.z() = r.z();
        return ret;
      }

And the [link][1]

  [1]: https://github.com/adafruit/Adafruit_BNO055/blob/master/utility/quaternion.h

body:
I do not know how to interpret the data given by that sensor, but from
reading the code, the meaning of `dt` is pretty clear.

The function you show assumes that the sensor started in the reference
orientation (quaternion `one`), then rotated at a constant angular
velocity until it reached the current orientation (quaternion `*this`),
and this rotation happened over a time `dt`.

Then `dt` is the time required for moving from the reference orientation
to the orientation described by the quaternion `*this`. You should
probably check out the sensor's datasheet for more details on how the
orientations are provided.


message:
Calling functions between 2 classes

Class `myIOT2` contains a function that need to be called from class `IPmonitoring`:

    bool myIOT2::checkInternet(char *externalSite, byte pings)
    {
     return Ping.ping(externalSite, pings);
    }

This function is needed as a pinger in `IPmonitor`:

    void IPmonitoring::start(cb_func ping)
    {

            _ping_cb = ping;
    }

and this `cb_func` is defined by (inside `IPmonitor.h`):

    typedef bool (*cb_func)(char *externalSite, byte pings);
    cb_func _ping_cb;

inside my sketch (relevant parts only) I fail when `iot.checkInternet` is passed, while using a function `test` that calls `iot.checkInternet` succeeds:

    myIOT2 iot;
    IPmonitoring WiFi_service(ROUTER_IP, "Router");

    bool test(char *a, byte b)
    {
            bool x = iot.checkInternet(ROUTER_IP);
            return x;
    }

    void setup()
    {
    WiFi_service.start(iot.checkInternet); // <---- Trial a)fails
    WiFi_service.start(test);              // <-----Trail b)succeeds
    }

error is :

    home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino: In function 'void setup()':
    IPmonitor:436:45: error: no matching function for call to 'IPmonitoring::start(<unresolved overloaded function type>)'
             WiFi_service.start(iot.checkInternet);//
                                                 ^
    /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:436:45: note: candidate is:
    In file included from /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:2:0:
    /home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note: void IPmonitoring::start(IPmonitoring::cb_func)
         void start(cb_func ping);
              ^
    /home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'IPmonitoring::cb_func {aka bool (*)(char*, unsigned char)}'
    Multiple libraries were found

What is done wrong ? and why `test` succeeds ?

body:
There is a fundamental difference between a simple function and a function that is a member of a class.  You can't use a function pointer to point to a member function of a class: simply because that member function also includes information about the class instance that it belongs to.

The *proper* C++ way to handle it is to use [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function), but the Arduino AVR compiler lacks the full STL (Standard Template Library), so that can't be used on normal Arduinos. Other cores do have it, so you may well be able to use it on the ESP8266.

If you want to make your code portable between systems that may not have the full STL then there's other tricks you have to do:

* Use a wrapper function (which as you have found works), or
* Make a polymorphic class and store a pointer to the instance cast to the parent class - the parent class defines the functions that are allowed to be called from the pointer.


message:
How can i call lcd.begin() from several different code files in a proper way?

I have a project split into several files:

```
//Loop.cpp
#include "LiquidCrystal.h"

void setup(){
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    lcd.begin(16, 2);
}

void loop() {
//Code
}
```

```
//Display.cpp
#include "LiquidCrystal.h"

namespace display {
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket) {
    lcd.setCursor(0,1);
    lcd.print("Foo");    //This creates display error, unless i call lcd.begin(16, 2) in this function
}

} //namespace display
```

My initial problem is that - without calling lcd.begin() from within displayData() - the characters aren't displayed correctly. In other words, calling lcd.begin() in setup() doesn't help. (It appears to me that setup() has implicit static property, no?)

As an attempted solution, i could create an lcd object in Display.cpp, and call lcd.begin() from within displayData(). Even though characters are displayed properly, this gives me display flickering. (Presumably as a result of calling these functions repeatedly in the loop during runtime).

So, the only solution to this dilemma that i can come up with is to call lcd.begin() from a function written to run only once inside of displayData(). Or is it?

My question is, are there other more elegant solutions/alternatives?

body:
The object called `lcd` that you create inside the `setup` function is a local variable. It only lives as long as that function is executing - so not very long. It doesn't exist outside that function.

The `lcd` object you have in `namespace display` on the other hand is a global variable. That one lives as long as your program, which means until you reset your Arduino here. (It is completely unrelated to the object inside `setup`.)

If you want all your LCD code to be grouped inside the `display` namespace, you could do this in `Display.cpp`:

    namespace display {
      // This is a global variable, full name `display::lcd`
      LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

      void setup() {
        // this `lcd` refers to the global `display::lcd` defined above
        lcd.begin(16, 2);
      }

      // rest of the display functions
    }

Create a `Display.h` file to provide prototypes for the display module:

    #ifndef DISPLAY_H
    #define DISPLAY_H

    // Include the header that defines InputPacket and DataPacket here

    namespace display
    {
    void setup();
    void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket);
    }

    #endif

Then your main file can call the display function. The main file doesn't even have to know that you're using an LCD if you do package all LCD code in the display file.

    #include "Display.h" // no need to include LiquidCrystal.h if all
                         // LCD handling is done in Display.cpp

    void setup(){
      // Initialize display
      display::setup();
    }


message:
What's the time out of Wire.begin()?

Here's a schematic of my project:

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

The purpose is to make laptop work as keyboard for desktop PC. Nano uses Serial.read() to get keystrokes from laptop and forwards key press and release data to Leonardo (using I2C) acting as USB-HID keyboard.

Nano's setup looks like:
```
void setup() {
  Wire.begin();
  Serial.begin(14400);
  Serial.write("Hello");  // https://serialport.io/docs/api-stream#serialpor|
  pinMode(LED_BUILTIN, OUTPUT);
}
```

Leonardo's setup looks like:
```
void setup() {
  Keyboard.begin();
  Wire.begin(4);
  Wire.onReceive(cbfunc);
}
```
I have tested both boards individually, but not the whole setup. Whenever either board connects to USB port it powers up due to +5 volt from USB. Now that I have i2c wires in place, I am confused -

if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at `Wire.begin(4)`? Will it wait (1s, 5s, forever) until i2c-master comes online?

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

body:
Generally you should not provide power to any pin of a device, which is powered off. That can cause current flowing through clamping diodes to ground and might destroy the pins hardware or the device (also it can lead to weird situations, where the device is somewhat powered through the IO pin, which might lead to instability).

You can either cut the connection between the devices, if only one of them is powered (this should be possible with some extra components), or you can power both devices from one USB port. For the other port you would cut the V+ (positive supply voltage) line of the USB port/cable (this makes sure, that you don't get a bad current between both computers on the USB power line, if they provide a bit different voltage). Since the ground wire still connects both computers and the Arduinos, the communication will still work correctly.

> if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at Wire.begin(4)?

The `Wire.begin()` line won't get stuck, since it doesn't do much on the lines and it doesn't know, if something is connected on the other end, until some transaction happens on the bus. But it might be, that any transaction from the powered Arduino (the master) might cause a blocked I2C bus (since at some places the library waits for the lines to get high. The connection through the clamping diodes might hold the line at low. I'm not sure about that). Then you would need to reset both Arduinos, to make sure, that the bus is in a healthy state.

The solution from above (powering both Arduinos from one USB port) will also make sure, that both Arduinos start at the same time and thus won't block the bus through the clamping diodes.


message:
Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State

**I Took a output from ESP8266 and Connected it with Arduino Nano Analog input A0**

i use BLYNK app to on/off D0 pin in ESP8266 , and i connected ESP8266 D0 pin with Arduino Nano A0 analogPin.

when esp8266 D0 in high state , the analogRead value in arduino nano serial monitor it show the value 395.

why not 1023 on high state .[![enter image description here][1]][1]

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

body:
There are two problems here - one immediate and one which will be come apparent.

First off, you appear not to have connected the ground pins of the two boards together. This is important. Voltage is not an absolute value, it's a value *relative to some other point in the circuit*. This is why "voltage" is sometimes called "potential *difference*". Normally the point in the circuit that voltages are referenced to is termed "ground". Note: there is nothing special about ground, it's just an arbitrary point in the circuit - usually, but not always, the point where the voltage is lowest.  If the ground of the Arduino that it's using to compare incoming voltages against is not the same as the ground that the ESP8266 is using to create its output voltage in relation to, then the Arduino really can't know what the voltage is.

You can think of it as a person standing on the ground. Now I am about 6 feet tall. When I am stood up the top of my head is about 6 feet above the ground. But to someone who is stood on a nearby rise in the ground my head is only maybe 3 feet above the ground. Their ground is not the same as my ground.

The second problem, which will become apparent once you have connected the grounds, is that the Arduino measures voltages between 0 and 5V as values between 0 and 1023. However the ESP8266 doesn't operate at 5V, it operates at 3.3V. The highest voltage it can ever put out is 3.3V. The Arduino can never read that as 1023 because it's not 5V.  Instead it will read somewhere around 675. That is, 3.3V is two thirds of 5V, and 675 is two thirds of 1023.


message:
Dht 11 sensors give null value

void Sensor_value()
    {   server.handleClient();
        humidity = dht.readHumidity();
        temperature = dht.readTemperature();
     }

I want to make condition if temperature = null and Humidity= null that means the sensor fails to take reading so I want to return and take value again

body:
The way to do this is:

    float h = dht.readHumidity();
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);

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

See https://www.hackster.io/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975 and https://stackoverflow.com/questions/40874880/getting-nan-readings-from-dht-11-sensor.

`NULL` should only be used with pointers.


message:
Use chars in quotes in const char* as name of function

I have been trying for a long time how to use a word declared as `const string* word = "xxx"` as name of void function declared somewhere below in my code.

Here is example with `ssid`:

```c++
const char* ssid = "name_of_ssid";

void (*name of ssid*) () {

⠀//some code

}
```

I want to use word declared in `const char*` in quotation marks as name of function.
It can not be written just `void ssid()`.
Yes, I can set a name of void function manually, when `const char* ssid = "CoffeeWifi"` I can type `void CaffeeWifi()` but I want to do that by this way because my code is specific for this option and explaining this code here would be very difficult. When I change array of `const char*` word from `"xxx"` to `"yyy"` I want to  change the name of void from `void xxx()` to `void yyy()` as well.

How to do that? What function should I use?

Thank you!

body:
Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.

An example:
```
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}
```


body:
Being a const char, you can set it at compile time with a define and then use it.

    #define fstring(x) #x

    const char* ssid = fstring(SSID_NAME) ;

    void setup() {
      Serial.println("Start");
      Serial.println(ssid);
      SSID_NAME();

    }

    void loop() {}

    void SSID_NAME (){
      Serial.println(ssid);
    }

Instead of using quotes, this uses the stringize operator.


message:
Endurance of Arduino UNO during 24/7 operations and mild power fluctuations

I am designing an automation system for my research project and planning on using Arduino Uno to do the same. The program is to execute simple instructions based on few input parameters and does not need large computational powers. It is estimated it would take 26 minutes to run the program (26-minute cycle*) and it is expected that it would take anywhere from 3 weeks to 2 months to complete the project (1160 - 3300 cycles before reboot)

My question is as follows:
 1. Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?
 2. What is the influence of small voltage fluctuations on the endurance of electronics on the board?
 3. Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?
4. Is there any fatigue rating for the cyclic running of the program?

I am planning to power the entire system via a regulated 12V 600-watt battery bank and this bank would be periodically recharged.

*By cycle duration I mean the real word time required for completion of one batch. It is estimated that it's required to complete 1160-3300 cycles/batches for the research

body:
I see no problems in that. Given the program you write is stable and correct, the Arduino UNO will certainly work without any problems for months. It has an integrated voltage regulator, so you can attach a 12V battery directly and it automatically regulates voltage changes. The CPU and/or flash do not have any "fatigue" problems as long as the program is only read or executed. The program flash has a limited number of write cycles, but that also is far beyond where you'll get problems.

Where I do see a problem is in your use case. You seem to be doing quite complex mathematics with quite a lot of data, when one cycle takes 26 Minutes. You might not have enough RAM on the UNO to do this. It has only 2.5k (that is around 2500 bytes) of RAM. Where do you store the results?


body:
> Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?

Yes, it is. Though your program and wiring needs to be stable and correct.

> What is the influence of small voltage fluctuations on the endurance of electronics on the board?

Depends on what you call small. As long as you don't enter the brown-out region (where the voltage is so low, that the Arduino goes into reset for safety) or giving a too high voltage to it (See the specifications for that), you should be fine.

> Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?

The power draw of the Arduino depends on what you are doing with it. The best way would be to just measure the current of your application. Then you get the power by multiplying current and voltage. Normally you don't need a heatsink with an Arduino. The only part, that can get hot, is the linear voltage regulator. Depending on what you are interfacing with the Arduino, you might need to put a small heat sink on that (12V is a bit on the high side of input voltage for the regulator. It will dissipate the excess 7V as heat, so 7V multiplied by the used current). The microcontroller on the Arduino will not get hot (unless you are doing something terribly wrong).

And you should make sure, that the current for extra peripherals in your project doesn't flow through the Arduino, since that will place an extra burden on the voltage regulator. It should flow past it (means you connect them in parallel to the voltage source).

> Is there any fatigue rating for the cyclic running of the program?

No, not really. I think the flash memory (where the program is stored) has a data retention failure rate of less then 1ppm (parts per million) over 20 years. So the program will not be lost, until you plan to run your application a hundret years. Also there is no read limit on the flash memory, only a write limit.


body: I have Arduino here powered over year long, still working (running the same loop() again and again) without a glitch and it is not even hand-temperature hot in my living room - I expect it to run flawlessly for lot more years, until I will switch it off :)


message:
Connect ESP32 via MQTT

For a project I am working on, I need to connect my ESP32 board to another server via MQTT protocol. I am using the Mosquitto MQTT Broker and it is presently on my laptop. Following is the test code I am using, which I'll build around this program.
```

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*****";              //WiFi Name
const char* password = "********";      //WiFi Password
const char* server= "***.***.**.***";    //RPi or Machine IP on which the broker is

WiFiClient espClient;
PubSubClient client(espClient);

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Attempting MQTT connection...");
  client.connect("esp32");
  if (client.connect("esp32")){
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
    }
    return 0;
}

int reconnect() {
  unsigned long startAttemptTime = millis();
  while (!client.connected())
  {
    Serial.println("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("esp32")){                 //if (client.connect("esp32", MQTT_USER, MQTT_PASS)) {
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  return 0;
}

int send_mqtt(){
  setup_WiFi();
  char sss[15]="Hello World";
   if (!client.connected()){
    reconnect();
  }
  client.publish("esp32/test", sss);    //send message
  WiFi.disconnect(true);
  Serial.println("Sent");
  return 0;
}
void setup() {
  Serial.begin(115200);
  client.setServer(server, 1883);   //mqtt server details
  setup_WiFi();
  reconnect();
  send_mqtt();
}

void loop() {
  send_mqtt();
  delay(10000);     //Wait 10 secs before next transmission
}
```
I tried connection but got this error
>Attempting MQTT connection...failed, rc= -2

What am I doing wrong? Any changes I need to make to the .conf file about which I don't know?
Guide me.
Thank You in advance

body:
The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.

According to the [pubSubClient API documentation](https://pubsubclient.knolleary.net/api#state), the `rc = -2` code returned by `client.state()` is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:

1. Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running `ping XXX.XXX.XXX.XXX` (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.
2. Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, `127.0.0.1`.
3. Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app, or [MQTT Explorer](http://mqtt-explorer.com/) in Windows)
3. Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately [configure it](https://mosquitto.org/documentation/migrating-to-2-0/#listener-behaviour-changes) to accept incoming connections, otherwise it will only listen to the `localhost` interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.
4. On the MQTT server, can you see any connection attempts in Mosquitto's log file (`/var/log/mosquitto/mosquitto.log`)? There might be some error messages that give you further clues.


message:
Do I need an Microchip ATSAM3X8E Evaluation Kit?

I am intending to use the Arduino Due processors into my own designs. We have a very extensive (dozen of thousands of lines in .c code) sets of Arduino Due functional codes, and now I intend to move into a more solid form shape.

I have the following questions. What i need is some sort of feedback in order to answer those by myself and realize how to proceed.

 1. I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

 2. Which are the main differences between the [Microchip ATSAM3X8E][1] and the Atmel ATSAM3X8E? R: No, they are the same.

 3. I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

 4. Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E? R: No, they are the same.

 5. As note, there is a [Keil ARM SAM3X-EK Evaluation Kit][4] (also also [here][2] with its [brochure][3]), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

 6. If my concern about High Speed Serial is real, how should I evaluate it?

  [1]: https://www.microchip.com/wwwproducts/en/ATSAM3X8E
  [2]: https://www.keil.com/boards2/atmel/sam3x_ek/
  [3]: https://keilpack.azureedge.net/content/Keil.SAM3_DFP.1.2.2/Boards/Atmel/SAM3X-EK/Documents/doc_11156.pdf
  [4]: https://www.element14.com/community/docs/DOC-47133/l/atmel-atsam3x-ek-evaluation-kit

body:
> I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

What would make you think that? The chip is the chip regardless of what board it's soldered to. You have the native USB and you have all the UART connections direct to the chip. The board has no effect on that at all.  2Mbps is nothing. You can go *much* faster than that.

> Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E?

The label. When Microchip bought Atmel a few years back they bought *everything*. That includes the Malaysian factories where the Atmel chips are made (a friend of mine had the job of inventory combining and spent quite some time in Malaysia sorting it all out). Microchip ATSAM3X8E chips are made in the same factory by the same people to the same designs on the same machines. It's just they are now labelled "Microchip" instead of "Atmel".

> I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Is that a question or a statement. Or aren't you sure? The Due is just a chip on a board with some support circuitry. Everything that is in the chip is there, you can't remove it. There may be the case that a specific pin may not be brought out to a header, but you will have to compare the datasheet with the schematic in that case. The chip is not at fault here.

> Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E?

No. The two are 100% identical.

> As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

The ATSAMA3X8H is not commercially available. It was a specific custom chip made only for the SAM3X-EK kit. It is, essentially, a SAM3X8E with more IO pins and the ability to connect to SDRAM.

> If my concern about High Speed Serial is real, how should I evaluate it?

Your concern is not real. Only imagined. The only possibility is that the UART to USB chip used on the Due may not be able to keep up at high baud rates. That has nothing to do with what the SAM3X8E can do, just what the interface to your PC is capable of. You can replace that with an external USB to UART interface if you want, such as an FT232R based interface. That is if it's communication with your PC that you're concerned about, in which case you would be better with the native USB interface as it's not restricted by whatever external hardware is added.


message:
Serial Communication between ESP8266 and Arduino ( Sofware and Hardware )

I wish to connect an Arduino ( any of 328P family ) which its 5v, with ESP8266 (ESP-01, or even NodeMCU or Wemos D1 mini ) which is 3v3 logic. My goal is that ESP8266 will be in-charge of MQTT messages and other remote abilities, while Arduino board will be in charge of UP/Off/Down rocker switch and 2 relays ( For reliability I rather have this setup ). **Both MCU's code is written by me using Arduino**

I Know of 2 main ways: voltage divider and level shifter ( and 3rd will be to use a 3v3 logic as pro-mini - but let's leave for now ).

My questions are:

A) Does `Rx` `Tx` need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?

B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

C) Does `SofwareSerial` library is recommended (again - reliability ).

body:
> A) Does Rx Tx need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?

The point is, that often 3.3V MCUs cannot tolerate voltages significantly above that. So connecting 5V can hurt it. I've seen quite a bit of discussion online, if ESP boards are 5V tolerant or not, but I haven't seen a real investigation in this. Often you can very well get away with connecting them directly, but nobody will give you any guarantees about this. If you want to be safe, you need to add some kind of voltage transition from Arduino TX to ESP RX. The other line (ESP TX to arduino RX) is driven by the ESP with 3.3V, which is ok for the Arduino (3.3V is enough for the Arduino to see it as HIGH), so you don't need anything on this line.

> B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

Since a voltage divider is passive, you get extra effects (parasitic capacitance and inductance), which limits the baudrate. Though I still got communication without errors with baudrates up to 115200 (I did not do a thorough investigation, this is just subjective experience). Electronically better would be proper level shifting (which uses transistors), but in most cases a voltage divider also works well. So I would say unless you want to use really high baudrates you are good with a voltage divider. Others can of course also provide their experience on this site.

> Does SofwareSerial library is recommended (again - reliability ).

Generally a Hardware Serial interface is always better, since the communication protocol is completely handled in hardware. The code just needs to read and write the individual bytes from/to hardware registers. `SoftwareSerial` is used, when there is no free to use Hardware Serial interface. And it imposes some extra limits: You can only listen to one `SoftwareSerial` interface at any give time and you cannot use high baudrates with it (I think 115200 is already too high for it, depending on the used Arduino). Also it depends on the rest of your code (depends on your use of ISRs). So, if you have an unused hardware Serial interface on your Arduino board, you should use that. Otherwise you can use `SoftwareSerial`.