body:
This is actually a huge topic, one that I could write volumes on. However I will try and be concise. But it is such a common question it's time to finally write a definitive answer.

Sending data between devices, be that computers, Arduinos, or anything else like that, is very much like speaking to someone.

It is very common to do something like you have done and just "send" the data. However that is, as you have rightly noticed, very much akin to sending someone a message all in capitals with no spaces or punctuation. Like this:

> WHATAPIECEOFWORKISMANHOWNOBLEINREASONHOWINFINITEINFACULTYINFORMANDMOVINGHOWEXPRESSANDADMIRABLEINACTIONHOWLIKEANANGELINAPPREHENSIONHOWLIKEAGODTHEBEAUTYOFTHEWORLDTHEPARAGONOFANIMALSANDYETTOMEWHATISTHISQUINTESSENCEOFDUSTMANDELIGHTSNOTMENONORWOMANEITHERTHOUGHBYYOURSMILINGYOUSEEMTOSAYSO

Only through effort and the application of known predefined standards (i.e., English vocabulary) is it possible to make out what the message says.

So in language we introduce "meta" information - that is, information in a message that tells you not about the content of the message, but about the message itself.  The simplest is to introduce spaces to indicate where words start and end. So that message now becomes:

> WHAT A PIECE OF WORK IS MAN HOW NOBLE IN REASON HOW INFINITE IN FACULTY IN FORM AND MOVING HOW EXPRESS AND ADMIRABLE IN ACTION HOW LIKE AN ANGEL IN APPREHENSION HOW LIKE A GOD THE BEAUTY OF THE WORLD THE PARAGON OF ANIMALS AND YET TO ME WHAT IS THIS QUINTESSENCE OF DUST MAN DELIGHTS NOT ME NO NOR WOMAN EITHER THOUGH BY YOUR SMILING YOU SEEM TO SAY SO

There, that's much more readable. But still lacking. So we add more "meta" characters that provide even more information about the formation of the message: punctuation.  Now we can have:

> What a piece of work is a man! How noble in reason, how infinite in faculty! In form and moving how express and admirable! In action how like an Angel! in apprehension how like a god! The beauty of the world! The paragon of animals! And yet to me, what is this quintessence of dust? Man delights not me; no, nor Woman neither; though by your smiling you seem to say so.

And now the message is completely plain. What we have done here is introduce characters that aren't part of the message but form the structure of the message. These characters are distinct from the message by being of a different type of character. Not letters, but symbols instead. It's possible to add any symbol you could imagine and attach a meaning to it to convey any information about the message you like. There is no limit.

But that's where computer communication differs.

When sending data over serial you have a limited range of values you can send. You have one byte for sending information, which means that you can only send one of 256 possible "symbols".

When you're sending, as you are, binary data you use all 256 symbols for your data. There are no symbols left for any "punctuation" in your message. It becomes impossible to go even from the first to the second examples above, let alone the third.

So what can be done?

Well, there's two approaches:

1. Re-encode your data to use less "symbols" leaving some available for meta information
2. Nominate some of the symbols used for data to be also used for meta information and create some way of distinguishing them from the actual data

The first method is probably the simplest - change the data encoding to use a smaller range of symbols. The most obvious way is to use ASCII encoding - use just 10 symbols to represent numerical data, but use a lot more of them. I'm sure you know the symbols: "0123456789". You then have such standard symbols as "New Line" (or `\n`) to mark when your message is finished, and commas to separate different parts of your message.

It's easy to encode and transmit, but harder to receive.  Sending is as simple as:

```c++
Serial.print(Value);
Serial.print(F(","));
Serial.print(Value2);
Serial.print(F(","));
Serial.print(Value3);
Serial.print(F(","));
Serial.println(Value4);
```

Receiving that data and making sense of it is far more involved. You have to read everything up to a comma (or to the end of the line and split it on a comma) and then convert the ASCII text back into numbers. It could be done on the fly on a character-by-character bases (read a character, if it's a number then multiply your current value by 10 and add the new number to it, if it's a comma then move on to to the next number, or if it's the end-of-line then reset to the first number again) or as a whole chunk of data (read the whole lot into a char array until you reach `\n` then split it with `strtok()` on the commas, and convert each chunk with `atoi()`).

That method though is not efficient. It takes a lot of bytes to represent just a small number (for instance the number 100 takes 3 bytes whereas the value 100 will fit into a single byte as a raw value), and processing it afterwards is slow and cumbersome.

Method 2 from the list above is far more efficient, but takes a little more in-depth knowledge and thought.

Step one is to design a strict format for your message. You need some way of saying "This is the start of the message" and "This is the end of the message" and everything in between is considered the data for the message. Since you are working with fixed sized variables you don't need anything within that data to separate the values.

You have 4 integer values. That's 8 bytes in total (each integer takes 2 bytes for 16 bits).  You could pack those together in to a `struct` for easier handling:

```c++
struct data {
    int value1;
    int value2;
    int value3;
    int value4;
};

struct data values;
```

That is good if you have lots of different kinds of data, but since yours are all the same a simple array might be better:

```c++
int values[4];
```

Now the ASCII character set has a set of control characters that are intended to be used for building these kind of messages. For example character 2 is "STX" or "Start Of Text". Character 4 is "EOT" or "End Of Transmission".  So you could choose to start your message with character 2, then send your 8 bytes, and follow it with character 4.  Then you just look for a 2, read 8 bytes, and check it's followed by a 4.  That would work, right?

Well, no. Not quite. What if you're sending the value 2 or 4 as part of your data? How would it distinguish those from the start/end characters?  You can't.

It's now time to introduce a new concept: Data Link Escape. This is where you nominate another special character. This one says "The next character is data. Treat it as such". DLE is character 16 in ASCII, so you might like to use that. 27 is sometimes used too, or 255. You can use whatever you like, but I like 16 (DLE).

The idea here is that if you are sending a byte that could be either a control character or a data character (i.e., 2 or 4) then you *first* send the DLE character *if and only if that character should be interpreted as data*. So if you are sending a start byte you send just 2. If you're sending the value of 2 in your data you send 16 then 2.

But what, you ask, if you are sending the value 16 in your data? Simple: you just send it twice. The first time is the DLE character which says the next byte is data. The next is interpreted as data regardless because it's following the DLE character.

Sounds complex, yes? Well, not really. Let's visualise it.  Take our original text message. Let's nominate A as the start of message and B as the end of message. We'll even add C as a space character. D will be our DLE character.  Our message would now look like (I won't do it all, too tedious...):

> AWHDATCDACPIEDCECOFCWORKCISCMDANB

To you as a human it looks garbled, but that's because you're trying to apply standard English rules to it. But if we take it one character at a time and apply our new rules to it it's different:

* A - start of message
* W - letter W
* H - letter H
* D - Next character is a letter
* A - letter A
* T - letter T
* C - Space

... etc ...

We do just the same with your binary data. Let's say we're sending the values 23, 2, 16 and 1928 as integers. In little-endian (I'll go into that later on) that's represented as the values

```
23,0,2,0,16,0,136,7
```

so with our start and end characters, and adding our DLE character 16 we end up with

```
2,23,0,16,2,0,16,16,0,136,7,4
```

You might like to write a little function to send data in that format:

```c++

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

void sendPacket(const uint8_t *data, int len) {
    Serial.write(STX);
    for (int i = 0; i < len; i++) {
        // Escape the special characters
        if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
            Serial.write(DLE);
        }
        Serial.write(data[i]);
    }
    Serial.write(EOT);
}

// then use it:

sendPacket((uint8_t *)values, sizeof(values));
```

Now reception can be done one byte at a time and fed into your array as raw data. Something like this:

```c++

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

bool rxData(uint8_t *data, int len) {
    static int pos = 0; // Where in the data are we now?
    static bool isDLE = false; // Are we in DLE mode?
    static bool messageStarted = false; // Are we receiving yet?

    if (Serial.available()) {
        int b = Serial.read(); // Read one byte

        if (!messageStarted) { // We're not receiving yet - should we start?
            if (b == STX) { // STX received, start receiving.
                messageStarted = true;
            }
            // Anything else is ignored.
            return false; // Message not complete yet
        }

        // If we're here we must be part way through receiving.

        // If we received a DLE last time then we always treat it as data
        if (isDLE) {
            data[pos++] = b;
            isDLE = false; // No longer in DLE mode
            if (pos > len) { // Too many bytes in the message, something bad happened
                // ABORT
                pos = 0;
                messageStarted = false;
            }
            return false; // Message not complete yet
        }

        // If we have an STX and we're not in DLE mode then we must be
        // out of sync. Reset the counter and flags and start a fresh message
        if (b == STX) {
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Are we at the end of the message?
        if (b == EOT) {
            if (pos == len) { // Did we receive the right number of bytes?
                messageStarted = false;
                return true; // Message complete
            }
            // Something bad must have happened. Not the right amount of
            // bytes received for a valid message. ABORT.
            messageStarted = false;
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Check for a DLE character
        if (b == DLE) {
            isDLE = true;
            return false; // Message not complete yet
        }

        // Anything else is a data byte.
        data[pos++] = b;
        if (pos > len) { // Too many bytes in the message, something bad happened
            // ABORT
            pos = 0;
            messageStarted = false;
        }
    }
    return false; // Message not complete yet
}

// Then use it:

if (rxData((uint8_t *)values, sizeof(values)) {
    Serial.print("You got: ");
    Serial.print(values[0]);
    Serial.print(", ");
    Serial.print(values[1]);
    Serial.print(", ");
    Serial.print(values[2]);
    Serial.print(", ");
    Serial.println(values[3]);
}
```

Now I haven't tested any of this code, so take it with a pinch of salt.

Now a little word on *endianness*.  An integer is 16 bits in size. That takes two bytes to represent (2 x 8 = 16). The "endianness" of a system is the order in which those two bytes are stored in memory.  In a little-endian system, like the Arduino, the value 1928 is stored as the bytes 136,7. But on a big-endian system it's stored as 7,136. The "biggest" (i.e., most significant byte) value comes first. When sending binary data like this it's vital to ensure that both ends of the link agree on the order of the bytes. And then there's word size to consider. 8-bit systems use a 16-bit word for integers. 32-bit systems use a 32-bit word. So sending an `int` from an Arduino to a Pi, for example, will cause confusion - the Arduino sends 2 bytes (for 16 bits) and the Pi expects 4 bytes (for 32 bits).

To combat the latter it is good to use the fixed width variable types that specify exactly how many bits are used. Instead of `int` use `uint16_t` (for **U**nsigned **INT**eger **16** bits). That way you're unambiguous about what size it is.

To combat the former problem (if needed) there are a standard set of functions that alter values from native to "network" endianness. Network endianness is a standard used for IP communication and is the same as big-endian.  If you're only ever going to communicate between little-endian Arduinos then there's no real need for this. But if that is not going to be a certainty then using `htons()` for "Host to Network Short" and `ntohs()` for "Network to Host Short" ("short" is a 16 bit word, like `int16_t`) could be of benefit. It's best to use them when storing or retrieving values in your `values[]` array:

```c++
values[0] = htons(analogRead(0));
```

and:

```c++
Serial.print(ntohs(values[0]);
```

You may need to include the header `machine/endian.h` in your code depending on which system you're using.

I could go into so much more depth about things like variable length packets, checksums, sliding window reception and such, but for now this covers the basic concepts. Maybe I'll write a book.


sender: user

message:
I have made a Nano send 4 pot values to an Uno please help with code

Happy New Year!

So I have made a Nano send 4 pot values to an Arduino Uno over serial but I have a problem: I don't know how to separate these values. Here's the code:

Master:
```c++
    int Pot = A0;
    int Pot2 = A1;
    int Pot3 = A2;
    int Pot4 = A3;

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

    void loop() {
      int Value = analogRead(Pot);
      int Value2 = analogRead(Pot2);
      int Value3 = analogRead(Pot3);
      int Value4 = analogRead(Pot4);
      Serial.write(Value); //Write the serial data
      Serial.write(Value2); //Write the serial data
      Serial.write(Value3); //Write the serial data
      Serial.write(Value4); //Write the serial data
      delay(150);
    }
```

Slave:

```c++
    int incomingByte; // for incoming serial data

    void setup() {
      Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
      }
    }
```

And a bit from the serial logs:
<pre>
    I received: 255
    I received: 247
    I received: 11
    I received: 0
</pre>

It updates and sends these four values for the four pots, it can read them but they are together, and it sometimes also kind of lags if I can say it like that; it sometimes takes longer to update but then it goes to normal again.

Thanks!

sender: assistant

body:
  So like this? And also what kind of serial speeds do I use? @Majenko This is the sender:

        int pot1 = A0;
        int pot2 = A1;
        int pot3 = A2;
        int pot4 = A3;

        // Some symbols for easy reference
        #define STX 2
        #define EOT 4
        #define DLE 16

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

        void sendPacket(const uint8_t *data, int len) {
          Serial.write(STX);
          for (int i = 0; i < len; i++) {
            // Escape the special characters
            if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
              Serial.write(DLE);
            }
            Serial.write(data[i]);
          }
          Serial.write(EOT);
        }

        void loop() {

          int values[4] = {analogRead(pot1), analogRead(pot2), analogRead(pot3), analogRead(pot4)};
          sendPacket((uint8_t *)values, sizeof(values));

        }

And this is the receiver:

    int values[4];

    // Some symbols for easy reference
    #define STX 2
    #define EOT 4
    #define DLE 16

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

    bool rxData(uint8_t *data, int len) {
      static int pos = 0; // Where in the data are we now?
      static bool isDLE = false; // Are we in DLE mode?
      static bool messageStarted = false; // Are we receiving yet?

      if (Serial.available()) {
        int b = Serial.read(); // Read one byte

        if (!messageStarted) { // We're not receiving yet - should we start?
          if (b == STX) { // STX received, start receiving.
            messageStarted = true;
          }
          // Anything else is ignored.
          return false; // Message not complete yet
        }

        // If we're here we must be part way through receiving.

        // If we received a DLE last time then we always treat it as data
        if (isDLE) {
          data[pos++] = b;
          isDLE = false; // No longer in DLE mode
          if (pos > len) { // Too many bytes in the message, something bad happened
            // ABORT
            pos = 0;
            messageStarted = false;
          }
          return false; // Message not complete yet
        }

        // If we have an STX and we're not in DLE mode then we must be
        // out of sync. Reset the counter and flags and start a fresh message
        if (b == STX) {
          pos = 0;
          isDLE = false;
          return false; // Message not complete yet
        }

        // Are we at the end of the message?
        if (b == EOT) {
          if (pos == len) { // Did we receive the right number of bytes?
            messageStarted = false;
            return true; // Message complete
          }
          // Something bad must have happened. Not the right amount of
          // bytes received for a valid message. ABORT.
          messageStarted = false;
          pos = 0;
          isDLE = false;
          return false; // Message not complete yet
        }

        // Check for a DLE character
        if (b == DLE) {
          isDLE = true;
          return false; // Message not complete yet
        }

        // Anything else is a data byte.
        data[pos++] = b;
        if (pos > len) { // Too many bytes in the message, something bad happened
          // ABORT
          pos = 0;
          messageStarted = false;
        }
      }
      return false; // Message not complete yet
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (rxData((uint8_t *)values, sizeof(values))) {
      Serial.print("You got: ");
        Serial.print(values[0]);
        Serial.print(", ");
        Serial.print(values[1]);
        Serial.print(", ");
        Serial.print(values[2]);
        Serial.print(", ");
        Serial.println(values[3]);
      }
    }


message:
Routing Arduino Mega output to either one of two serial ports

I have an Arduino Mega controller that normally communicates via Bluetooth (HC08 Bluetooth module) to an Android device. In case there is a problem on the Android side I wish to have a fallback ability to communicate via the USB serial port. The choice of serial port is determined by a hardware switch that the Arduino can read. Currently I have:
```
HardwareSerial & Terminal = Serial;
HardwareSerial & BTPort = Serial1;
```

Is there a way to route an output to either BTPort or to terminal, dependent on the state of the switch? Ideally I would like to do something like this:
```
HardwareSerial & OutputPort
if(switch_is_on)
  OutputPort = Terminal;
else
  OutputPort = BTPort;

```
Obviously the above code does not work. I have no idea of how to proceed.

body:
I can think of three distinct ways (and one that is similar to another) of doing what you want.

But first a note on *polymorphism*.  The `HardwareSerial` class is itself a child of the `Stream` class. It's this `Stream` class that provides all the read/write functionality (it, itself, is a child of the `Print` class which provides all the `print(...)` functions).

If all you want to do is print then you should be working with the `Print` class. if you want to do both reading and writing then the `Stream` class is what you want. You should only use `HardwareSerial` if you *need* to use the Serial-specific functions like `.begin(baud)`.

So with that in mind you could:

# 1. Assign a pointer

```c++
Print *printer;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    printer = &Serial;
}

void loop() {
    printer = &Serial;
    printer->println(millis());
    delay(100);
    printer = &Serial1;
    printer->println(millis());
    delay(100);
}
```

This is by far the most efficient method from a purely machine perspective.

Note the use of `->` instead of `.` when calling a function on a pointer.

# 2a. Use a wrapper function

```c++
uint8_t stream = 0;

void printit(const char *text) {
    switch (stream) {
        case 0:
            Serial.print(text);
            break;
        case 1:
            Serial1.print(text);
            break;
    }
}

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

void loop() {
    stream = 0;
    printit("Hello on stream 0\r\n");
    stream = 1;
    printit("Hello on stream 1\r\n");
}
```

This is less efficient and limits what you can print unless you write lots of overloaded functions.

# 2b. Use a macro

This is like 2a but uses a macro instead of a function:

```c++
#define printit(T) if (stream == 0) Serial.print(T) else Serial1.print(T)
```

This keeps the standard overloading of the print function but has lots of IF statements littered through your code. A fraction more efficient than 2a since it's all inline. Harder for a human to understand though.

# 3. Create a wrapper class

This is the rolls-royce method. Everything becomes encapsulated in your own object. Pointers are used to keep it efficient.

```c++
class Printer : public Print {
    private:
        Print *stream;
        Print *stream0;
        Print *stream1;
    public:
        Printer(Print &s0, Print &s1) : stream0(&s0), stream1(&s1) {
            stream = &s0;
        }
        size_t write(uint8_t c) {
            return stream->write(c);
        }
        void setStream(uint8_t sno) {
            switch (sno) {
                case 0: stream = stream0; break;
                case 1: stream = stream1; break;
            }
        }
};

Printer printer(Serial, Serial1);

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

void loop() {
    printer.setStream(0);
    printer.println(millis());
    delay(100);
    printer.setStream(1);
    printer.prinln(millis());
    delay(100);
}
```

With this method the new class could be put into a library and used across your projects.

You also get all the functions you'd normally get with the `Serial` object when printing (for reading change `Print` to `Stream` and implement all the *pure virtual* functions you need for that class).

And a footnote for all those that say "Why use pointers? Why not references?" I say: I hate references. Pointers are far more obvious what they are. References you can't tell apart from distinct variables. With a pointer you know it's a pointer. References are the spawn of the devil.


message:
How to upload code without closing puTTY

My question is quite simple: can you, somehow, upload Arduino code without closing puTTY's serial console? I hate having to close the program to open it again for reading the incoming information.

body:
You can't. Putty has no way of disconnecting without closing the program (as far as I can tell).

You could try "Tera Term" which apparently (though I don't use Windows so have no experience with it) has a disconnect option (which you would have to use before uploading).

Alternatively, as @Juraj has mentioned, you could use a separate USB to TTL UART adaptor to provide a second debug serial port (either with SoftwareSerial or mirroring the TX pin of the Arduino directly - don't connect RX in this case) which doesn't interfere with software upload.


body:
There is an open source project that will do what you want.

http://com0com.sourceforge.net/

The com0com will create virtual com ports for the programs to connect to.

The hub4com will allow you to route data between the physical port and multiple virtual com ports.

http://com0com.sourceforge.net/hub4com/ReadMe.txt


message:
BLDC geared motor with encoder - How to wire the encoder? (6 wires)

I am quite a newbie to Arduino and currently stuck with an encoder.

I have a BLDC geared motor with encoder, all I want to do is to get values from the encoder.

There are 6 wires: out A, out B, out Z, +V, 0V, FG. How should I wire the six of them correctly?

Encoder specification says 5 VDC is OK to power it, and I want to make a circuit to power an encoder using an Arduino Mega board.

body:
This should be in the documentation of the motor or encoder, and that is the first place to look.

If you don't have any documentation, here is my best guess:

ABZ suggests it is an *[incremental encoder][1]* with channel A and B for *quadrature encoding* (giving direction and speed), with Z as the *index pulse* for getting absolute position once every rotation. FG is most probably Frame Ground, or maybe be the Fault signal.

How you wire it all depends on what you want to do with it, but knowing what each signal is should make it easy enough.

  [1]: https://en.wikipedia.org/wiki/Rotary_encoder#Incremental


message:
Does Linux have software protection on USB? Or has the magic smoke escaped?

I'm making a GUI in Python that will control an Arduino via serial monitor. I have 6 input pins grounded and I'm taking 5V from the board (powered from USB) whilst serial monitoring and everything's going beautifully.

I'm so impressed by all these flickering 0's and 1's that I drop my flying lead straight onto the tiny cap behind the USB connector on the UNO. Everything is definitely not going beautifully now.  My serial data is frozen mid-string.

I try to connect again with my serial monitor software:

Error: Could not open device /dev/ttyUSB0

Power off and on my PC and the Arduino, same result. So, I connect another board a nano this time.

The Arduino Web Editor recognizes that I have connected a Nano, but when I try to upload my code the Arduino Web Editor says this:

avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

So, I put this in to terminal:

```#
sudo chmod a+rw /dev/ttyACM0
chmod: cannot access '/dev/ttyACM0': No such file or directory
sudo chmod a+rw /dev/ttyusb0
chmod: cannot access '/dev/ttyusb0': No such file or directory
```

Thought I might have fried my USB but it's still accepting flash drives being plugged in, and I have connected to both front and back USBs with the same results. And I have power-cycled my PC.

So, not sure if I fried my Arduino, (but having 2 Arduinos with the same fault seems unlikely, especially as one was not attached when I dropped the flying lead).

Magic smoke escaped from my PC USB ports, but again it seems unlikely that front and back would be dead whilst allowing USB sticks to communicate.

Is there some kind of software fusing preventing communication that needs to be/can be reset? Or could something have become corrupted maybe?

I'm on Ubuntu 20. If anyone knows of a command I can give that will bring ttyusb0 back to life, that would be great.

body:
The fact that you're referencing `ttyUSB0` tells me you have cheap Chinese clones and not genuine Ardunios.  These are usually based around the CH340 USB interface chip which is notoriously unreliable.

Your UNO is dead.

My supposition is that plugging it in cripples the CH340 driver.  Any other boards that you subsequently plug in can not be recognised because the driver is in a bad state.

To prove this:

1. Unplug the UNO
2. Reboot (power cycle) the computer
3. Plug in the Nano

It should recognise the Nano fine.

4. Unplug the Nano
5. Plug in the UNO

It should fail now.

6. Unplug the UNO
7. Plug in the Nano

The Nano should now also fail.

If that sequence is correct then the Uno is definitely dead. Throw it away, or at least never plug it in through USB ever again (you could program over serial through the TX/RX pins or using ICSP as if it were a breadboard Arduino though).


body:
running:

`sudo usermod -a -G dialout $USER `

cleared the issue it was the first time I have used that machine with an Aduino not sure how it was running before with out permissions set up correctly or why it failed when I dropped that 5v, I assume that just reset the board and when it tried to reconnect it failed. Both board and PC all working fine, phew.

Thanks


message:
What is the over-volt, over-current or over-power limit on a pin to an Arduino Mega 2560

I have an input voltage going to an Arduino pin that could be up to 5.25 V. I have many options on solving the problem but the simplest would be to include an inline resistor that limits the power that the over-voltage can deliver to the board.

I have done some experiments with the board using a pin that is set to `INPUT`, `INPUT_PULLUP`, `OUTPUT` set to low and `OUTPUT` set to high. I sent a voltage through a 33 kOhm resistor to the pin in those configurations, and swept 0-6V across the resistor. The pin voltage when in `OUTPUT` mode was very rigid, holding its output perfectly against the resistor.

When in either `INPUT` mode, the overvoltages seemed to happily pass through the resistor, driving at most 65 uA and 0.15 mW into the pin while it was raised to the 5.5 V value. it seems to me then that the Arduino pins are quite resilient to overvoltage, but this might be an incorrect assessment.

body:
The maximum voltage on any IO pin is VCC+0.5V or 5.5V when powered from 5V.

The maximum "injected" current is not specified in the datasheet, but typically 1mA is a reasonable value to assume.

So 5.25V at 65uA is, while not ideal, at least tolerable.


body:
The ATMega2560 Datasheet is here:

[Microchip ATMeta2560 Datasheet][1]

The important section for questions like this is: **ABSOLUTE MAXIMUM RATINGS**

For this chip we are provided:

[![Absolute Maximum Ratings ATMega2560][2]][2]

Note the Voltage on any Pin... specification that I have highlighted.  This says that under NO circumstances should you allow a pin to go below -0.5V or above (Vcc + 0.5V) or you risk damaging the chip.  So if you are running at 5.0V that means you can safely apply a voltage of +5.5V to the pin.

Your 0-6V signal is over the limit for this device and you will fall into the other section that I highlighted, the "NOTICE".

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega640-1280-1281-2560-2561-Datasheet-DS40002211A.pdf
  [2]: https://i.stack.imgur.com/Qjyoe.png


message:
If condition for switch not working as expected

I am trying to write a simple program to control one LED with two switches.

If any of the switches is pressed, I want to turn the LED on.

My LED however is always ON even when none of the switches are pushed.
Why could this happen?

Thanks!

https://www.tinkercad.com/things/7SRoEXkHRqh-one-led-two-switches-

[![Image capture from tinkercad link][1]][1]

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

body:
It's hard to tell which pins of the switch do what. Since you have your inputs set up as INPUT (instead of INPUT_PULLUP) you should have a resistor (10k Ω, say) tying those pins to ground. Then the other end of switch should connect to +5V. Don't connect the switches to both +5V and ground.

Use a multimeter on continuity to make sure that the pins of the switch that you are using are open normally, and close when you press the switch. With 4 pins it's easy to get confused as to which switch pin does what.


body:
It's easy to confuse the pins of these single-pole buttons - I still do it. Only two pins are needed for this kind of button. The extra two are there for mechanical stability on the PC board.

Lay the button on one of its sides:

 - If the two upper pins come out of the top edge, those pins are switched - either open, or shorted by the button. Ditto, for the two bottom pins.

- If instead, the two upper pins come out of opposite edges, those two are literally a *single piece of wire* passing through the button-frame and so are *always* shorted to each other. These two pins together are open with respect to the bottom two pins when the button is released, or shorted to the bottom two pins when the button is pressed.

Update:

> I probably won't remember your info next time I need to use one of
> these switches, so I'll still have to just test it... :(

Thanks, @Duncan C. I probably made it more complicated than it needed to be! How about:

Each pair of pins is a flat metal strip, bent to pass through the switch body, each end of it pointing down at the PC board; roughly into the shape of the letter 'C'. Looking at one of the pins, there is only one other pin that could be its other end, because you can only  bend a flat strip toward one of its faces, not edgewise.


message:
SoftwareSerial read until available is empty only works with delay

I originally was only going to make my program work on an ESP until I needed it on an Arduino UNO (because  I suspect my ESP is broken).
I had to add SoftwareSerial support but because I didn't originally intend to, the strings I send from my app have no terminators on them. I thought this would be fine because I could do something like:
```
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}
```
All that is doing is creating a string out of the recieved characters. It then checks if there is nothing left to read, and stuff has already been read (ie `data` has a length), then print the data.
What I expect the output to be is (if the input string in `03:255,255,255`):
```
03:255,255,255
```
What I actually get is:
```
0
3
:
2
5
5
,
//and so on
```
That is becuase, for some reason, even though `ble.available()` should return a number not 0 at the if statement, it returns 0 and therefore the statement will always become true.
The only way I've fixed this is by adding in a little delay at the end of the loop. Whether that be:
```
delay(10)
```
or even this, in the while loop:
```
Serial.println(ble.available()) //This introduces enough delay somehow
```

Without having to modify my app, can I pull this off without using a delay? With delays it seems hacky especially because for all I know, for older or newer devices this delay could be too high or too low.

body:
Serial does not transmit data as one bunch, but byte by byte. There can easily be some little delays introduced, especially, when transmitted via a packaged protocol like bluetooth, long enough, for the Arduino to not see any new data in its buffer. Also the transmission needs some time, depending on the baudrate. When you read faster from the buffer, than you receive, you will encounter an empty buffer after every byte.

Now with that information look at your code:

    void loop()
    {
        while (ble.available() > 0)
        {
            data += (char)ble.read();
        }

        if (ble.available() <= 0 && data.length() > 0)
        {
            ble.println(data);
            //do stuff
            data = "";
        }
    }

Let's assume, the Arduino receives one byte, then a little pause happens, then the next data is received. The code will go into the while loop and read the received byte from the serial buffer. To stay in the while loop, the next byte has to be received in the execution time of the code inside of the while loop. That is incredible short. So after one byte there is nothing more inside the buffer, thus the while loop exits, because `ble.available()` returns zero. Then the if statement is executed, also rather fast. Most likely, `ble.available()` will still return zero. But you already put a character into the buffer, so the if statement is executed.

The delay solves your problem because then you read way slower than you receive. The data is mainly received while the delay runs. Then the rest of your code can read, what was already received and put into the buffer.

**What to do instead of `delay()`: You need to make sure, that you always read a full message. There are different ways, depending on your requirements. If your messages always have the same length, you could wait, until the specified number of characters was received, and only then read them. But that will fail, if you for some reason (for example a reset of the Arduino) receive a partial message, which would cause a misalignment. You could clear the receive buffer, when you read a full message, that might help, if your data transmissions don't happen to often.

You could try to parse the incoming data according to the message format (which needs to stay constant for this purpose), like:

    Read a number.
    If it has a colon following it, it is a new message.
    Then read number
        read comma
        read number
        read comma
        read number
    Repeat.

For this purpose it would be fitting to read every byte, that gets received, and write then into your own circular buffer. You can then continuously add newly received characters at the end, while removing the already parsed messages from the start of the buffer.

---

You see, these ways have caveats and might be convoluted. The easiest way would be to add a delimiter/terminator to your messages, though from your question it sounds, as if this is not possible for you currently.

Note:
- None of the above is specific to `SoftwareSerial`. It's the same for hardware `Serial`.
- I suspect the code worked your ESP, because you had some other code there, which introduced a big enough delay (just like your `delay()` call)


message:
Best Data model/Concept to Store Multi-Day Alarm for clock?

I'm writing a multiday day alarm program for a project.

I'm not sure how I want to store the format of each of 10 alarms....I need to store it...in SPIFFS retrieve it(at boot) and then compare it to the current day of the week and time so as to fire off the alarm..I was thinking of storing it in a 10 member array.

First alarm would be every day at 2PM and the second is turned off but would be Mon tues Thursday at 10AM. was going to use strtok_r to extract all of the pieces and compare them every minutte to see if an alarm is needed.

Every minute

```{"1|M|T|W|T|F|S|S|14|00","0|M|T||T|||S|10|00"}```

body:
I would suggest a bit field for storing the days of the week when the
alarm is supposed to fire:

* bit 0: fire on Sundays
* bit 1: fire on Mondays
* ...

This numbering is meant to match the one of `DateTime::dayOfTheWeek()`.

Pack this, together with the hour and minute of the alarm, in a `struct`
(or a `class` if you prefer). Maybe add a boolean to tell whether the
alarm is active. For example:

```c++
struct Alarm {
    bool is_on;
    uint8_t days;  // bitfield: 0 = Sunday
    uint8_t hour;
    uint8_t minute;
    bool matches(DateTime) const;
};

bool Alarm::matches(DateTime t) const {
    bool day_matches = days & (1 << t.dayOfTheWeek());
    return day_matches && t.hour() == hour && t.minute() == minute;
}
```

Then `if (alarm.is_on && alarm.matches(rtc.now()))`, the alarm fires.


body:
That would work. Though I feel like your solution isn't easily readable by humans, and also not easily readable by machines.

Removing the `|`s, making the data a fixed length, and putting each alarm on separate line, would help with both. You'd get something like
```
ON  MTWTFSS 14:00
OFF MT T  S 10:00
````
Because the data-string is of a fixed length, you know where the data you want is inside the string. So your code can, for example, check the 7th character, to see if it needs to turn on/off on Wednesday. Or check the 13th and 14th character to get the hour. And so on.

But you'd have to decide what's important to you. Human readability, machine parseability, compactness (storing it as binary data, like Edgar said), standardized format (Cron-style), Extensibility (for example the option to add seconds, somewhere in the future), ease of implementing.


message:
Laser tripwire and LDR

I am planning to make a laser tripwire but I have an issue. Let me explain what I am trying to do:

Making a laser tripwire is actually pretty easy at its core. You just need an LDR and a laser diode. You look at the normal results of the LDR; it's usually around 60.

When the laser hits the LDR, it's usually around 600 so you write an `if` statement saying if the LDR value is below 500, power the LED or buzzer.

But there is an issue here. The LDR module must be connected to Arduino with cables for signaling. I don't want that. Luckily, I have a Bluetooth module but I have no idea how to use it for sending signal to my Android phone. I know how to send signals though. So to simplify things:

---
Can I send any kind of signal to my phone with Bluetooth (I am using an app called `Arduino Bluecontroll` but I can upload a different app if necessary)? If yes, how?

body:
> Can I send any kind of signal to my phone with Bluetooth?

You have an HC-06, which is a bluetooth Serial (UART) bridge. Thus the bluetooth device exposes the profile for a serial terminal. You can only transmit serial data. It doesn't work for HID input to the smatphone or audio. The Bluecontrol app seems to use serial. So that is not a problem.

To get the communication to work, you need to pair the HC-06 with your phone. The actual connection is then established by the app. It will send serial data to the HC-06, which will output it on its TX pin. Serial communication on its RX pin will be transmitted back to the app.

You need to test, for which baudrate the HC-06 is configured. For that write a test sketch, you use an extra serial interface (either another hardware interface or SoftwareSerial) for the HC-06 and send every byte, that you receive from it, to your PC, so that you can see, what the Arduino receives. Try different standard baudrates (like those, which are listed in the serial monitor), until you find the one, which gives you the correct output.

When that works, you can write your sketch to read the commands from the HC-06 serial interface and act accordingly. How exactly that works depends on the data, that the app is sending. Most likely is sends ASCII encoded text, each message terminated by a newline character `\n`. In that case you could read the data into a buffer byte by byte, when they arrive. When you read a newline character, you know, that you received a full message. Then you can process it and act accordingly.


message:
Serial Communication to Control Stepper

**I wanted to add an updated code after I have finished it to help others in the future if they are ever looking for it.

EDIT AT END OF QUESTION AFTER ANSWER AND CODE UPDATE.**

I currently have an Uno with a CNCBoard Hat.

I am running a program on my RPi and sending a value through serial to the Arduino. I am receiving what I believe is a string, converting it to an `int` using `toInt()` (I found this solution somewhere). I then want to write that value to the stepper I have connected.

I know the stepper works, because if I run a simple test program such as this one:

```c++
const int stepX = 2;
const int dirX  = 5;

const int stepY = 3;
const int dirY  = 6;

const int stepZ = 4;
const int dirZ  = 7;

const int enPin = 8;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepX, OUTPUT);
  pinMode(dirX, OUTPUT);
  pinMode(enPin, OUTPUT);

  digitalWrite(enPin, LOW);
  digitalWrite(dirX, HIGH);
  digitalWrite(dirY, LOW);
  digitalWrite(dirZ, HIGH);
}

void loop() {
  // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for (int x = 0; x < 200; x++) {
    digitalWrite(stepX,HIGH);
    delayMicroseconds(1000);
    digitalWrite(stepX, LOW);
    delayMicroseconds(1000);
  }
   delay(1000); // One second delay
}
```

The stepper rotates as the program describes. Where 200 is the pulse count.

The program I am currently trying to use is:

```c++
// defines pins numbers
//Front left wheel
const int stepX = 2;
const int dirX  = 5;

//Front right wheel
const int stepY = 3;
const int dirY  = 6;

//Back left wheel
const int stepZ = 4;
const int dirZ  = 7;

//Back right wheel
const int stepA = 12;
const int dirA  = 13;

const int enPin = 8;

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

  // Sets the two pins as Outputs
  pinMode(stepX, OUTPUT);
  pinMode(dirX, OUTPUT);

  pinMode(stepY, OUTPUT);
  pinMode(dirY, OUTPUT);

  pinMode(stepZ, OUTPUT);
  pinMode(dirZ, OUTPUT);

  pinMode(enPin, OUTPUT);

  digitalWrite(enPin, LOW);
  digitalWrite(dirX, HIGH);
  digitalWrite(dirY, LOW);
  digitalWrite(dirZ, HIGH);
  digitalWrite(dirA, HIGH);
}

void loop() {
  String YpulseEncode;
  if (Serial.available() > 0) {
    YpulseEncode = Serial.readStringUntil('\n');
    int yMove1 = YpulseEncode.toInt();
    //XpulseCalc = Serial.read();

    //Serial.print("YpulseCalc: ");
    Serial.println(yMove1 * (-1));
    //Serial.print("YpulseCalc +: ");
    //Serial.println(YpulseCalc
    //Serial.print("XpulseCalc: ");
    //Serial.println(XpulseCalc);
    delay(5000);
    Serial.end();
    if (yMove1 != 0) {
      // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      for (int x = 0; x < (yMove1); x++) {
        digitalWrite(stepX, HIGH);
        delayMicroseconds(1000);
        digitalWrite(stepX, LOW);
      }
    }
  }
}
```

The number I am receiving from the RPi is -267. So when the serial monitor shows it, it is 267. I want to send the number 267 pulses to the stepper motor.

**EDIT - UPDATED CODE**

```#include <AccelStepper.h>

AccelStepper yStepper(AccelStepper::DRIVER, 2, 5);

// defines pins numbers
//Front left wheel
const int stepX = 2;
const int dirX  = 5;

//Front right wheel
const int stepY = 3;
const int dirY  = 6;

//Back left wheel
const int stepZ = 4;
const int dirZ  = 7;

//Back right wheel
const int stepA = 12;
const int dirA  = 13;

const int enPin = 8;

void setup() {
  yStepper.setMaxSpeed(800);
  yStepper.setAcceleration(400);

  Serial.begin(9600);

  // Sets the pins as Outputs
  pinMode(stepX, OUTPUT);
  pinMode(dirX, OUTPUT);

  pinMode(stepY, OUTPUT);
  pinMode(dirY, OUTPUT);

  pinMode(stepZ, OUTPUT);
  pinMode(dirZ, OUTPUT);

  pinMode(enPin, OUTPUT);

  digitalWrite(enPin, LOW);
  digitalWrite(dirX, HIGH);
  digitalWrite(dirY, LOW);
  digitalWrite(dirZ, HIGH);
  digitalWrite(dirA, HIGH);
}

void loop() {

  String YpulseEncode;
  if (Serial.available() > 0) {
    YpulseEncode = Serial.readStringUntil('\n');
    int yMove1 = YpulseEncode.toInt();

if (yMove1 < 0) {
    int yMoveNew = yMove1 * (-1);

    //XpulseCalc = Serial.read();
    //Serial.print("YpulseCalc: ");
    Serial.println(yMove1 * (-1));
    //Serial.print("YpulseCalc +: ");
    //Serial.println(YpulseCalc
    //Serial.print("XpulseCalc: ");
    //Serial.println(XpulseCalc);
    delay(2000);

      // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      //for (int x = 0; x < yMoveNew; x++) {
      yStepper.move(yMoveNew);
      yStepper.runToPosition();
        //digitalWrite(stepX, HIGH);
        delayMicroseconds(1000);
        //digitalWrite(stepX, LOW);
      //}
    }
  }
}
```

body:
You have 2 problems, which are already mentioned in the comments:

- You call `Serial.end()` after you received one line. That will stop the Serial hardware. Thus the code will only receive one line and then ignore any data from Serial. I don't think, that you want this. So just remove the `Serial.end()`.

- `yMove1` is negative, while your `for` loop has the condition `int x = 0; x < (yMove1); x++`. But zero is always higher than a negative number. Thus the `for` does not run at all (the condition `x < yMove1` is `false`, when `yMove1` is negative). I don't quite understand, why you want to provide a negative number. You don't have any code for direction reversing. In the current state I would suggest just not sending a negative number. I cannot say more, because it is unclear, what exactly you want here.

---

Note:
- The parentheses around `yMove1` inside the `for` loop condition is not needed.
- The `if` statement `if (yMove1 != 0)` is not needed. If `yMove1` is zero, the `for` loop  will just not run, because it starts with zero.


message:
MPU6050 FIFO overflow and freezing problems

I'm using the sensor MPU6050 to control movements of my robotic arm. The code works fine when it is a standalone program but I keep encountering 'FIFO overflow' when the code is compiled into the main program. This is the code that I am using:

```c++
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif
    MPU6050 mpu;

    RF24 radio(9, 8);  // CE, CSN

    const byte address[6] = "00001";

    const int AccReadings = 10;
    //Wrist Roll
    int DataX[AccReadings];
    int WRIndex = 0;
    int WRtotal = 0;
    int WRaverage = 0;
    //Wrist Pitch
    int DataY[AccReadings];
    int WPIndex = 0;
    int WPtotal = 0;
    int WPaverage = 0;
    //Shoulder Lift
    int DataY2[AccReadings];
    int SLIndex = 0;
    int SLtotal = 0;
    int SLaverage = 0;
    //Elbow Lift
    int ELaverage = 0;
    //Arm Rotation
    int ARaverage = 0;
    float correct;

    #define OUTPUT_READABLE_YAWPITCHROLL
    #define INTERRUPT_PIN 2
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    struct Sensor_Data
    {
      int WristRoll;
      int WristPitch;
      int ShoulderLift;
      int ElbowLift;
      int ArmRotation;
    };
    Sensor_Data data;

    //Interrupt Detection
    volatile bool mpuInterrupt = false;
    void dmpDataReady()
    {
      mpuInterrupt = true;
    }

    void setup()
    {
      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();

      //Zero-fill Arrays
      for (int i = 0; i < AccReadings; i++)
      {
       DataX[i] = 0;
      }
      for (int j = 0; j < AccReadings; j++)
      {
       DataY[j] = 0;
      }
      for (int k = 0; k < AccReadings; k++)
      {
       DataY2[k] = 0;
      }

      #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000);
      #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
      #endif

      Serial.begin(115200);
      while (!Serial);

      mpu.initialize();
      pinMode(INTERRUPT_PIN, INPUT);
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(49);
      mpu.setYGyroOffset(-18);
      mpu.setZGyroOffset(9);
      mpu.setZAccelOffset(4427);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }
      else
      {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        // Serial.print(F("DMP Initialization failed (code "));
        //Serial.print(devStatus);
        //Serial.println(F(")"));
      }
    }

    void loop()
    {
      /*smoothWR();
      movementWR();
      smoothWP();
      movementWP();
      smoothSL();
      movementSL();*/
      ElbowMovement();
      radio.write(&data, sizeof(Sensor_Data));
    }

    void smoothWR()
    {
      WRtotal = WRtotal - DataX[WRIndex];
      DataX[WRIndex] = analogRead(A0);
      WRtotal = WRtotal + DataX[WRIndex];
      WRIndex = WRIndex + 1;

      if (WRIndex >= AccReadings)
      {
        WRIndex = 0;
      }

      WRaverage = WRtotal / AccReadings;
      //Serial.println(WRaverage);
    }

    void movementWR()
    {
      WRaverage = map(WRaverage, 278, 419, 0, 180);
      data.WristRoll = constrain(WRaverage, 0, 180);
      //Serial.println(data.WristRoll);
    }

    void smoothWP()
    {
      WPtotal = WPtotal - DataY[WPIndex];
      DataY[WPIndex] = analogRead(A1);
      WPtotal = WPtotal + DataY[WPIndex];
      WPIndex = WPIndex + 1;

      if (WPIndex >= AccReadings)
      {
        WPIndex = 0;
      }

      WPaverage = WPtotal / AccReadings;
      //Serial.println(WPaverage);
    }

    void movementWP()
    {
      WPaverage = map(WPaverage, 280, 421, 0 , 135);
      data.WristPitch = constrain(WPaverage, 0, 135);
      //Serial.println(data.WristPitch);
    }

    void smoothSL()
    {
      SLtotal = SLtotal - DataY2[SLIndex];
      DataY2[SLIndex] = analogRead(A2);
      SLtotal = SLtotal + DataY2[SLIndex];
      SLIndex = SLIndex + 1;

      if (SLIndex >= AccReadings)
      {
        SLIndex = 0;
      }

      SLaverage = SLtotal / AccReadings;
      //Serial.println(SLaverage);
    }

    void movementSL()
    {
      SLaverage = map(SLaverage, 410, 270, 0 , 180);
      data.ShoulderLift = constrain(SLaverage, 35, 180);
      //Serial.println(data.ShoulderLift);
    }

    void ElbowMovement()
    {
      // if programming failed, don't try to do anything
      if (!dmpReady) return;

      // wait for MPU interrupt or extra packet(s) available
      while (!mpuInterrupt && fifoCount < packetSize)
      {
        if (mpuInterrupt && fifoCount < packetSize)
        {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }
      }

      // reset interrupt flag and get INT_STATUS byte
      mpuInterrupt = false;
      mpuIntStatus = mpu.getIntStatus();

      // get current FIFO count
      fifoCount = mpu.getFIFOCount();

      // check for overflow (this should never happen unless our code is too inefficient)
      if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024)
      {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        fifoCount = mpu.getFIFOCount();
        Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
      }
      else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT))
      {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        // Get Yaw, Pitch and Roll values
    #ifdef OUTPUT_READABLE_YAWPITCHROLL
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        // Yaw, Pitch, Roll values - Radians to degrees
        ypr[0] = ypr[0] * 180 / M_PI;
        ypr[1] = ypr[1] * 180 / M_PI;
        ypr[2] = ypr[2] * 180 / M_PI;

        // Skip 300 readings (self-calibration process)
        if (int l = 0; l <= 300) {
          correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
          l++;
        }
        // After 300 readings
        else {
          ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
          // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
          ELaverage = map(ypr[0], -90, 90, 0, 180);
          data.ElbowLift = constrain(ELaverage, 30, 110);
          ARaverage = map(ypr[1], -90, 90, 0, 180);
          data.ArmRotation = constrain(ARaverage, 0, 180);
          //Serial.println(data.ElbowLift);
          Serial.println(ypr[1]);
        }
    #endif
      }
    }
```

Is there any ways to get rid of the FIFO overflow? Also When I tried to used Jeff Rowberg's example code MPU6050_DMP6 the program froze after a few seconds. Is there any solution to that?

This is the example code that I am using:

```c++
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif
    MPU6050 mpu;
    float correct;
    int j = 0;

    #define OUTPUT_READABLE_YAWPITCHROLL
    #define INTERRUPT_PIN 2
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    //Interrupt Detection
    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
      mpuInterrupt = true;
    }

    void setup()
    {
      #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      Wire.begin();
      Wire.setClock(400000);
      #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
      #endif
      Serial.begin(38400);
      while (!Serial);

      mpu.initialize();
      pinMode(INTERRUPT_PIN, INPUT);
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(17);
      mpu.setYGyroOffset(-69);
      mpu.setZGyroOffset(27);
      mpu.setZAccelOffset(1551);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }
      else
      {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        // Serial.print(F("DMP Initialization failed (code "));
        //Serial.print(devStatus);
        //Serial.println(F(")"));
      }
    }

    void loop()
    {
      if (!dmpReady) return;
      if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer))
      {
        #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                if (j <= 300)
                {
                  correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
                  j++;
                }
                else
                {
                  ypr[0] = ypr[0] - correct;
                  Serial.print("ypr\t");
                  Serial.print(ypr[0] * 180/M_PI);
                  Serial.print("\t");
                  Serial.print(ypr[1] * 180/M_PI);
                  Serial.print("\t");
                  Serial.println(ypr[2] * 180/M_PI);
                }
        #endif
      }
    }
```

body:
I have used an MPU6050 successfully in my autonomous robot project for several years now, so I have some knowledge of the subject

If your code is freezing intermittently, it may well be the infamous bug in the Arduino 'Wire' code that causes the I2C receive and/or transmit functions to block under certain conditions.

Take a look at some of my posts on 'Paynter's Palace'.  You'll find there is a long history of intermittent I2C hangup problems with the stock 'Wire' library.  The good news is that this problem was (sorta) fixed.  You can now use the stock 'Wire' library, but you still have to manually enable the watchdog timeout value to get the transmit/receive functions to unblock if they get stuck.

See [this post][1] regarding the Wire library bug fix. You will find the following lines in setup():

    Wire.setWireTimeout(3000,true);
     wireTimeoutCount = 0;
     Wire.clearWireTimeoutFlag();

These lines set a reasonable timeout value (3000 uSec in my case), reset a local variable (wireTimeoutCount) I used for debug, and reset the new Wire library timeout flag.

Note that you'll need to ensure you are using the latest Wire library code.  If the above 'Wire.setWireTimout(3000, true);' compiles, then you are using the latest library.  If it doesn't, then you'll have to get the latest one.

Hope this helps,

Frank

  [1]: https://www.fpaynter.com/2020/07/i2c-hangup-bug-cured-miracle-of-miracles-film-at-11/


message:
How to enable exception handling on the Arduino Due?

While the question [here][1] gives some hints, the solution provided there does not directly work on the Due, since it uses a different compiler and toolkit. Also, the Due has more than enough flash for most projects, so that the extra code required for exception handling is acceptable. But as with the AVR-based boards, "-fno-exceptions" is automatically added to the compiler flags when using the Arduino IDE, preventing any throw or catch instructions to compile.

How can I enable exception support on the Due?

  [1]: https://arduino.stackexchange.com/questions/65392/exception-handling-with-the-arduino-ide

body:
First, we must make sure the "-fno-exceptions" compiler flag is overwritten with "-fexceptions". In addition, we must link a separate library that includes the compiler support functions for stack unwinding.

Navigate to `C:\Users\<UserName>\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.12` and create a new file `platform.local.txt` with this content:

```

compiler.cpp.extra_flags=-fexceptions
linker.elf.extralibs=-lsupc++

recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb {compiler.c.elf.flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group {compiler.combine.flags} {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -lgcc {linker.elf.extralibs}
```

The last line should match the corresponding line in `platform.txt`, with an extra `{linker.elf.extralibs}` at the end (upgrading the toolkit might update that line, so you may need to compare the other parameters).

These lines add the `-fexceptions` to the compiler command line and the `supc++` library to the linker input (otherwise you'll get errors about unresolved externals). After these changes, you can rebuild your project and use exception handling.

**Some usage hints**

The exception support on the Due requires about 40k of extra flash memory. Given it has 512k, this is usually acceptable. A bit of extra RAM is also used, but that seems to be small enough as well.

Since there are no standard exception classes defined (and the ArduinoSTL library doesn't compile on the due out-of-the-box), you'll have to write your own exception classes, i.e something like this:

```c++
class Exception
{
  private:
  const char* _msg;
  public:
  Exception(const char* msg)
  {
    _msg = msg;
  }

  const char* Message() const
  {
    return _msg;
  }
};
```

Use as:
```c++

void ThrowExceptionFunc()
{
  throw Exception("Something bad happened");
}

void ValidateExceptionHandling()
{
  try
  {
    ThrowExceptionFunc();
    Serial.print("Exception was not thrown:");
  }
  catch(Exception& ex)
  {
    Serial.print("Exception happened:");
    Serial.println(ex.Message());
  }
}

```

Note that **Unhandled exceptions will terminate the program**. An unhandled exception will cause the due to output a corresponding message to the serial console and then enter a deadend fail state.


message:
defining a macro with variables

I am working on Marlin 3D program. I made some changes for xyz prop and I do not make a definition as `#define PRB_GCODE_END "G92 X-" XOFF "Y" XOFF "Z" ZOFF "\ n"` to send the final xyz coordinates as gcode at the end of the promulgation procedure. It is required. If anyone has any idea how to use float type variables during macro definition please help.

```c++
void _user_gcode_exe(const char * const cmd) {
  lcd_return_to_status();
  enqueue_and_echo_commands_P(cmd);
}

void user_gcode_exe_1() {
  float XOFF = (25.00 + PRB_XOFFSET + (TOOL_DIA / 2.00));
  float YOFF = (25.00 - (PRB_YOFFSET + (TOOL_DIA / 2.00)));
  float ZOFF = (10.00 + PRB_ZOFFSET);

#define PRB_GCODE_END "G92 X-" XOFF " Y" XOFF " Z" ZOFF "\n"

#define PRB_GCODE "M117 Z-XY Probing now..\nG38.2 F120 Z-20.00\nG92 X0.00 Y.00 Z0.00\nG0 Z5.00 F1200\nG0 X-20.00 F1200\nG0 Z-5.00 F1200\nG38.2 F120 X25.00\nG92 X0.00\nG0 X-5.00 Y-25.00 F1200\nG0 X15.00 F1200\nG38.2 F120 Y25.00\nG92 Y0.00\nG0 Y-5.00 F1200\nG0 Z10.00 F1200\nG0 X-25.00 Y25.00 F1200\n"

#define MSG__OK "M117 Z-XY Probing done..\n"
  _user_gcode_exe(PSTR(PRB_GCODE PRB_GCODE_END MSG__OK));
}
```

While defining `PRB_GCODE_END`, ensuring that float type variables are included in this definition. For example: Considering that the variables `XOFF`, `YOFF` and `ZOFF` are calculated as 12.85, 11.25 and 10.50 respectively. `PRB_GCODE_END` should occur as follows:
`G92 X-12.85 Y 11.25 Z10.50 \n`

body:
You can't. Variables and macros are completely different concepts and handled by completely different parts of the compiler toolchain.

Instead you will need to build your string up into a char array (or whatever format the `_user_gcode_exec()` function accepts) with the likes of sprintf.


message:
Unsure if my NEMA 14 stepper motor wiring is correct

So I'm pretty brand new to Arduino's in general so I do apologize if its a simple mistake. But basically I'm trying to use the <Stepper.h> library to control my NEMA 14 motor on an arduino with a CNC shield and a A4988 driver. Specifically at this moment I am testing out this code:

```
/*
 Stepper Motor Control - one step at a time

 This program drives a unipolar or bipolar stepper motor.
 The motor is attached to digital pins 8 - 11 of the Arduino.

 The motor will step one step at a time, very slowly.  You can use this to
 test that you've got the four wires of your stepper wired to the correct
 pins. If wired correctly, all steps should be in the same direction.

 Use this also to count the number of steps per revolution of your motor,
 if you don't know it.  Then plug that number into the oneRevolution
 example to see if you got it right.

 Created 30 Nov. 2009
 by Tom Igoe

 */

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount);
  stepCount++;
  delay(500);
}
```

Now unfortunately when I run this code I can hear the motor whirring, but it doesn't revolve. I'm guessing that either I wired the motor incorrectly, or because I'm using a CNC shield the pins in the code should be different. Also, I've checked the voltage going into the driver in accordance with [this website][2]. I've also attached pictures below of my setup to just to make everything clear:
1. Picture of CNC shield atop Arduino board with wires connected as follows:
[![CNC shield][3]][3]

2. Picture of Stepper motor I'm using:
[![NEMA 14 Stepper motor][4]][4]

3. Specifications of the NEMA 14 motor I'm using:
[Can be seen here][5]

I'm sorry for the convoluted post but I am kind've stuck so any help would be greatly appreciated and if there's any more info needed to help clarify my problem I will update the post or reply to your comments. Thanks!

  [1]: https://i.stack.imgur.com/o8o8b.png
  [2]: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/
  [3]: https://i.stack.imgur.com/fv6i6.jpg
  [4]: https://i.stack.imgur.com/0gqd3.png
  [5]: https://motion.schneider-electric.com/downloads/quickreference/NEMA14.pdf

body: I would first check with a multimeter which pins from the the shield have voltage. Draw on a piece of paper the sequence of pin activated by the driver and check your motor connection. Probably you have just inverted two wires, this would also explain the whirring sound.


message:
Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers

I intend to power three ATTiny45 chips (each requiring around 3.5V) in parallel with 2 pill batteries (namely Maxwell's **CR2032**) in series (which would come to around 6V). They will each play a sound with a piezo buzzer when a button is pressed.

Now maybe my thinking is wrong but I think dividing the power between the three chips may result in only around 2V delivered to each chip? Does the other components play a role?

So my question is this:

 - How much voltage is delivered across elements in parallel?
 - What changes should I do to the wiring to make the most of the voltage?
 - What kind of resources should I get to make sense of what to do? Cause I thought I was more advanced but this stomped me.

In any case I've added the schematic of what's intended.

*[This schematic used to contain resistors to pull the switch but this need was removed with the help of jsotola's `input_pullup` comment]*

<!-- 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/yPbcu.png)

<!-- End schematic -->

body:
If you connect the AtTiny chips in parallel, they will all receive the full voltage from your battery. If you exceed the current output of your battery the voltage will droop.

If the AtTiny chips need 3.5V and you give them 6V instead, it will likely destroy the chips.

The short answer: Don't try to drive microcontrollers directly from batteries. You should get a 3.5V switching power supply. Then you will be able to drive all 3 chips cleanly from your battery. (Switching power supplies are very efficient. They don't waste much power at all.)

Note that button cells produce very small total power (in milliwatt/hours) so they won't drive your processors for very long before they are exhausted. I suggest using 4 AA batteries and a switching regulator instead. The 4 AA batteries would give you a 6V VIN to your voltage regulator, but a lot more total power.


message:
avrdude fuse error when programming ATMEGA328 without crystal

I built several boards with an ATMEGA328 and no crystal a couple of years ago. I programmed them successfully with a bootloader using usbasp, and with a sketch using the Arduino serial interface. I have now made some more, but I get an error message from AVRDUDE when I try to burn the bootloader:

>  ***failed;
> avrdude: WARNING: invalid value for unused bits in fuse "efuse", should be set to 1 according to datasheet
> This behaviour is deprecated and will result in an error in future version
> You probably want to use 0xfd instead of 0x05 (double check with your datasheet first).

I followed the instructions [here][1] and I am using the hardware configuration archive referenced on that page: breadboard-1-6-x.zip.

If I reprogram the bootloader on a device that does have a crystal, it works if I select Arduino Pro/Pro Mini (3.3V, 8MHz), but fails with the message above if I select the breadboard specified in the boards.txt from  breadboard-1-6-x.zip.

There are no other error messages, but... if I turn on verbose, it works.. turn verbose off and it stops working again. Maybe verbose mode modifies the timing enough to make it work.

I know that you can use the -B option to slow down avrdude when you run it from the command line: is there a way of doing the same thing from within the Arduino environment?

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard

body:
The ATMega328P [datasheet][1] has the following table in it:

[![ATMega328P datasheet extended fuses excerpt.][2]][2]

The top 5 bits of the of the Extended Fuse Byte are default `1` and are reserved.  You're not really supposed to change them, since they might be used in the future for a 328P-like part and setting them to something other than `1` could have unexpected results.  In the 328PB variant bit number 3 **is used** for "Disable Clock Failure Detection".

The lower three bits of 0xFD and 0x05 are both 0b101.  In other words, taking into account only the bits you should be setting, for the BODLEVELn fuses, they would have the same effect.  But you are being WARNED that you should be using 0xFD rather than 0x05 for the above reason.

The boards.txt that comes in the breadboard-1-6-x.zip has a line that looks like this:
> atmega328bb.bootloader.extended_fuses=0x05

You *could* change this yourself by editing the file, but really for what you're doing I'd recommend [MCUdude MiniCore][3] which is comparatively up to date.  If nothing else, its boards.txt file has been [written with the correct fuse values][4].  You can see there for a plain 328P (not PB) which does not support clock failure detection, the CFD bit is just hardcoded to 1 in the file.

The message you're seeing is a "WARNING" through, rather than "ERROR".  The distinction being that warnings don't actually stop you from continuing.  It is likely that if you're having a problem isn't not really because they've incorrectly specified the high-order bits of the fuse.  If it's halting, it may be arduino-builder see a non-zero exit code for avrdude and thinking this means "ERROR" rather than "WARNING", in which case this problem will go away if you edit the boards.txt file (or adopt MiniCore) such that no longer produces the warning.

Unless you've brought the effective system clock below 1MHz, probably lower still, it's not likely that you'll need to change from the default ISP clock rate.  If you do though, that can also be done by editing board package files.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf
  [2]: https://i.stack.imgur.com/b4qm7.png
  [3]: https://github.com/MCUdude/MiniCore
  [4]: https://github.com/MCUdude/MiniCore/blob/v2.0.9/avr/boards.txt#L173


message:
Host a webserver on esp32d that has a hyperlink that triggers an ardiuno song through a buzzer

I would like to use my ESP32D to create a wireless access point and host an html page that has a hyperlink and a few other things on it that triggers an arduino song (rickroll), and plays it through a buzzer.

I just need to know how to host the webserver and make the trigger hyperlink work, right now the html is set to send "trigger" whenever the link is pressed.

html file https://pastebin.com/sGmPPVYG

(Arduino-song)https://github.com/robsoncouto/arduino-songs/blob/master/nevergonnagiveyouup/nevergonnagiveyouup.ino

body:
This is a partial answer. I assume you already know how to build a Web
server on you ESP32, and how to react to client requests. If not, there
are tutorials available on the Internet. Here I will specifically
discuss the issue of the hyperlink.

You wrote:

```html
<a href="trigger">Click Here To Trigger The Rick Roll!/a>
```

Not only the closing tag is incorrect (it should be `</a>`), but such a
link is likely not what you want. The semantics of an hyperlink is “go
fetch that resource and display it here, replacing the current page”.
Unless you do have a displayable resource (Web page, image...) on your
server actually named “trigger”, you do not want an hyperlink. You want
a clickable item that may look like an hyperlink and, when clicked,
triggers a request to the server, but without replacing the current
page.

So I would start by replacing the link by a generic container:

```html
<div id="trigger">Click Here To Trigger The Rick Roll!</div>
```

Then, style it like a link. I don't quite like the underlining, but you
can add it if you wish:

```css
#trigger {
  color: blue;
  cursor: pointer;
}
```

Then, within a `<script>` tag, add the desired behavior:

```javascript
window.onload = () => {
    document.getElementById("trigger").onclick = () => {
        fetch("trigger", { method: "POST" });
    };
};
```

When the user clicks on the element, the client will send a “POST”
request to the server for the “trigger” resource, and the server can
react to this by playing the song. You could use a “GET” request
instead, but that would violate the semantics of “GET”, which is to
retrieve a resource from the server, without affecting its state.


message:
What pins to use on a Teensy to get data from multiple peripherals?

I'm using a Teensy to keep records on the location, speed, altitude, and direction of a weather balloon I'm hoping to launch. I have an Adafruit LSM9DS1 and a Ublox NEO-M8N with compass (HMC5833L) so to get all the data from these I need to connect to a total of 6 pins to get the data. I also want to use a Pixhawk radio telemetry unit to send these data to the ground so I can see them in realtime, so that will involve at least 2 more pins I believe.

The Teensy appears to have plenty of IO pins for all of this, but I've noticed that in all the libraries I've installed to try to use with these things, the pins to use aren't explicitly set. The libraries I've played with include the Adafruit LSM9DS1 library, NeoGPS, Pixhawk Arduino link, RadioHead, Grove HMC5833L, and others. I've been able to get some serial data in by using pins 18 and 19, but I can't attach all the periperhals to the same pin.

It feels like I'm missing something very basic here but I haven't been able to figure out how to use these libraries with inputs on different pins. Even when I look into the code of the libraries themselves, I can't find where the pins are being set. Most of the documentation that mentions which pins things use is written for specific Arduino models, like the Uno, and don't mention the Teensy.

What pins do I use if I want to read and write on more than one peripheral from my Teensy? How can I get data on more than just the two "default pins" that these libraries seem to expect?

body: The first thing to look at when determining which pins to connect a peripheral to is what protocol that peripheral uses - e.g. I2C, SPI, analog voltage via ADC, etc. The Teensy pinout for the version you have (e.g. [the 3.2 pinout](https://www.pjrc.com/store/teensy32.html#pins)) lists which pins can function as which protocol functions. For example, pin 19 can act as an analog input (`A5`) or as part of the 0th I2C unit, `SCL0`. Your `LSM9DS1` can use I2C, so you could connect it to that I2C unit. Typically Arduino libraries will default to using the default peripheral type. In Arduino, an I2C bus is called `Wire`, so a library for an I2C device will typically use the `Wire` device. Well-written libraries will also let you pass in your own peripheral, which is how you change the pins. Each library will do this differently.


message:
Resistor - Correct value for optocoupler, but dont have that size

I am making a shutter for my camera using a Arduino and an optocoupler.

I understand most of most parts, but unsure about the resistor because I don't have the correct size. 5V will be coming from the Arduino, and the [4N35][1] will need 1.3V 10mA. This leads to a 380Ω resistor.

Now I only have 100Ω, 220Ω, 330Ω, and 1kΩ resistors. I have read I shouldn't use anything lower than 380Ω and only use higher but 1kΩ seem a little too high haha.

Just looking for some pointers please.

  [1]: https://www.vishay.com/docs/81181/4n35.pdf

body:
1kΩ will be just fine. But if you want lower you could take two 1kΩ and place them in parallel - that will give you 500Ω.

BTW - 1kΩ will give you ((5-1.3)/1000=) 3.7mA through the diode of the optocoupler, and 500Ω will give you ((5-1.3)/500=) 7.4mA.


body: And 330 will give you just over 11mA, I'd go with that


message:
ArduinoJSON define as extern

My sketch contains 2 `.h` files. one defines

on 1st `.h` file:

    #define JSON_SIZE_IOT 400
    #define JSON_SIZE_SKETCH 300
    StaticJsonDocument<JSON_SIZE_IOT> paramJSON;
    StaticJsonDocument<JSON_SIZE_SKETCH> sketchJSON;

and other need to define `paramJSON` and `sketchJSON` as `extern`

on 2nd `.h` file:

    extern JsonDocument paramJSON;
    extern JsonDocument paramJSON;

but I get this error:

    error: conflicting declaration 'ArduinoJson6172_91::StaticJsonDocument<400u> paramJSON'
     StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

....

    : previous declaration as 'ArduinoJson6172_91::JsonDocument paramJSON'
     extern JsonDocument paramJSON;

body:
For an `extern` the whole definition has to match the "master" definition.

So if you have:

```c++
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;
```

then you `extern` has to be:

```c++
extern StaticJsonDocument<JSON_SIZE_IOT> paramJSON;
```

Of course you have to make sure your `JSON_SIZE_IOT` is the same for both - so it's best if that comes from a common source.

This is known as *explicit instantiation declaration* and you can read more about it in the [Class template C++ reference](https://en.cppreference.com/w/cpp/language/class_template).


message:
Adding zero padding to decimal values

I want to add zero before the float number like this:

    010.0

The code I'm using is this:

    if(value < 10){
      lcd.print(F("0"));
    }

    lcd.print(value);

But when the value is exactly 10, it adds the zero anyway:

    0010.0

I tried something like this but haven't had any luck:

    if(value < 10 && value != 10){
      lcd.print(F("0"));
    }

* How can I solve this issue?

**- EDIT:**

    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3B, 16, 2);

    #define turnOff 3
    #define turnOn 2
    #define gateStatus 8
    #define btn 4

    float ADC0, current, ADC1, voltage, ADC2, temp, watt;
    int8_t state, btnState, btnPushed, btnToggle, lcdClear;
    uint32_t deBounce = 0;

    void setup() {
      analogReference(EXTERNAL);
      pinMode(turnOff, OUTPUT);
      pinMode(turnOn, OUTPUT);
      pinMode(gateStatus, INPUT);
      pinMode(btn, INPUT_PULLUP);
      pinMode(13, OUTPUT);
      lcd.begin();
    }

    void loop() {
      digitalWrite(13, LOW);
      state = digitalRead(gateStatus);
      btnState = digitalRead(btn);

      if (!btnState) {
        if (millis() - deBounce > 200) {
          btnPushed = 1;
          deBounce = millis();
        }
      }
      if (btnPushed && btnState) {
        btnToggle = 1;
      }
      if (btnToggle && state) {
        digitalWrite(turnOn, HIGH);
        delay(5);
        digitalWrite(turnOn, LOW);
        btnToggle = 0;
        btnPushed = 0;
      }
      if (btnToggle && !state) {
        digitalWrite(turnOff, HIGH);
        delay(5);
        digitalWrite(turnOff, LOW);
        btnToggle = 0;
        btnPushed = 0;
      }

      for (int i = 0; i < 500; ++i) {
        ADC0 += analogRead(A0);
      }
      ADC0 /= 500;
      current = ADC0 * (2.5 / 1023.0);
      current = current / 0.211;

      for (int i = 0; i < 500; ++i) {
        ADC1 += analogRead(A1);
      }
      ADC1 /= 500;
      voltage = ADC1 * (2.5 / 1023.0);
      voltage = voltage * 20.2;

      for (int i = 0; i < 100; ++i) {
        ADC2 += analogRead(A2);
      }
      ADC2 /= 100;
      temp = ADC2 * (2.5 / 1023.0);
      temp = temp * 100.5;

      watt = voltage * current;

      lcd.setCursor(0, 0);
      if(voltage < 10){
        lcd.print(F("0"));
      }
      lcd.print(voltage);
      lcd.setCursor(5, 0);
      lcd.print(F(" V"));

      lcd.setCursor(9, 0);
      if(temp < 10){
        lcd.print(F("0"));
      }
      lcd.print(temp, 1);
      lcd.print((char)223);
      lcd.print(F(" C"));

      if (state) {
        lcd.setCursor(0, 1);
        lcd.print(F("   OUTPUT OFF   "));
        lcdClear = 1;
      }

      else {
        if (lcdClear) {
          lcd.clear();
          lcdClear = 0;
        }
        lcd.setCursor(0, 1);
        if (current < 10) {
          lcd.print(F("0"));
        }
        lcd.print(current);
        lcd.setCursor(5, 1);
        lcd.print(F(" A"));

        lcd.setCursor(9, 1);
        if (watt < 10) {
          lcd.print(F("0"));
        }
        if (watt < 100) {
          lcd.print(F("0"));
        }
        lcd.print(watt, 1);
        lcd.setCursor(14, 1);
        lcd.print(F(" W"));
      }
    }

body:
This looks like a rounding problem. If the number you want to print lies
within the open interval (9.95, 10), the condition `value < 10` is true,
as the number is strictly less than 10. Obviously, `value != 10` is also
true. Yet, `lcd.print(x, 1)` will round the number to the closest
multiple of 0.1, which in this case is 10.

I see no better solution than handling the rounding yourself. I would
use integers for the comparison, as they avoid all rounding issues:

```c++
// Print a float to the LCD in 2.1 format (xx.x), left padded with a
// zero if needed. Assume x < 100.
void printPadded(float x)
{
    // Left pad.
    int i = round(x * 10);
    if (i < 100) lcd.write('0');

    // Print the rounded value.
    lcd.print(i * 0.1, 1);
}
```


message:
Will the L9823 work at 3.3 V with Wemos boards?

Or is it 5 V only?

https://www.st.com/en/automotive-analog-and-power/l9823.html

I see in the data sheet it says under Absolute Maximum:
> Supply Voltage:  VDD -0.3 V to 7 V

Then, under Electrical Characteristics:
> 4.5 V < VDD < 5.5 V; unless otherwise specified.

Is the Electrical Characteristics section just listing values for an example voltage of 5 V, or does the chip need 5 V to work properly?

body: No. The undervoltage puts it in reset at 3.95V per the ST data sheet. It is a  5v only part with a wide tolerance on VCC. It was designed many years ago as an automotive part. It is a very nice part and performs well.


body:
The *Absolute Maximum* section in a datasheet describes what will damage a component, or shorten its life span; it does not state the acceptable range of values that will make the component work as expected. It is not a design guideline.

You can deduce from these Absolute Maximum data that a Vdd of 3.3 V will not damage the IC, but not that it will work well at that voltage.

In this case, the datasheet says that all Electrical Characteristics *are specified at* a Vdd of about 5 V. This by itself does not necessarily mean the IC won't work at lower voltages, but it is a hint.

But, further on in the Electrical Characteristics, it is stated that the IC could reset at any Vdd between 2.5 V and 3.95 V, so the IC will very probably not work reliably at 3.3V.


message:
Problems with green TWI (I2C) port on Arduino Braccio Shield

Summary: The green TWI/I2C port on my Braccio shield I2C port hasn't worked for me so far. Looking for advice or information please.

Detail:
I'm using the [Arduino (Tinkerkit) Braccio robot arm][1] for self education. It comes with a Uno based [Braccio Shield][2]. Tinkerkit no longer seems to be in business and documentation is a bit scarce. The shield uses KF2510 style connectors for servos (orange), inputs (white), serial (yellow) and importantly for my question a TWI/I2C port (green).
[![Braccio Shield][3]][3]

The green four pin TWI/I2C connector provides GND, +5V, SDA (A4), SCL (A5). However the SDA and SCL connections are [reported][4] to not be direct, but that "a very tiny chip (located next to the I4 connector) buffers between the green connector and the Arduino pins SDA and SCL" . A photo of the chip described is below.
[![Close-up of buffer chip][5]][5]

Contrary to the reports of a "buffer" studying the [schematic][6] shows a level shifter [PCA9306TI][7] and two sets of 10K pullup resistors (R7,R8 and R11,R12) on the bus on both sides of the chip. VREF2 on the outboard side of the chip has a R9 220K resistor to +5V.

[![Schematic snippet][8]][8]

The other side of my I2C connection was an Arduino Pro-mini 5V. I was never able to get it working using the green port described, but it works fine directly hooked into SCL and SDA bypassing the level shifter.

My questions (sorry for the long lead up) are:

 1. Has the green TWI port been level shifted to expect ~3V? (Only really came to this conclusion writing this all up clearly).
 2. If I want to change the green TWI port to 5V I2C can I replace R9 220K with a zero ohm jumper?
 3. The 10K pullups (R7,R8 and R11,R12) seem larger than anticipated (I had anticipated about 4.7K for 5v or about 2.4 for 3V)? Can they be removed and left open if I have a single set of pullups elsewhere on the bus? Or better suggestions?

Thanks!

**Update 2021/01/30**

Well my I2C debugging skills are improving researching this! As a test bed I set up a clean working I2C bus with two MCU's running the Arduino Example Master/Writer Slave/Receiver sketches by Nicholas Zambetti. I tested the I2C signal on the oscilloscope to make sure it was clean. All good. To that test bed I connected the Braccio shield (5V, GND, SCL, SDA). Connecting the Braccio shield changes the I2C signal in interesting ways, with partial strength (runt) pulses, and round shoulder slow rises. Connecting via the green TWI port seems to accentuate the runt pulse aspect. Also interesting the oscillscope was still able to decode the signal. Still working on figuring this out.

Pic 1. First test - SCA and SCL connected via pin headers in top left of shield picture above.
[![First test][9]][9]
Pic 2. Second test - SCA and SCL connected via green TWI port
[![Second test][10]][10]
Pic 3. Clean Signal (no Braccio Shield connection)
[![Clean signal][11]][11]

  [1]: http://www.farnell.com/datasheets/2575116.pdf?_ga=2.151369337.1936105882.1517985527-654667508.1508905608
  [2]: https://www.arduino.cc/en/Guide/Braccio#braccio-shield
  [3]: https://i.stack.imgur.com/qapkL.png
  [4]: https://forum.arduino.cc/index.php?topic=502485.0
  [5]: https://i.stack.imgur.com/eGPq1.jpg
  [6]: https://content.arduino.cc/assets/Braccio-Shield-V1.pdf
  [7]: https://www.ti.com/product/PCA9306?utm_source=google&utm_medium=cpc&utm_campaign=asc-null-null-GPN_EN-cpc-pf-google-sa&utm_content=PCA9306&ds_k=PCA9306 Datasheet&DCM=yes&gclid=Cj0KCQiA6Or_BRC_ARIsAPzuer-9r3SFKEpBST426P58NfAV52irQPhw6Vol82yxK1wqjSYw1QZpDWAaAthyEALw_wcB&gclsrc=aw.ds
  [8]: https://i.stack.imgur.com/Uz21Q.png
  [9]: https://i.stack.imgur.com/CDQfJ.png
  [10]: https://i.stack.imgur.com/vlKPI.png
  [11]: https://i.stack.imgur.com/Rh0mD.png

body:
I fear we have a colloring issue. Your green is my blue ;-).

I have looked into the data sheet of the level shifter IC and TI only describes scenarios with a higher voltage on the right side and a lower voltage on the left side. Also the allowed voltage translations do not contain 5V to 5V. So I would say in equal voltage scenario the Level shifter may not work.

Answers

* Q1: The TWI port is always used with 5V (not ~3V). The Arduino that is supposed to use the shield might be a 3.6V version (like a DUE or M0). Perhaps the TWI port is only intended for this use case: A low voltage arduino with a 5V device. I admit: This should be noted in the documentation. So perhaps Braccio shields work outside the specification and may works under normal circumstances. But meanwhile I begin to understand why they are out of busines ;-).

* Supplement: the SCL and SCL signals are routed to two pairs of header pins as they are connected to different pins on different Arduinos. On a UNO you can not use A4 and A5 for analog as they are used for I2C for example. Do you use A4 A5 in any way? Or did you connect the second I2C pin pair in the power header when you had used the TWI connector? (rhetoric question ;-) of cause I will change the answer if you give me more information ;-) )

* Q2: The 220k resistor is necessary as it limits the current through the chip if VRef1 is lower than VRef2. Removing it with 0 Ohms would be a bad idea. As long as 5V is used on both sides, nothing would happen. But if Vref1 is 3.6Volts, you would waste energy and perhaps the chip would take part at a grill fest.

* Q3: Most I2C devices breakout boards already use their own pullup resistors. So lowering the pullups is not the best idea. -> too high current with LOW signals as the devices pull ups and the braccio pull ups are set in parallel.
-- There is a chance, that the resistors are too large for devices that don't use their own pull ups, but at a 100kHz bus speed I don't think, this could cause an issue.

BTW: You do not need to exchange the pull ups, if you insist to try out different values. Just use parallel resistors to lower the resistance (10K || 10K -> 5K) [|| means connected in parallel] (R || Rp -> (R*Rp) / (R+Rp))


message:
Valid options for output port on Mega 2560

I would like to adopt this library on an Arduino Mega2560:

https://github.com/gueei/DShot-Arduino

However, the macro `DSHOT_PORT` needs defined for the Mega2560 here:
https://github.com/gueei/DShot-Arduino/blob/master/src/DShot.h

So I need to add a `#if defined(__AVR_ATmega2560__)` macro to that `DShot.h` header, however, it is not clear to me where to lookup the port mapping on a 2560 mega.  I'm looking directly at the schematic itself here:
https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf

And understand that the 'ports' are groupings of IO where the pins are described as `P?#`, ? being the port letter and # being 0-7.

So what are my valid options?  It appears that some ports (A,C,L) aren't pinned at all, some (D,J) only a few pins, and just about none of them (except K/F) have all port pins utilized.  Also, I can see most of these pins are reserved for some type of functionality (analog, SPI, etc).  I'm assuming I'm looking for a port with available pins reserved for PWM, such as Port B (pins 10-13 are PWM).  Would this be correct?

body:
It would seem this library needs a single pin to communicate. So it
doesn't really matter whether the port you choose has only a few pins
available. Also, you do not care that some pins can have extra
functionality, like SPI, I2C, etc, unless you do plan to use that
functionality.

There is one think you should be aware of: the library uses the `in` and
`out` assembly instructions to access the port. These instructions can
only access the ports that are mapped in the regular I/O space of the
microcontroller, not those that are in the “extended I/O” space. In the
case of the ATmega2560, this means you can use any of the ports A
through G, but you cannot use H, J, K nor L.


message:
IDE compiles incorrect file after renaming them

I am using the stand alone Arduino IDE to build some projects, and I have a few `.cpp` files now, but during work I renamed them `.c` and back. When compiling the project now (with Ctrl-R), it is still trying to compile the `.c` files. But, I don't even see them on disk!

Changing the `.cpp` makes no difference. I am used to IDEs having some kind of project file, or a "clean project" option, but I cannot find those here.

body:
The Arduino IDE does not monitor changes to open files. So if you rename or change a file externally (i.e. in another editor), the IDE won't update the file contents. Therefore, after such a change, a restart might be necessary.

Note: If you use another editor to change a file but only compile (and upload) in the IDE, this will work, because the compiler correctly reads the updated file. But editing the source in the IDE and an external editor at the same time might overwrite either change!