message:
Large(ish) strings failing to send over WiFi101 using WiFiServer

I've based a sketch off the vanilla WiFi101 server examples.

If I define a const char array like this:

    const char HTML_index[] = "test";

The server works well.  However if I increase the char[] size to about 1,300 bytes the server fails to send a response.  The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response.  The device and laptop (client) are both on the same WiFi AP so nothing weird there.

First I thought this was a memory issues, but as I'm using newer architecture and IDE using `const` *should* ensure the string is in FLASH.

So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205

But again not sure how applicable this is to an ARM based system/ WiFi101 library.

Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses?  How could I go about debugging this situation?

Edit:
This is the example sketch my code is based off:
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do.  I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET_BUFFER_UDP_SIZE.  So I looked through the WiFi101 src and found this:

    #ifdef LIMITED_RAM_DEVICE
    #define SOCKET_BUFFER_SIZE 64
    #else
    #define SOCKET_BUFFER_SIZE 1472
    #endif

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp

It's likely that my string was actually over 1472 bytes so this makes sense.

Edit3:
Found more references:

https://github.com/arduino-libraries/ArduinoHttpClient/issues/14

https://github.com/arduino-libraries/WiFi101/pull/116

So I take it the 1500 in WINC1500 could mean the buffer size.  Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.

body:
As per my notes the WINC1500 has a limit of 1500 bytes per transmission.  But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.

From:
http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500_at14596_applicationnote.pdf

> **2.2.2 TCP Packet Size**
>
> A packet is sized as per the lowest MTU (Maximum
> Transmission Unit) on the path, which is typically 1500 bytes (for
> Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes).
> The packet size is defined in main.h as :

    #define MAIN_WIFI_M2M_BUFFER_SIZE 1460

>The application then defines a socket buffer of this size in main.c as:

    static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.

FYI chunked Transfer-Encoding is superseded in HTTP/2:
http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html

Info on HTTP chunked encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

    Transfer-Encoding: chunked

> Data is sent in a series of chunks. The Content-Length header is
> omitted in this case and at the beginning of each chunk you need to
> add the length of the current chunk in hexadecimal format, followed by
> '\r\n' and then the chunk itself, followed by another '\r\n'. The
> terminating chunk is a regular chunk, with the exception that its
> length is zero. It is followed by the trailer, which consists of a
> (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/

https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

> **Transfer-Encoding**
>
> The use of Transfer-Encoding: chunked is what allows streaming within
> a single request or response. This means that the data is transmitted
> in a chunked manner, and does not impact the representation of the
> content.
>
> Officially an HTTP client is meant to send a request with a TE header
> field that specifies what kinds of transfer encodings the client is
> willing to accept. This is not always sent, however most servers
> assume that clients can process chunked encodings.
>
> The chunked transfer encoding makes better use of persistent TCP
> connections, which HTTP 1.1 assumes to be true by default.
>
> Chunked data is represented in this manner:

    4\r\n
    Wiki\r\n
    5\r\n
    pedia\r\n
    e\r\n
     in\r\n\r\nchunks.\r\n
    0\r\n
    \r\n

> Each chunk starts with its byte length expressed as a hexadecimal
> number followed by optional parameters (chunk extension) and a
> terminating CRLF sequence, followed by the chunk data. The final chunk
> is terminated by a CRLF sequence.
>
> Chunk extensions can be used to indicate a message digest or an
> estimated progress. They are just custom metadata that your layer 7
> receiver needs to parse. There's no standardised format for it.
> Because of this, it's probably better to just add your metadata (if
> any) into the chunk itself for your layer 7.5 application to parse.
>
> For your application to send out chunked data, you must first send out
> the Transfer-Encoding header, and then you must flush content in
> chunks according to the chunk format. If you don't have an appropriate
> HTTP server that handles this, then you need to implement the syntax
> generator yourself. Sometimes you can use a library to provide an
> abstract interface.

Possible fix on Arduino platforms is to use [StreamLib][1] library or roll-your-own chunking system.

**Update:**  I hacked together a sketch and confirmed this works.  Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.

  [1]: https://github.com/jandrassy/StreamLib


sender: user

message:
How to parse multi line serial data with an unknown number of lines?

Here's the example data I've read in H-Term:

    \r\n
    \r\n
    NO:0015\r\n
    G:   5.97kg\r\n
    T:   0.00kg\r\n
    N:   5.97kg\r\n
    \r\n
    \r\n

How to save the number including "kg" to each variable (NO, G, T, N)?

sender: assistant

body:
This is an overly broad question which borders "write me the code" - this isn't a coding service - and if anything belongs on StackOverflow since it regards processing.  That being said, this question would be flagging as overly broad there too.

I'm providing an answer because I believe it may help others here as it speaks to some fundamental programming concepts.  This is not a perfect solution by any means, for example it doesn't take program size into account. See the end of the post for a sketch.

There are two main problems you face:

 1. Model the input data
 2. Process the data

Modeling the input data means structuring your expected input in a meaningful way.  Looking at the input data provided, I see this format

 - 0-N chars indicate some metadata delimited by a colon (:)
 - 0-N white space
 - 0-N digits with optional decimal point (0015,5.97)
 - 0-N unit designation (kg)
 - data is delimited with a CRLF (\r\n)

Now think of each line as a **packet** of information.  In that sense, let's create some data structures that describe the data of the packet.

    // Types
    typedef enum {
      NoType,
      NO,
      G,
      T,
      N,
    } Type;

    // Units
    typedef enum {
      NoUnit,
      uKg, // kilogram
      uG,  // gram
    } Unit;

    // Values - unions are handy to model variants.
    typedef union {
      char str[5];
      float dval;
    } Value;

Given the basics above, let's model a Packet:

    // the data model for a CRLF delimited packet
    typedef struct {
      Type type;
      Value value;
      Unit unit;
      byte valid;
      // metadata
      byte expectUnit; // 1 if a Value has a Unit; 0 otherwise.

    } Packet;

OK, so that's a basic model of the input data.  How to process?  Always break down big problems to the smaller, manageable units to provide a solution.

Now there's a huge number of possibilities to parse/interpret your data packets.  I am providing a bare bones, brute force approach that you may learn from, and hopefully improve upon.  For example I am not providing much in the way of array overruns which can crash a program.

Here's the main processing function, which takes a string of input data (a line) and produces a Packet.  In all I am only going to provide for the Type 'G' and leave the rest to you.

    // readPacket processes the input string pszBuffer and fills pPacket accordingly.
    //
    // pszBuffer should be a string of characters delimited by \r\n.
    // pPacket is a pointer to a Packet which is filled by this function.
    //
    // returns 1 if packet is valid, 0 otherwise.
    byte readPacket(Packet* pPacket, const char* pszBuffer) {
      byte isvalid = 0;
      if (pszBuffer && pPacket) {
        char tmp[10];
        char* psz = (char*)pszBuffer;
        char* pszTmp = 0;
        byte len = 0;
        // initialize packet
        pPacket->type = Type::NoType;
        pPacket->unit = Unit::NoUnit;
        pPacket->valid = 0;
        pPacket->expectUnit = 0;
        // get the Type
        psz = processType(pPacket, psz);
        if (psz) {
          // skip any space characters now.
          psz = trimLeadingSpaces(psz);
          psz = processValue(pPacket, psz);
          // if Type handled, check units and finish.
          if (psz) {
            if (pPacket->expectUnit)
              pPacket->valid = processUnit(pPacket, psz);
            else
              pPacket->valid = 1;
          }

        } // Type not found

        isvalid = pPacket->valid;
      }
      return isvalid;
    }

OK that's not a lot.  The logic is

 - Get the packet Type
 - IFF a packet Type was found, get the packet Value
 - IFF a value was found, get the Unit if required

It's important to breakdown these steps in smaller, manageable functions.  First, the code for getting the packet Type.

    // processType
    // Sets pPacket->type to the type found in psz.  Type is delimited by a colon (:)
    // Returns 0 (null) if a known Type wasn't found.
    // Otherwise a ptr to the data past colon delimiter.
    //
    char* processType(Packet* pPacket, const char* psz) {
      // find the colon (:) delimiter and return what it leads to.
      byte len = 0;

      char* ptr = strchr((char*)psz, ':');
      char* pResult = 0;
      if (ptr) {
        // found the colon.
        char buffer[4];
        byte len = (ptr - psz) / sizeof(char); // pointer math to find length.
        strncpy(buffer, psz, len);
        // null term buff
        buffer[len] = 0;
        // assume succcess; default will rest to fail.
        pResult = (char*)psz + len + 1; // +1 to skip colon character.
        switch (buffer[0]) {
        case 'G':
          pPacket->type = Type::G;
          pPacket->expectUnit = 1; // unit should be given.
          break;
        default:
          pPacket->type = Type::NoType;
          pResult = 0; // fail, didn't find a known type.
        }
      }

      return pResult;
    }

So processType sets up the packet Type and adds information about whether to look for Unit information later.

If processType() found a valid Type, the next step is to get the value based in that type with the function processValue

    // Sets pPacket->value according to the packet Type.
    // Returns null (0) if type not supported or value not found,
    // otherwise a pointer to the remaining characters following the value handled.
    char* processValue(Packet* pPacket, const char* psz) {
      char* ptr = 0;
      // value is construed by Type
      switch (pPacket->type) {
      case Type::G:
        ptr = processFloat(pPacket, psz);
        break;
        //
        // add your additonal Type implementations...
        //
      default:
        // invalid, set psz to null.
        ptr = 0;
      }
      return ptr;
    }

Great. Now, let's look at a way to get the value for a float:

    // Sets pPacket->value.dval
    // Returns 0 (null) if a value wasn't found.
    // Otherwise a ptr past the last character of the decimal value.
    char* processFloat(Packet* pPacket, const char* psz) {
      const char *float_chars = ".0123456789";
      char* ptr = (char*)psz;
      if (ptr) {
        // scan ptr until we don't find a match.
        byte index = 0;
        while (strchr(float_chars, (char)ptr[index]))
          index++;

        if (index) {
          //  get the float using a temporary buffer.
          //  dangerous! assuming this will not overrun!
          char buf[10];
          strncpy(buf, ptr, index);
          // null term buff
          buf[index] = 0;
          pPacket->value.dval = atof(buf);
          // advance ptr past the decimal characters for return valie.
          ptr += index;
        }
        else ptr = 0; // fail
      }
      return ptr;
    }

Finally if all went well, the code should look for the Unit if expected (based on the Type)

    // Sets pPacket->unit to the unit given in psz.
    // Returns 0 if no unit was found, non-zero otherwise.
    byte processUnit(Packet* pPacket, const char* psz) {
      pPacket->unit =  Unit::NoUnit;
      if (psz) {
        switch ((char)*psz) {
        case 'k':
          pPacket->unit = Unit::uKg;
          break;
        case 'g':
          pPacket->unit = Unit::uG;
          break;
        default:
          break; // unit initialized to NoUnit.
        }
      }
      return pPacket->unit != Unit::NoUnit;
    }

Here's a [GIST](https://gist.github.com/TennesseeJed/980dbc68aa2e0002399e35c81ef8c0eb) of an arduino sketch using the code above.

Good luck, hope this helps.  In the future, pose questions regarding processing on StackOverflow.


message:
Connect SD card to Arduino with or without a level shifter

I have some audio files in an SD card and I want to play them using Arduino, thus connect the SD card to the Arduino. Since the transfer of the data will be from the SD card (+3.3V) to the Arduino (+5.0V) and not vice versa, is a level shifter necessary?

body: You can't use SD card without level conversion from 5 V to 3.3 V. Clock and CS line are driven by the master, and the master must request over MOSI the data to read.


body: i have a cheap generic chinese off-brand sd Card module and it does not even work if i do connect vcc to 3v3 so i use it with 5v. and i do not bother to add a Level shifter on the bus lines. and writing text to a file on the sd Card does work like a charm this way. so i would say no you not neccesarily Need the Level shifter but feel free to add it anyway and see if it works this way too.


message:
How to use millis instead of delay on Arduino for independent time intervals for two output pins

I wanted to use millis for the code below but stuck in between . can anyone help to change the given code to millis? Code here:

        void set(){
        digitalWrite(on, HIGH);   // turn the motor on (HIGH is the voltage level)
      delay(1500);
      digitalWrite(on, LOW);
      delay(ont);               //waits for given time
      digitalWrite(off, HIGH );    // stop the motor
      delay(500);
      digitalWrite(off, LOW );
      delay(offt);                  //wait for different

body:
Here is the code for changing pin value without delay. Read it and try it.

```
#define on 2
#define off 3

//delay times
const unsigned int ont = {1500,  500};
const unsigned int offt = {500, 300};

//last millis
unsigned long last_tm_on = 0;
unsigned long last_tm_off = 0;

//position
byte pos_on = 0;
byte pos_off = 0;

void setup(){
  pinMode(on, OUTPUT);
  pinMode(off, OUTPUT);
}

void loop(){
  if(millis() - last_tm_on >= ont[pos_on]){   //check if millis() - last millis() is bigger than wanted time
   last_tm_on = millis();   //save last millis()
      if(pos_on == 0) digitalWrite(on, HIGH);
      if(pos_on == 1) digitalWrite(on, LOW);

      pos_on ++;   //add position
      if(pos_on > 1) pos_on = 0;   //check max position
  }

 if(millis() - last_tm_off >= offt[pos_off]){
   last_tm_off = millis();
      if(pos_off == 0) digitalWrite(off, HIGH);   // turn the motor on (HIGH is the voltage level)
      if(pos_off == 1) digitalWrite(off, LOW);

      pos_off ++;
      if(pos_off > 1) pos_off = 0;
  }
}
 ```


message:
please help with my arduino

My problem is when I run code like this:

    char directioN;

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

    void loop()
    {
      if (Serial.available())
      {
        directioN = Serial.read();

        switch (directioN)
        {
          case 'F':
            break;

          case 'B':
            break;

          case 'R':
            break;

          case 'L':
            break;

          default :
            break;
        }

        Serial.print("direction is:");
        Serial.println(directioN);
      }
    }

My serial monitor add another input, but the second one is empty; this happened here with char both as with int.

But when i tried the same code in tinkercad it worked fine.

So do I really need a new ATMEGA328 or it can be done by software or something?

**I use an Arduino Uno

body:
So why you don't just ignore it?
```
if(directionN >= 32){   //check if char is readable ascii character
  Serial.print("direction is:");
  Serial.println(directioN);
}
```


message:
How to use power led from arduino-pro-micro?

In my project I need 3 leds. I would like to use on-board leds if possible.

I know how to use `PB0` and `PD5` red on-board leds, and I would like to hack the board somehow to use the green power led.

If I do not find a way to use the power led from MCU, I'm planning to destroy it anyway, because it is constantly on, which is harmful in my project.

body: There are 34-pin atmega32u4-based boards. They have 3 leds. So use them instead of pro-micro board.


message:
How can I reduce current drawn by micro SD card module?

I am using a servo along with a sensor and micro SD card module and speaker in arduino uno in order to play a wav file at certain conditions . But when i run the whole system the sd card module is consuming high current and the servo stops working as the current in that is in order of some micro amps. So please help me to solve the problem.

body: Don't try to drive all of that from the Arduino regulator. The answer is to get a higher current power supply. You might even need to add filter capacitors on the 5V rails "right in front" of your different systems to protect them from voltage drops when other systems suddenly draw large amounts of current from the 5V rail.


body: another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...


message:
Passing non-static member function using bind

I'm using the [GxEPD2 library][1] to communicate with an E-Paper display. I now wanted to use the `drawPaged` method of this library with an object `display`.

I also have written my own class from which I want to print stuff on the display.

Here's the relevant code for the MyClass.h:
```
class MyClass{
    //some variables and methods
    void drawClass(); //this is public
    void drawClassCallback(const void* v1); //this is private
    //    this is actually a uint8_t --^
}
```
And here's the MyClass.cpp:
```
void MyClass::drawClass(){
    //some display preparation
    uint8_t var; //A variable to pass information from the callback to this method since it is needed later
    display.drawPaged(std::bind(&MyClass::drawClassCallback, this, &var));
    //some code where I need var with info from the callback
}
```
I'm getting the following error:

> no matching function for call to 'GxEPD2_BW<GxEPD2_290, 296u>::drawPaged(std::_Bind_helper<false, void (MyClass::*)(const void*), MyClass*, unsigned char*>::type)'

> note: candidate: void GxEPD2_BW<GxEPD2_Type, page_height>::drawPaged(void (*)(const void*), const void*) [with GxEPD2_Type = GxEPD2_290; short unsigned int page_height = 296u]
     void drawPaged(void (*drawCallback)(const void*), const void* pv)

I've also tried `display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var)` without success.

I've stumbled upon [this post][2] already, however the solution presented there (and the one used above) does not work in this case.

Why is that?

  [1]: https://github.com/ZinggJM/GxEPD2/tree/master/src
  [2]: https://arduino.stackexchange.com/questions/56026/how-to-pass-non-static-class-member-to-callback

body:
In your `MyClass` example, the `drawPaged()` call is given only a single argument, while according to the library, it needs two:

```cpp
void drawPaged(void (*drawCallback)(const void*), const void* pv)
```

The first argument is the function pointer (or the one wrapped by `std::bind`!). The second argument seems to be some data that will be passed on to that function. (according to the [linked API)

The error actually explains it, it suspects that you are trying to call `void GxEPD2_BW::drawPaged(void ()(const void), const void*)`. Hence it mentions this as a candidate.

What you need to do is something like this:

```cpp
display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var);
```

`std::placeholders::_1` is the placeholder that represents the `var` argument that will be passed on when it is called.


message:
How to trigger NodeMCU sketch from Arduino Leonardo Micro Pro?

So this is probably a very simple question. I have my NodeMCU set up and working where it connects to wifi and sends a push notification. Currently it does that automatically when connected to power.

What I want to do is connect it to my Leonardo Micro so that at a part in the Leonardo sketch it sends a signal to the NodeMCU to run the sketch to trigger the push notification. So simply, which ports should I connect and what code should I change.

Here is my working NodeMCU code.

        #include <ESP8266WiFi.h>

    // Wifi Settings
    const char* ssid = "MySSID";
    const char* password = "MyPassword";
    // Pushover settings
    char pushoversite[] = "api.pushover.net";
    char apitoken[] = "MyAPIToken";
    char userkey [] = "MyUserKey";
    int length;
    WiFiClient client;
    void setup() {
      Serial.begin(9600);
      delay(10);

      // Connect to WiFi network
      Serial.println();
      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");

      // Print the IP address
      Serial.print(WiFi.localIP());

    }

    void loop()
    {
     pushover("OMG, Yes it works!!!");
     delay(60000);
    }

    byte pushover(char *pushovermessage)
    {
     String message = pushovermessage;

     length = 81 + message.length();

    if(client.connect(pushoversite,80))
     {
       client.println("POST /1/messages.json HTTP/1.1");
       client.println("Host: api.pushover.net");
       client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
       client.print("Content-Length: ");
       client.print(length);
       client.println("\r\n");;
       client.print("token=");
       client.print(apitoken);
       client.print("&user=");
       client.print(userkey);
       client.print("&message=");
       client.print(message);
       while(client.connected())
       {
         while(client.available())
         {
           char ch = client.read();
           Serial.write(ch);
         }
       }
       client.stop();
     }
    }

And my Leonardo code

    #include <Keyboard.h>
    #include <Mouse.h>
    char returnKey = KEY_RETURN;
    char tabKey = KEY_TAB;
    void setup() {
      Keyboard.begin();
      Mouse.begin();

      delay(4000); //Testing Delay
    // Language Select Screen
      Keyboard.write(returnKey);
      delay(30000);
    // Welcome Screen
      Mouse.click(MOUSE_LEFT);
      delay(100);
      Keyboard.write(tabKey);
      delay(100);
      Keyboard.write(tabKey);
      delay(100);
      Keyboard.write(' ');
      delay(2000);
    // Select Keyboard
      Keyboard.write(tabKey);
      delay(100);
      Keyboard.write(tabKey);
      delay(100);
      Keyboard.write(tabKey);
      delay(100);
      Keyboard.write(' ');
      delay(2000);
      TELL NODEMCU TO SEND PUSH NOTIFICATION HERE
    }

    void loop() {
    }

As a reminder the pinout on my boards are as follows.

Leonardo:

[![Leonardo Layout][1]][1]

NodeMCU:

[![NodeMCU Layout][2]][2]

  [1]: https://i.stack.imgur.com/gHG41.png
  [2]: https://i.stack.imgur.com/CZAlD.png

body:
**HW part:**

It's like button, simply connect arduino micro pin to nodeMCU pin and GND of arduino to GND of nodeMCU.

It's also good idea to use two resistors as voltage divider because arduino micro works with 5V and ESP8266 (nodeMCU) with 3V3. 5V can destroy ESP8266 but this thing is still not really clear.
Resistor divider connect as in this link [link about resistor divider for uart][1] but instead of TX put arduino micro and instead of RX nodeMCU.
[resistor divider schematic][2]

-----------

**Code part:**

On the **arduino micro part** use:

 - In `void setup()`:
`pinMode(PIN, OUTPUT);`

 - In your marked place:
```
digitalWrite(PIN, HIGH);
delay(100);   //short wait time
digitalWrite(PIN, LOW);
```

**nodeMCU part:**

 - In `void setup()`:
`pinMode(PIN, INPUT);`

 - Remove everything from `void loop()` and put there this:
```
if(digitalRead(PIN) == 1) pushover("OMG, Yes it works!!!");
```

In both codes select the `PIN` according to your choice.

  [1]: https://www.avrfreaks.net/forum/how-connect-5v-avr-mcu-uart-33v-uart
  [2]: http://cdn.instructables.com/FMS/V245/H0OJ17O9/FMSV245H0OJ17O9.LARGE.jpg


message:
firebase arduino uno + esp8266

I am trying to make a project that can read data from usbsheild connected to arduino uno board then send them to firebase through esp8266.
But the libraries of firebase and esp8266wifi that i found are not for arduino uno but for the esp8266 board can anyone help me in this problem ?

body:
**The best way you can do is connect it to a web and then use firebase-php library**

> https://github.com/ktamas77/firebase-php/blob/master/README.md

*insert this*

**Follow this as your guide**

> https://stilllot2learn.wordpress.com/2017/11/18/arduino_gps_gsm/comment-page-1/#comment-47

**Don't forget to create your FIREBASE ACCOUNT**

> look for **database secret** as your TOKEN under User and Permissions
> TAB


message:
Trying to understand Classes

I have searched about class and int but I still don't understand.

I have seen this code online I want to understand it

    class Motor {

      int enablePin;
      int directionPin1;
      int directionPin2;
      public:

      //Method to define the motor pins
      Motor(int ENPin,int dPin1,int dPin2){
        enablePin = ENPin;
        directionPin1 = dPin1;
        directionPin2 = dPin2;
    };

body:
    class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.

      int enablePin;
      int directionPin1;
      int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (`enablePin`, etc.) Since not otherwise specified, these variables are *private*, meaning that only other functions **in** the class can access them. Other parts of the program are not allowed to access these variables.

    public:

This means that the following definitions *are* accessible by parts of the program that exist outside the class.

    Motor(int ENPin,int dPin1,int dPin2) {
      enablePin = ENPin;
      directionPin1 = dPin1;
      directionPin2 = dPin2;
    }

This defines the only "member function" in this class and because it shares the same name as the class (`Motor`), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class `Motor` by `myMotor = Motor(1, 2, 3);`, the constructor is called with parameters `1`, `2`, and `3`. This constructor happens to just set the private variables to be the same as the arguments passed in.

But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.

The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.


message:
Power Arduino Mega ESP85266

Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

What would be the best solution?

 - Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)
 - Is a Power Converter like [this][1] for the ESP8266 necessary?
 - Should i use another external Power source for the ESP8266?

Thanks for any Help :)

  [1]: https://www.amazon.com/eBoot-MP1584EN-Converter-Adjustable-Module/dp/B01MQGMOKI/ref=cm_cr_arp_d_product_top?ie=UTF8

body:
> Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

Yes. Assuming the "block" can provide enough current.

> Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)

No.

> Is a Power Converter like this for the ESP8266 necessary?

Yes if you are powering it from more than 3.3V.

> Should I use another external Power source for the ESP8266?

Not necessary if the 9V one can provide enough current as I mentioned above.


message:
ATmega 32A and 2560 R3 register to pin mapping?

I've been doing research for the last few hours trying to determine the mapping of physical pins to memory-mapped I/O registers for the Arduino Mega board (which is an ATmega 2560 R3).

 - [My code is on GitHub](https://github.com/naftulikay/vw-cdc-emulator/pull/2) in a pull request, but hasn't been merged yet because I'm not finished yet.
 - [This](https://gist.github.com/naftulikay/ddad3abe90310da2d4769531a92f0dcc#file-vag_cdc-c) is the upstream example [I'm working from](http://schuett.io/2013/09/avr-raspberry-pi-vw-beta-vag-cdc-faker/), which was written for an ATmega 32A.
 - [Here is Arduino's 2560 pin mapping](https://www.arduino.cc/en/Hacking/PinMapping2560) which doesn't tell which registers are mapped to which pins.
 - [Here is `avr/iomxx0_1.h`](https://gist.github.com/naftulikay/9e881057b9c1b389ca7dc4a0dcbed76a) which defines the ports with simple numbers that I can't make heads or tails of.
 - [Here is a collection of links](https://github.com/naftulikay/vw-cdc-emulator/wiki/Arduino-Mega-2560-R3-Documentation) relevant to my research.
 - I [broke down and cross-referenced](https://github.com/naftulikay/vw-cdc-emulator/wiki/Upstream-Example) all of the uses of memory-mapped I/O registers in the upstream example.

Some of the registers used include `CS11`, `DDB4`, `DDRA`, `DDRB`, `GICR`, `INT0`, `INT1`, `ISC00`, `ISC10`, `MCUCR`, `PA0`, `PB5`, `PB7`, `PD2`, `PD3`, `PIND`, `PORTA`, `PORTD`, `SPCR`, `SPDR`, `SPIF`, `SPSR`, `TCCR1B`, and `TCNT1`. I can't figure out which pins these are and/or what they do.

Here is a diagram provided by the upstream example:

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

Unfortunately, I'm not very good at reading these diagrams so I'm doing my best.

How can I determine the mapping of these registers to physical ports on both the ATmega 32A, which is the board the example was originally written for, and the ATmega 2560 R3, which is the board I'm currently working with?

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

body:
What is ATmega2560 R3? There is ATmega2560 MCU or Arduino Mega R3. do you want the mapping of pins of Arduino Mega or the pins of the ATmega2560 MCU.

The mapping of pins of the ATmega 2560 chip is in the [datasheet][1].

The mapping of the Arduino Mega pins to ATmega2560 pins and registers is in [the schema of the board][2] or in the Arduino AVR boards package variants [mega folder][3].

The link "Arduino's 2560 pin mapping" in your question shows the mapping too. Registers are PA, PB,... and every register covers to 8 pins with the 8 bits of the register. For example PB3 is pin 50 of the board.

  [1]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf
  [2]: https://content.arduino.cc/assets/MEGA2560_Rev3e_sch.pdf
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/master/variants/mega/pins_arduino.h


body:
Atmega32A is a 44 pin TQFP part with 4 8-bit IO ports.
It is kind of a crippled Atmega1284P. You may have an easier time just switching to a 1284P chip (also 44 pin TQFP) to take advantage of its 16K byte SRAM and 128K byte flash. There's an easy to use add-in to the Arduino IDE to use it.
https://github.com/MCUdude/MightyCore
I do a lot of 1284P designs and use it all the time.

Atmega2560 is 100 pin TQFP part with 10 8-bit and one 6-bit IO ports.

As your schematic only uses a few IO pins, the electrical connections will be simple - SPI for bootloading or downloading code
- 2 pins for serial
- 2 pins for other IO

If you look at the Arduino Mega2560 schematic, you can pick those out pretty readily.  The rest you will have to tweak up in your code.


message:
AVR software reset without watchdog

I wrote a generic avr program wrapper which already use the watchdog timer to restart - and after the watchdog reset - recover the the bad situation.

After this recover process i have to restart the avr. Everything i've found in topic "software reset arduino" is about to set the shortest watchdog (15ms) timeout, then spins the CPU (for(;;);) until it cause watchdog reset.

But this results to enter the recovery process which is already done in this point.

It is any elegant way to achieve this?

Some non or less elegant way:

- I can bind a digital pin to the reset and pull up with a resistor.

- I can write to a fixed address in the flash or eeprom (but this maybe happens frequently) before soft restart, to prevent entering to recovery mode.

---
Is there any register that "survives" soft resets?

Edit:

I add mock example code to hint what i trying to do.

In the actual code, in the recovering the microcontroller connect to the serial bus, waits for commands then resets itselft in oder to return to application mode.

    /*************************** Application wrapper ******************************/

    //define call_application and call_recover as weak empty functions
    //so they can be rewritten.

    bool isWatchdogReset()
    {
     return MCUSR == 8;
    }

    void softwareReset()
    {
     // wdt_enable(WDTO_15MS);for(;;);// (this way enters recovery mode)
     //or
     // asm ("jmp 0x0");// (this way function registers not being resetted)
    }

    bool isSoftwareReset()
    {
     //???
    }

    int main()
    {
     bool needRecover = isWatchdogReset() && !isSoftwareReset();
     MCUSR = 0;
     init_board();
     wdt_enable(WDTO_1S);
     while(1)
     {
      if(!needRecover)
      {
       call_application();
      }
      else
      {
       call_recover();
      }
      wdt_reset();
     }
    }

    /********************************* Application ********************************/

    void call_application()
    {
     if(randomTrue())
     {
      //stuck more that 1 secounds, that results WDT reset
     }
     else
     {
      //proper operation
     }
    }

    /********************************** Recover ***********************************/

    void call_recover()
    {
     //initialize UART, attach interrupts, Write flash and EEPROM, modify
     //function registers.

     //recovering completed, returning to the original application as like
     //nothing's happened.
     softwareReset();
    }

**Edit:**
I try explain short to spot the point:

1) I already use the watchdog timer to detect when the application code is flawed.

2) soft reset is an inproper solution, because it doesn't reset the registers. So onyl the program will be resetted, the state of the microcontroller doesn't.

3) To commit a proper reset, the solution is to timeout the watchdog timer. But see point 1), it is already used, so how can you make the difference of a requested reset and a flawed code recovery reset?

body:
The reset is basically jumping to the reset vector address `0x0000` (if you don't have the bootloader, or you don't want to start it).

There is also the `MCUSR` register, indicating which reset source caused the reset. It won't be set if you do simple jump to the reset adress.

The memory is also preserved, but C/C++ init code takes place and initialize your global variables. This can be ommited by placing variable/variables into the `.noinit` section. But it's not defined, what is there after the reset. With combination with `MCUSR` register you can init the variables for regular reset sources and keep it unchanged if you jump to the reset vector address.

Also the regular reset sources jumps to the bootloader, so it can use the same memory locations as your `.noinit` variables and trash them.


body:
The logic of you applications is wrong. You set the `needRecover` at the beginning of `main`, but test it in your infinite `while (1)` loop. **The `needRecover` value will not change in the loop.**

Do your initialization first no matter if normal power-up or watchdog restart and then do stuff in the infinite loop.

You could put the initialization in a function called `setup` and the infinite loop in a function called `loop`. And have a `main` function like this:

    int main( void )
    {
      setup();

      for (;;)
      {
        loop();
      }

      return 0;
    }

wait, a saw this somewhere already :-)


message:
What is the voltage between Vin & GND?

I have NodeMCU ESP8266N Lolin V3, my 5V relay is powered from Vin of the NodeMCU.
The NodeMCU is powered from 5V USB.

My difficulty is when I measure voltage between Vin & GND, it is of 1.9V, but supposed to be around 5V as it is directly attached with usb 5V supply. Actually my relay is not working with the power tapped from Vin, but relay's led & NodeMCU  led are blinking but relay coil does not trip.
Please confirm is my NodeMCU having problems as voltage between vin & GND read 1.9V.
https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk
![enter image description here](https://i.stack.imgur.com/QIEqV.jpg)

body:
It is hard to tell from your pictures but I don't think you have your relay connected properly.

Some problems i see:

 - Your esp8266n seems to be a 3 Volt device; it has 3V output pins
 - Vin usually feeds a regulator; the +V rail is usually after it
 - Your relay needs 5V but you only have 3V for power and signal

You will need a level shifter, and another powersupply to run your relay. You should be able to put 5v into Vin on your ESP and have it be powered, then you will need a level shifter to connect to the IN1 or IN2 of the realy so that you can control it with 3v. And the relay Vcc and GND also connected to the same power supply.


body:
The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for

You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that

In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

[![Lolin v3 pinout][1]][1]

Use this pin to connect to JD-VCC on the relays

I've just now successfully done this with a 4 relay board

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

I would connect (nodemcu -> relay)

 - 3V3 to VCC
 - VU to JD-VCC
 - Gnd to Gnd
 - D*n* to IN*m* - i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay


message:
Where are the implementations of the SdFat BlockDriver methods?

This is most probably more of a C++ question than an Arduino question; but since this is an Arduino library, I am asking here.

 I am using the [SdFat][1] library for my project. The library defines a `BlockDriver` object in one of its [header][2] file which only declares the `typedef` of `BaseDriver` to some other classes.

```c++
#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef BaseBlockDriver BlockDriver;
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef SdSpiCard BlockDriver;
#endif  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
#endif // BlockDriver_h
```

`typedef SdSpiCard BlockDriver;` makes sense to me. But if `ENABLE_EXTENDED_TRANSFER_CLASS` or `ENABLE_SDIO_CLASS` are defined, `BlockDriver` is typedeffed into `BaseBlockDriver`. `BaseBlockDriver` is an abstract base class (as defined [here][3]). An instance of the `BlockDriver` object is later used directly in the `FatVolume` class [here][4].

**My question is, how does `BlockDriver`'s method get defined when it abstract base class `BaseBlockDriver` is typedeffed to `BlockDriver`?**

  [1]: https://github.com/greiman/SdFat
  [2]: https://github.com/greiman/SdFat/blob/master/src/BlockDriver.h
  [3]: https://github.com/greiman/SdFat/blob/master/src/FatLib/BaseBlockDriver.h
  [4]: https://github.com/greiman/SdFat/blob/635d3fd50f932a6dbac9a3d5baae97d1bdf2d0fc/src/FatLib/FatVolume.h#L270

body:
The typedef in BlockDriver.h is only for pointer type, not for instance of the object. The object is always of type `SdSpiCard`, but in one case it is not an implementation of BlockDriverBase, so the function parameters can't refer it by base type.

    #if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
    class SdSpiCard : public BaseBlockDriver {
    #else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
    class SdSpiCard {

use of BlockDriver typedef

    class FatFileSystem : public  FatVolume {
     public:
      bool begin(BlockDriver* blockDev, uint8_t part = 0) {

I was curious why the version without BaseBlockDriver. I asked the author Bill Greiman and he [answered][1]:

> This is due to history. Long ago using a virtual base class cost lots
> of RAM and flash so I did this mainly for 328 boards

  [1]: https://github.com/greiman/SdFat/issues/128


message:
give a class's function name as a parameter

I'm trying code using `FastLed` library to have a 3 state ( color or brightness ) led strip, using a physical input switch, while each press will change leds color, using a predefined list.

code below demonstrate  1) create a `colorPallete` of two colors 2) try to use it in `loop` with no success.

    #include <FastLED.h>

    // How many leds in your strip?
    #define NUM_LEDS 1

    // For led chips like Neopixels, which have a data line, ground, and power, you just
    // need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
    // ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
    #define DATA_PIN 3
    //#define CLOCK_PIN 13

    // Define the array of leds
    CRGB leds[NUM_LEDS];
    int colorSelctor = 0;
    int birughtSelector = 25;
    int inputPin = 13;
    char *colorPallete[2] = {"Red","Blue"};

    void setup() {
      // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      pinMode(inputPin, INPUT_PULLUP);
    }

    void loop() {
      // Turn the LED on, then pause
      leds[0] = CRGB::colorPallete[0];
      FastLED.show();
      delay(500);
      // Now turn the LED off, then pause
      leds[0] = CRGB::Black;
      FastLED.show();
      delay(500);
    }

body:
`CRGB::Red`, etc, are just numbers. You need to treat them as such.

    uint32_t colorPallette[2] = { CRGB::Red, CRGB::Blue };

And then:

    leds[0] = colorPallete[0];

From `pixeltypes.h`:

    /// Predefined RGB colors
    typedef enum {
        AliceBlue=0xF0F8FF,
        Amethyst=0x9966CC,
        AntiqueWhite=0xFAEBD7,
        Aqua=0x00FFFF,
        Aquamarine=0x7FFFD4,
        Azure=0xF0FFFF,
        Beige=0xF5F5DC,
        Bisque=0xFFE4C4,
        Black=0x000000,
          ... etc ...
    } HTMLColorCode;


message:
Arduino Power project question?

I saw a project on the Internet (the one in the photo), and I wonder, would it be a problem for me to connect the Vin and GND of the Arduino to the same place where the Servo Motors are being powered? (to power the Arduino together without having to connect it to another source or USB)

And if instead of the batteries I use one of those Breadboard Power Module (photo two) and connect a 12V / 1A power supply in it, would it have problem ? (connect the 4 Servo + the Arduino in it)

[![project][1]][1]

[![Breadboard Power Module][2]][2]

  [1]: https://i.stack.imgur.com/QkZEW.png
  [2]: https://i.stack.imgur.com/03xpt.png

body:
Please provide more information about the power module, or at least a link to it.

But you could supply 12v directly to the Arduino's DC-In barrel-jack. It's not ideal; the Arduino's regulator is likely to get warm, but it would work. This module looks like it regulates its input down to 5v or 3.3v (jumper-selectable). If that is so, then its 5v output would be just right for the Arduino's 5v-In pin. Just make sure your the motors and the Arduino are each directly connected to whatever supply(s) you use. What you need to avoid is trying to power the motors *through* the Arduino. Your first photo has it right.

Update:

After reading about the supply (using your link), I see that its output is limited to 700ma. Some of that will have to go to power the Arduino (you can use the power supply's USB port for that), leaving a little less for the motors. That will be marginal for one motor and insufficient if the motor is stalled or moving more than a trivial load. It won't be sufficient for more than one motor at a time without scheduling them to prevent simultaneous starts.

You haven't described your motors, so I looked up the Tower-Pro SG-90 hobby servos, one of the simplest and least expensive of the hobby servos. I found a [very similar looking one][1] (maybe a clone?) described as being similar to the Tower-Pro, the only one for which I could find current specs. At 5 volts, it draws 100mA with no load and 700ma when stalled. With a stalled motor, the output voltage would likely drop, possibly stopping and resetting the Arduino.

So bottom line is, this supply is marginal, even for one hobby servo in a mechanism that won't stall it. With a larger motor or a heavier load, I don't think it will do the job.

  [1]: https://www.addicore.com/FS90-Mini-Servo-p/113.htm


message:
How to declare a global variable in the .h file?

I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file.

The question is, is it possible to declare a variable in the .h file and make it global?

body:
.h file is included by the compilation *preprocessor* as text into the .c or .cpp file. It is included as if you would replace the `#include` *preprocessor instruction* with the content of the .h file. (The Arduino .ino file is converted to cpp file before *preprocessing*.)

After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable *definition* the variable is *defined* in this *object* file. If your .h file contained a variable *definition*, the it is also in this object file.

If two cpp files included the .h file with the *definition* of the variable, then the variable will be in two *object* files and the linker will exit with an error, because of two variables with the same name.
If only one cpp/ino files includes the variable *definition*, then it is OK. It is not a good practice, but sometimes a necessary compromise. ([example of it][1])

To have one global variable made accessible by a .h file, the variable should be only *declared* in the .h file and be *defined* in one cpp file. Usually it is a pair of .h and .cpp file with same name.

An example of global variable is `Serial`. It is a global object of type `HardwareSerial` *declared* in HardwareSerial.h as

` extern HardwareSerial Serial;`

and *defined* in HardwareSerial0.cpp as

`HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);`

Do you see the difference? The *declaration* has the keyword `extern` and the *definition* has in this case parameters for the constructor of the object. The *declaration* with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).

  [1]: https://arduino.stackexchange.com/questions/58358/how-to-avoid-multiple-definition-of-blynk-error/58359#58359


body:
You can declare the variable as a `static` variable inside an `inline` function, and then just call this function to get a reference to this variable. Example:

    inline int& getMyInteger()
    {
        static int x;
        return x;
    }

This definition can be in a header file, included into multiple `*.cpp` files, and any call to `getMyInteger` will return reference to the same object. You don't need any `extern`, nor to actually put the variable in any compilation unit as you would need with a simple namespace-scope variable. This trick just uses the linker's ability to de-duplicate `inline` functions.

See also: [static variables in an inlined function](https://stackoverflow.com/q/185624/673852) question on StackOverflow.


message:
5V DC Mini Water Pump with Arduino Mega 2560?

First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that  :(

I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?

I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.

Thanks if you read this far :)

body:
Welcome to arduino.stackexchange.com .

As motor is usually a high current load, controlling a switch to control the motor's power is the solution.

If you are not interested in h/w design just want to use a interface out of box you can use relay module like this [relay][1]. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.

see this [answer][2] for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

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

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.

Here is a possible schematic.

![schematic](https://i.stack.imgur.com/bcR5W.png)

Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.

node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.

Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic

Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

 - Ibe = (current gain at saturation)*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)

Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

 - Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

 - Vce(max)(max) > VL
 - Ice(max) > IL
 - Arduino digital pin max I > Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.

  [1]: https://www.amazon.com/KY-019-Relay-Module-Arduino-Pack/dp/B077S3VL25
  [2]: https://electronics.stackexchange.com/questions/64798/can-an-arduino-use-a-12-v-relay
  [3]: https://i.stack.imgur.com/1Jhcq.png


message:
Length of uint8_t* const array

I've an array of type uint8_t* const with 6 items, defined like this

    uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

Whereas each element in this array is `static uint8_t` defined like this

    static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
    static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
    static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
    static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
    static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
    static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

When I do

      Serial.print("size:");
      Serial.println(sizeof(neighbourSet));

I get `size:24`. I am expecting the size to be 6. could someone explain ?
I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.

        for (int i = 0; i < sizeof(neighbourSet); i++) {
             //do something for each PEER.
             delay(50);
        }

body:
[`sizeof()`][1] gives the number of bytes. You are looking for `membersof()`. It is often defined as:

    #define membersof(x) (sizeof(x) / sizeof(x[0]))

And in the example above:

    for (int i = 0; i < membersof(neighbourSet); i++) {
         //do something for each PEER.
         delay(50);
    }

For more practical C/C++ macro and type extensions please see the Cosa [Types.h][2] file.

  [1]: https://en.cppreference.com/w/cpp/language/sizeof
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Types.h#L165


message:
Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing

I have a complex sketch with Arduino Uno, Bluetooth Serial Com using altSoftSerial, serial com using SoftwareSerial and Serial communication with PC.

I want to move one stepper motor and stop it when a signal is received.
I use A4988 Pololu driver and NEMA 17 bipolar stepper motor.

This code is working fine.
      MyStepper.moveTo(position);
      MyStepper.runToPosition();

If I change the code to
      MyStepper.moveTo(position);
      MyStepper.run();
so that the running does not block my code the motor does nothing
Absolutely no movement.

The ground of the motor power supply is connected with the ground of Arduino. The motor is working fine with blocking movements.

body:
You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.

If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.

When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.

    stepperMotor.moveTo(3000);
    stepperMotor.runToPosition();
    // reaches destination

    stepperMotor.moveTo(3000);
    stepperMotor.run();
    // moves a single step

    stepperMotor.moveTo(3000);
    while (stepperMotor.distanceToGo > 0) {
    stepperMotor.run();
    }
    // reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:

    stepperMotor1.moveTo(5000);
    stepperMotor2.moveTo(3000);
    while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
    stepperMotor1.run();
    stepperMotor2.run();
    }
    // Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).


message:
expected unqualified-id before '.' token

//my coding

    #include<DHT.h>              // Including library for dht
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(14,15,16,17,18,19);
    #include<Timer.h>
    Timer t;
    #include <SoftwareSerial.h>
    SoftwareSerial Serial1(2, 3);

    #define dht_dpin 12
    #define heart 13

    DHT dht;

    char *api_key="0UXHCZ777V0PAWPW";     // Enter your Write API key from ThingSpeak
    static char postUrl[150];
    int humi,tem;
    void httpGet(String ip, String path, int port=80);

    void setup()
    {
     lcd.begin(16, 2);
     lcd.clear();
     lcd.print("   Humidity   ");
     lcd.setCursor(0,1);
     lcd.print("  Measurement ");
     delay(2000);
     lcd.clear();
     lcd.print("Circuit Digest ");
     lcd.setCursor(0,1);
     lcd.print("Welcomes You");
     delay(2000);
     Serial1.begin(9600);
     Serial.begin(9600);
     lcd.clear();
     lcd.print("WIFI Connecting");
     lcd.setCursor(0,1);
     lcd.print("Please wait....");
     Serial.println("Connecting Wifi....");
     connect_wifi("AT",1000);
     connect_wifi("AT+CWMODE=1",1000);
     connect_wifi("AT+CWQAP",1000);
     connect_wifi("AT+RST",5000);
     connect_wifi("AT+CWJAP=\"1st floor\",\"muda1884\"",10000);
     Serial.println("Wifi Connected");
     lcd.clear();
     lcd.print("WIFI Connected.");
     pinMode(heart, OUTPUT);
     delay(2000);
     t.oscillate(heart, 1000, LOW);
     t.every(20000, send2server);
    }

    void loop()
    {
    ***DHT.read11(dht_dpin);     error in this line***
      lcd.setCursor(0,0);
      lcd.print("Humidity");
     **humi=DHT.Humidity;**   error in this line

      lcd.print(humi);   // printing Humidity on LCD
      lcd.print(" %    ");
      lcd.setCursor(0,1);
      lcd.print("Temperature");
    **tem=DHT.Temperature;**  error in this line
      lcd.print(tem);   // Printing temperature on LCD
      lcd.write(1);
      lcd.print("C   ");
      delay(1000);
      t.update();
    }

    void send2server()
    {
      char tempStr[8];
      char humidStr[8];
      dtostrf(tem, 5, 3, tempStr);
      dtostrf(humi, 5, 3, humidStr);
      sprintf(postUrl, "update?api_key=%s&field1=%s&field2=%s",api_key,humidStr,tempStr);
      httpGet("api.thingspeak.com", postUrl, 80);
    }

    //GET https://api.thingspeak.com/update?api_key=0UXHCZ777V0PAWPW&field1=0
    void httpGet(String ip, String path, int port)
    {
      int resp;
      String atHttpGetCmd = "GET /"+path+" HTTP/1.0\r\n\r\n";
      //AT+CIPSTART="TCP","192.168.20.200",80
      String atTcpPortConnectCmd = "AT+CIPSTART=\"TCP\",\""+ip+"\","+port+"";
      connect_wifi(atTcpPortConnectCmd,1000);
      int len = atHttpGetCmd.length();
      String atSendCmd = "AT+CIPSEND=";
      atSendCmd+=len;
      connect_wifi(atSendCmd,1000);
      connect_wifi(atHttpGetCmd,1000);
    }

    void connect_wifi(String cmd, int t)
    {
      int temp=0,i=0;
      while(1)
      {
        lcd.clear();
        lcd.print(cmd);
        Serial.println(cmd);
        Serial1.println(cmd);
        while(Serial1.available())
        {
          if(Serial1.find("OK"))

          i=8;
        }
        delay(t);
        if(i>5)
        break;
        i++;
      }
      if(i==8)
      {
       Serial.println("OK");
            lcd.setCursor(0,1);
          lcd.print("OK");
      }
      else
      {
       Serial.println("Error");
             lcd.setCursor(0,1);
          lcd.print("Error");
      }
    }

body:
You declare an object of type `DHT` and name `dht`. Then you try to call a method of `DHT.read11()`.

Instead, you should be using the object name, `dht.read11()`, or as @Gerben points out, change the way you declare the object:  `DHT dht;`.


message:
ESP8266 deep sleep and MQTT

I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor.  When it wakes from deep sleep I would like to send a message to my MQTT broker.  The wiring works, the interrupt works, however, the code does not.

When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working.  However, my MQTT broker does not show any messages.  But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.

Any suggestions would be greatly appreciated

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    const char* ssid = "*";
    const char* ss_pswd = "*";
    const char* mqtt_server = "*";
    WiFiClient EspClient;
    PubSubClient client(EspClient);

    void wifi_setup() {
      Serial.print("Connecting to: ");
      Serial.println(ssid);
      WiFi.begin(ssid, ss_pswd);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
    void reconnect() {
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        String ClientId = "ESP8266";
        ClientId += String(random(0xffff), HEX);
        if (client.connect(ClientId.c_str())) {
          Serial.println("connected");
          client.publish("outtopic", "hello world, finally");
          client.subscribe("/room/test");
        } else {
          Serial.print("failed, rc=");
          Serial.println(client.state());
          Serial.println("Try again...");
          delay(5000);
        }
      }
    }
    void sendMQTTMessage() {
      Serial.println("sending your message");
      if (!client.connected()) {
        reconnect();
      }
      client.publish("belmont/sensor/pir/hallway", "on");
    }
    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived: ");
      Serial.println(topic);
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
    }
    void setup() {
      Serial.begin(115200);
      wifi_setup();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
      sendMQTTMessage();
      Serial.println("going into deep sleep");
      ESP.deepSleep(10 * 1000000);
    }

    void loop() {
    //  sendMQTTMessage();
    //  delay(5000);
    }

body: The answer for this actually goes to Juraj.  It was the fact that I was missing a delay.  In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent.  I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.


message:
Can't add board for RFDuino in Arduino IDE

I tried to upload sketch to my RFDuino. I can select the RFDuino port. But I can't upload cos I can't select the RFDuino board.

I followed the installation steps listed [here](https://github.com/RFduino/RFduino)
but I don't see RFduino package in Board Manager after I finished the steps above.

I am using Mac Mojave and Arduino IDE v1.8.9. I have tried it with v1.6.6 but results the same.

body:
Turns out that rfduino.com's domain is gone, so the link will always return with an error downloading. After reading this thread [arduino.cc][1], @pert posted [a link for the .json file][2] that used to be at the website you have. I used this link on MacOS Mojave and Arduino v1.8.9 and it worked perfectly!

  [1]: https://forum.arduino.cc/index.php?topic=610331.0
  [2]: https://gist.github.com/per1234/f7822073e05276c4243740eaab4235d1/raw/9c34051294ddd54dbbdf3bec392df0afef8da938/package_rfduino166_index.json


message:
Combining 2 sensors in one code with 1 push button

I am trying to create a circuit with one tactile pushbutton, and LCD and two sensors: 1) temperature, and 2) pulse sensor. When the circuit is on, the LCD initially shows the reading from the temp sensor, when the button is pressed the LCD shows the reading from the pulse sensor.

The code compiles, the LCD shows both of the temperature function and pulse reading work.

I attached a picture of the schematic of the circuit.

The problem is that when the button is pressed, it takes many pushing of the button for the circuit to go from temperature reading to pulse reading. I thought maybe debouncing the button was unnecessary so I tried to write a code without the code, but it made no difference. My coding skills are still in the beginner side but I am trying my best for my coding to make sense. I just need some guidance and advice on what the problem could be and how I can tackle the problem. My code is attached here:

```
#include <LiquidCrystal.h>
#define BUTTON 2

const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

//TEMPERATURE
const int tempPin = A0;              // LM35 in A0

int T1=60;

//PULSE
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

int PulseWire = A1;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

//=========BUTTON DEBOUNCE============
boolean lastButton = LOW;     // last button state
boolean currentButton = LOW; // current button state
int switchMode = 1;             //cycle between function
//====================================
void setup()
{

  lcd.begin(16, 2);
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  //pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.

  }//end if

}//end void setup()

//Debouncing Function
boolean debounce(boolean last) {
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(T1);         //wait #ms
    current = digitalRead(BUTTON); //read it again
  }//end if
  return current;     //return the current value
}//end boolean debounce

void setMode(int mode) {

  //TEMP ON
  if (mode == 1)
  {
    Serial.begin(9600);
    int value = analogRead(tempPin); // read the value from the sensor
    lcd.setCursor(0, 1);
    float millivolts = (value / 1024.0) * 5000;
    float celsius = millivolts / 10;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp = "); lcd.print((celsius * 9) / 5 + 32);  lcd.print((char) 223); //turning the celsius into fahrehait
    lcd.print("F");
    lcd.setCursor(7, 2);
    lcd.print(celsius); lcd.print((char) 223);
    lcd.print("C");
    delay(1600);

    lcd.clear();
    delay(T1);
  }//end if TEMP ON

  //RED ON
  else if (mode == 2) {
    {
      Serial.begin(9600);
      int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
      // "myBPM" hold this BPM value now.

      if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
        Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
        Serial.print("BPM: ");                        // Print phrase "BPM: "
        Serial.println(myBPM);                        // Print the value inside of myBPM.

        lcd.setCursor(0, 0);
        lcd.print("HeartBeat Found!");
        lcd.setCursor(4, 1);
        lcd.print("BPM: "); lcd.print(myBPM);

        delay(1600);
        lcd.clear();
        delay(T1);
      }//end if
    }//end setMode void function
  }
}
    void loop()
    {
      currentButton = debounce(lastButton); //read debounced state
      if (lastButton == LOW && currentButton == HIGH) /// if it was pressed
      {
        switchMode++;
      }
      //if cycled through the different options,
      //reset the counter to 0
      if (switchMode == 3) switchMode = 1;
      setMode(switchMode);
    }//end loop
```
[![enter image description here][1]][1]

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

I also considered doing a switch case statement, but so far it hasn't worked either. Please let me know some ideas!

Thank you!!

body:
Your code has various issues, but the main one is that you can’t use `delay()` when you’re trying to more than one thing at a time. Delay causes your program to freeze, and not do anything else.

(Basically you should forget about the `delay()` function and never write any Arduino code that uses it. It is a code smell.)

You need to rewrite your code to record the value of `millis()` and then check back the next time through your loop function to see if enough time has passed. Do a Google search on “Arduino blink without delay” for an explanation of how to do this. Here’s an example article: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

(Note that some solutions suggest that you increment a counter every time through your loop and see if some magic number of counts has gone past based on how frequently you expect your loop to be called. That is a bad approach. You want to use the `millis()` function.


body:
Your loop function needs to call debounce() and setMode() as often as possible, and none of your functions must use delay(). Instead, they compute the time elapsed since the last action, and if it is greater than what you now use as a delay value, perform its next action; otherwise, it should just return.

Just as a curiosity, your present code will probably function (better...) if you press and hold the button until you get a response, instead of press-and-releasing multiple times, hoping to get one. The latter way depends on your pressing the button just as the system is reading it, but the system reads it too infrequently for that to be workable, as you found out. The delay() calls are the reason.


message:
Can't Interface SIM900a With Arduino Uno

I've got the following module of SIM900a.

[![SIM90a Module][1]][1]

My connections are:

    VCC -> External 5 Volt 1.5 Amp Supply
    GND -> Common GND
    TX -> Arduino RX (Pin 0)
    RX -> Arduino TX (Pin 1)

I hear a ring when I call on the sim card that has inserted there. So it can register to a network successfully. I've uploaded a blank code in Arduino Uno to test `AT Commands`. But I'm not getting any response when I type `AT` on Serial Monitor. What am I doing wrong here?

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

body: At first, make sure that the sim has connected to the network. For this, you can call to the sim number from another phone. If not ringing that means the sim wasn't able to connect with the network. For this check power supply, antenna etc. If ringing then there something wrong in connection or code. So cross check the connection and send `AT` to the module and wait for returned data. If no data returned, then there check connection again. If the returned data is `OK`, then it is ready to use. and if returned data is `ERROR` then Arduino have connected to sim module but sim network, power supply etc problem happening.


body:
I was facing the same issue and solved this issue when I have used softwareSerial.h library and used to connect TXD of sim900A with pin 13 and RXD of sim900A withpin 12 of ardunio MEGA.

You can also use 10 and 11 pins of mega instade of 12 and 13 i.e.

    #include <SoftwareSerial.h>      // Configure software serial por
    SoftwareSerial SIM900A(10, 11);  // (sim 900 connections RXD=>10 & TXD=>11)


message:
How to print not enough credits if the credits is not sufficient

The problem of my code is in the serial monitor it print the not enough credits even i did not pressed the button. The output that i want is it must be print not enough credits when i pressed the button.

    #include <Servo.h>
    const int coinpin = 2;
    const int buttonPin = 7;

    // Variables
    volatile int credits = 0;
    int buttonState = 0;
    const int servoPin = 8;
     Servo servo;

    // Setup
    void setup() {
      servo.attach (servoPin);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
      pinMode(buttonPin, INPUT);
      servo.write(0);

    }

    // Main loop
    void loop() {

    Serial.println(credits);
    delay(2000);
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH && credits == 5) {

      Serial.println(credits);
      servo.write(180);
      delay(1000);
      servo.write(0);
    }

    if(credits !=5) {
      Serial.println("NOT ENOUGH CREDITS");
      delay(2000);
    }

    }

    // Interrupt
    void coinInterrupt(){

      // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
      credits = credits + 1;
    }

body:
The second if statement is standalone and not inside the button press check if statement so will always print 'not enough credit' whenever credit is not exactly 5.
You might also want to look at debouncing the button as you're liable to get multiple triggers on one press.


body:
Look at lines of code I marked:

[![Formatted code from the question][1]][1]

Each loop you check for credits being equal to 5, and if it's not equal to 5 you write "NOT ENOUGH CREDITS" You might want to modify your "if" structure to only check for credits when the button is pressed.

Immediately I see two bugs:

 1. What happens when number of credits is 6? Is it enough or not?
 2. What happens when user presses the button for 2 or more "loop"s?

The physical button press looks to the hardware as several consecutive button presses because the button "bouncess" under your finger. Fixing that issue is called "debouncing" and there are several ways to do that. Read more about that.

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


message:
Adding esp32_komoot_ble library to Arduino IDE

I am an absolute beginner with Arduino IDE and I want to build an interesting device I stumbled upon on github
https://github.com/jstiefel/esp32_komoot_ble
Problem is I really can not add it to Arduino IDE. I did the wiring for the lcd and all, but please bear in mind i'm an electrician, with a very basic understanding of arduino/ absolute beginner.
What i'm asking is which is  the "main file" in the src folder so i can rename it 'ino' to work with the arduino IDE  and upload it to the esp32 board?
I downloaded the esp32 library and all the dependencies that says in the readme.md file. I download the esp32_komoot_ble.zip file. Now how do I get the  .cpp and .h files on the arduino IDE and finally my esp32 device. I have been watching tutorial for 1 week now  but could not figure it out yet!
Thank you for everything guys!

body:
The file, that you are searching, is the one, which contains the `setup()` and `loop` functions: `esp32_komoot_ble.cpp`

These functions are part of the Arduino framework and wrap the classic `main()` function. `setup()` is called once at startup, `loop()` after it repeating forever.


message:
Can I put a resistor in the ground connection of my DHT22 sensor?

I'm building a project that uses a couple of Adafruit DTH22 temp/humidity sensors. (https://www.adafruit.com/product/385)

I have them wired into my project box through 3.5mm mini plugs (The kind that are commonly used by stereo earbud headphones for MP3 players.)

More than half the time, when I plug/unplug one of my sensors, my Arduino restarts.

My guess is that as I plug in the plug, it sometimes momentarily shorts +5V and ground, causing the +5 source to my Arduino to lose voltage.

These sensors apparently draw single-digit mA of current at peak (like 1.5mA, according to the spec.)

Could I wire a 120Ω or 150Ω resistor in line with the ground connection to the DHT22? This would limit the max current it could carry to around 40mA, which would not be a problem for my power supply (which is fed through the USB port on the Arduino, and thus is limited to 500mA.) Putting a resistor on the ground would limit the current to ground from either the VCC connection to the sensor or the data connection. It would also cause a small loss of voltage to both the data line and the VCC connection.

Would the serial connection between the DHT22 and my Arduino tolerate a 120Ω resistor, even if I connect it via ≈15M of 28-gauge wire?

I could also put the resistor into the VCC wire, but that would only current-limit a VCC-to-ground short, not data-to-ground.

body:
Your case :
   Check wire (shors ?) and pin configuration (out ??)

General :
 No resistor in a ground path.

 Decoupling supply :
  one can insert a 100 Ohms resistor between the arduino +5V and the +5V sensor : but ALWAYS use a decoupling capacitor : connect a 100µF betwen +5V sensor and groud. One can add a 100nF ceramic in paraller for digital devices.

 Safety in case of bad I/O config :
  Using a 1kOhms restisor between Arduino and Device is good, if next to the Arduino (not at the other end of sensor cable, or use 330 Ohms at eatch end of cable).


message:
Using pushbutton to make Stepper motor rotate 90 degrees

Using a 28BYJ-48 Motor with a ULN2000 Driver. The motor works fine since I can rotate it using serial input.
Pushbutton is connected properly, Can light up an led if I connect one.
I want the motor to rotate 90 degrees everytime I push the button. When I run the code below the LEDs on the driver just blink rapidly, when I press and hold the button they stop blinking, keeping the state they were on already. e.g. if the LED A on the board was on at the moment I press the button, It stays on. If it was off, It stays off. you get the Idea.

code used:

    #include <Stepper.h>;

     // pushbutton pin
     const int buttonPin = 2;

     int STEPS = 32;
     Stepper stepper(STEPS,8,9,10,11);

    //create a variable to store a counter and set it to 0
    int counter = 0;
    void setup()
    {
      pinMode(buttonPin, INPUT);
    }

    void loop()
    {
     // local variable to hold the pushbutton states
      int buttonState;

      //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
      buttonState = digitalRead(buttonPin);

      //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
      if (buttonState == LOW) // light the LED
      {
        counter++;
        delay(150);
      }

      if(counter == 1)
        stepper.step(512);  // zero degrees
      //else reset the counter to 0 which resets thr servo to 0 degrees
      else
       counter = 0;
    }

EDIT 1: Modifying the code @Matej gave me, I was able to debug the problem that was causing the stepper to not rotate. the code:

    #include <Stepper.h>

    // pushbutton pin
    const int buttonPin = 2;

    const int STEPS = 32;
    Stepper stepper(STEPS, 8, 9, 10, 11);
    int val = 2048;

    //create a variable to store a counter and set it to 0
    int counter = 0;

    unsigned long last_button_time = 0;   //for aving last millis

    void setup(){
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
      stepper.setSpeed(1000);
    }

    void loop(){
      bool buttonState;   // local variable to hold the pushbutton states

      //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
      buttonState = digitalRead(buttonPin);
      //if the button is pressed incremen counter and wait a tiny bit to give us some          //time to release the button
      if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
        last_button_time = millis();
        counter = 1;
        Serial.println(counter);
      }

      if (counter == 1) {
        Serial.println("Please Write the desired angle");
        val = Serial.parseInt();
        delay(5000);
        counter = 0;
        if(Serial.available() > 0) {
        Serial.println("Stepping: ");
        Serial.print(val);
        stepper.step(val);
        counter = 0;
        Serial.println(counter);
        }
        else {
          Serial.println("ERROR LOOPING THROUGH IF STATEMENT");
        }
      }

    }

The Serial output looks like this:

    1
    Please Write the desired angle
    Stepping:
    00
    1
    Please Write the desired angle
    Stepping:
    20480
    1
    Please Write the desired angle
    Stepping:
    20480

please note that In the first attempt, I wrote "2048" in Serial input to define the value of the integer (val), and nothing happened. in the second and third attempt, I also wrote 2048 (0 at the end is the counter variable) and the motor started shaking, but it didn't rotate.

body:
I edtied few things in your code. I am not sure if `LOW` value is correct, so I replaced it with `HIGH`. Second thing is timing. I removed all `delay()` functions instead of it you can see usage of `millis()`. That's for handling interval between button press and button release - second part of `if` will check if last time of button press is bigger than `200ms`, if yes, move stepper. Last things is stepping. You can see here `stepper.step(STEPS/4);`. `STEPS` is variable which you declared on the top of code. It's called steps per revolution, one revolution is `360°` so `90°` will be `STEPS/4`.

Here is the code, read it and test it:

```
#include <Stepper.h>;

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}
```


message:
Is my code triggering the N-Channel MOSFET as I have intended to

I have a certain bit of code that I believe after 10 seconds will send a high signal to the second digital pin for 50 seconds. After it will not do anything.

For some reason the nichrome wire is not heating up. I realize there could be a problem with my circuit but just want to make sure for the final time it is not an issue with my code. Thanks.

```
int nichromePin = 2;

unsigned long burnTime = 10000;
unsigned long dt = 50000;
unsigned long time;

void setup()
{
  pinMode(nichromePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Balloon Countdown...");
  Serial.print("When Will It Burn: ");
  Serial.println(burnTime);

}

void loop()
{
  time = millis();

  if (time > burnTime && time < burnTime+dt)
  {
  digitalWrite(nichromePin, HIGH);
  Serial.print("Time: ");
  Serial.println(time);
  }
}
```

body:
The code is as follows: After 10 seconds following Arduino power up, burn the nichrome for 60 seconds, after which do nothing. I just tested it on my UNO and it works fine, so it must be your circuit. Post your nichrome question in the EE forums for help on that.

P.S. This code is kinda silly tho there's no trigger event!


message:
Conveyor and Counter Project

I am new to Arduino and looking for advice if Arduino is the right microcontroller for this project.

My project is quite simple, I want to build 3 conveyors using 3 DC motors. At the end of each conveyor I plan to implement 3 IR break beam sensors to each respective conveyor to count when an object passes through. When **n** objects passes through each respective conveyor and falls into a catching mechanism the DC motor stops until object(s) are cleared. For the catching mechanism for each conveyor, I plan to use IR break beam sensors to detect if it’s cleared or not as well. (If you have an alternative suggestion to IR break beam sensors, please advice)

Question: Can a single Arduino uno microcontroller board handle this project? From what I know, Arduino can only run one program at a time and I’m not sure if my project can be run in one program; I believe it can. Additionally, what if I wanted to add a LCD display?

body: Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)


message:
Simple multiplication bug

Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.

    long z = 0;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

      z = 255 * 255;
      Serial.println(z);
      delay(200);

    }

body:
Assuming long is 4 bytes, it should work.

However, if somehow a long type is only 2 bytes, or (more likely) you used another type or there is some wrong define/typedef, and it is a signed long (default if you do not used the unsigned keyword), the value range is -32,768 to 32,767 and 255 * 255 = 65,025 which is out of range.

So you can first try to use `unsigned long`.


body:
No, this is not a bug. You are using a compile time constant expression which is `signed int` unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of `255 * 255 = 65025` exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like `uint16_t` have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:

```
z = 255U * 255U;
````

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".


message:
Selected board depends on 'arduino' core (not installed)

When I load the Arduino IDE with `Board: Pololu A-Star 32U4` selected, I see:

```
The current selected board needs the core 'arduino:arduino' that is not installed.
```

I installed the board manually via [these instructions](https://github.com/pololu/a-star#manual-installation).

When verifying the initial empty sketch, I see:

    Arduino: 1.8.8 (Linux), Board: "Pololu A-Star 32U4"

    The current selected board needs the core 'arduino:arduino' that is not installed.
    /usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/ravi/Arduino/hardware -tools /usr/share/arduino/tools-builder -libraries /home/ravi/Arduino/libraries -fqbn=pololu:avr:a-star32U4 -ide-version=10808 -build-path /tmp/arduino_build_299010 -warnings=none -build-cache /tmp/arduino_cache_842714 -prefs=build.warn_data_percentage=75 -verbose /tmp/untitled689103723.tmp/sketch_feb05a/sketch_feb05a.ino

    Selected board depends on 'arduino' core (not installed).

    Error compiling for board Pololu A-Star 32U4.

How do I prevent this error and compile a sketch?

body:
I needed to install the boards package for:

    Arduino AVR Boards

Under Tools -> Board -> Board Manager


message:
AnalogRead value constant for a varying voltage (for LED brightness variation)

Having the 11~ pin on OUTPUT mode that delivers a varying voltage (from 0 to 5 : 0 to 255).

and the A0 pin on INPUT mode to read the voltage, I find that the value read by A0 being either 0 or 1016 instead of it gradually taking multiple values between the two. what is the catch?

The circuit and the code i am using:

[![https://i.ibb.co/dDMJJCg/Cir.png][1]][1]

    int volt = 0;
    int sign = 1; //values: (1, -1), increments or decrements "volt" by 5.
    float potential;

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);

    }

    void loop() {

    if (volt == 0){sign = 1;}
    if (volt == 255){sign = -1}

    volt = volt + sign * 5; //raises brightness to 255 from 0, then to 0 from 255.
    analogWrite(11, volt);

    potential = analogRead(A0);

    Serial.println(potential);

    delay(30);
    /*
    */

    }

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

body:
The PWM output pin does not vary voltage - it only outputs 0, or 5V. The amount of time that 5V is on, from 1/255 of about a 2mS period, to 255/255 of the same period, determines how bright the LED is perceived to be.

You really need a current limit resistor in series with the LED to keep from burning out the uC output pin, or from burning up the LED.


body:
As CrossRoads says, there really isn't any such thing as analog output on an Arduino. (Any Arduino unless it has a built-in DAC.) It uses pulse-width modulation to vary the "duty cycle" of the output from 100% on to 0% on, which simulates an analog voltage.

If you drive an LED with PWM (and the required current limiting resistor) your eyes will not see the flashes, and will average out the brightness based on the duty cycle of the PWM signal.

If you want an actual analog voltage from PWM you will need to add a filter capacitor to average out the voltage over time. With a simple single capacitor filter you'll still have flutter in the output but it will be closer. If you want a clean constant voltage you'll need a more complex filter.


message:
Printing elements of char array from PROGMEM

Given:

    const char* PROGMEM names[] = {"Foo","Bar"};
    Serial.print(names[0]);

I get garbage output. Is there some function that will print the string from PROGMEM? E.G.:

    Serial.print(<function name>(names[0]);

body:
Among many others, check out pgmspace.h utilities at
[AVR-libc][1]

  [1]: https://www.nongnu.org/avr-libc/user-manual/modules.html


body:
    const char PROGMEM b0 = pgm_read_dword(&(names[0]));
    Serial.print(b0);


message:
Which is a better? GPRS SIM800L or GPRS SIM900?

I will implementate the GPRS technologity in my Arduino project, but before buy the module, I want to know which is a better. If GPRS SIM800L or GPRS SIM900? My needs are send JSON array through POST request.

Thanks and best regards.

body:
SIM900 is older type. SIM800L has FM build it and it uses same AT cmds as SIM900.
Also, they are in same quadband. I guess both will work just fine.


message:
NPN sensor to Arduino

I have a beam sensor providing NPN and also PNP output. It as 4 wires and works on 24V. I hooked the brown(+) and blue(-) to a small 24V power supply and the sensor is working!!! Yeah!

Now I would like to recieve the signal in my arduino. I dont know where to plug the black and white and I dont want to frie everything. I know I need to have an NPN configuration but I dont know how to achieve that.

This is the sensor in question: https://literature.rockwellautomation.com/idc/groups/literature/documents/in/42ef-in005_-en-p.pdf

And a little shema of my conections:
[![Senseor setup][1]][1]

If someone could help me.
Thanks,
Nicolas

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

body:
I would connect the - from the supply and the sensor to Arduino Gnd.

Then the NPN output can pulldown an Arduino input with pullup resistor enabled.

Brown to 24V, Blue to Gnd, White to Arduino input.  No resistor to Brown. Black not used.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/UQnXJ.png)

<!-- End schematic -->


message:
Is every Arduino comes with onboard compass?

The doubt was came in mind after seeing Arduino [documentation][1]. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?

  [1]: https://www.arduino.cc/en/Reference/RobotTurn

body:
No current Arduino board comes with an on-board compass. That function description comes from the documentation for the [Arduino Robot][1], which is a retired product.

There may be other "maker" dev boards, such as the [Adafruit Circuit Playground Express][2] which have on-board compass peripherals.

  [1]: https://www.arduino.cc/en/Guide/Robot
  [2]: https://learn.adafruit.com/circuit-playground-express-compass/overview


message:
Several Software Serial Ports

I am planning to use an Arduino (Nano ideally, or Other) to send and receive information from several software serial ports to other arduinos, over their available pins, ideally 8 ports.

I could understand an Asynchrounous Communication having one *master* and 8 *slaves*, with the master enabling communication from one port, receiving the data from that port, and then move onto the next port, into a sampling loop.

The `SoftwareSerial` library allows to set up the pins individually, and set the `listen()` port (thanks Juraj).

I read the `AltSoftSerial` library handle [some of the limitations][1] of the `SoftwareSerial` library, but I just realized the pins cannot be configured (without... cloning the full library?).

Question is:

 - Option 1: Should I stick with the `SoftwareSerial` library?,
 - Option 2: Should I try the `AltSoftSerial` library, and figure how to duplicate it (i think this is a NO)?
 - Option 3: Understand that none of these libraries are prepared for this, and seek for other alternative?
 - Option 4: It is pointless to have several serial trunks in Arduino, if only one will work at a time, and should hence try to arrange just one serial trunk?

  [1]: https://1sheeld.com/arduinos-softwareserial-vs-altsoftserial-library-use-1sheeld/

body:
You could use a part with 2 hardware serial ports (Atmega1284P), and use a simple mux chip to switch between the slaves for the master to receive from, such as DG406
https://www.digikey.com/products/en/integrated-circuits-ics/interface-analog-switches-multiplexers-demultiplexers/747?k=dg406&k=&pkeyword=dg406&sv=0&pv1989=0&pv433=170&sf=0&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25

Hardware serial will allow for faster comm's too, vs software serial.
1284P is Arduino friendly too.


body: I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.