message:
How i convert to Arduino Mega?

i need using OV7670 camera on my arduino mega, and i found this site have tutorial using ov7670 camera, but in this tutorial they use arduino Uno. if i'm using arduino Mega2560, what i need to do? do i have to change their code and pin connection ?

here is the link

https://www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/?amp_page=true

body:
**Yes, you will have to change the code to match the Mega pinout**.

Because the program need to run quite fast, and the Arduino functions
`digitalRead()` and `digitalWrite()` are dead slow, the author of the
program used [direct port access][] for performing the raw IO.
[For example][]:

```c++
 //Wait for vsync it is on pin 3 (counting from 0) portD
 while(!(PIND&8));//wait for high
 while((PIND&8));//wait for low
```

This is testing pin PD3 (8 is 23), which on the Uno is
digital 3, but on the Mega is digital 18. The same code could
be written in a portable fashion:

```c++
 //Wait for vsync it is on pin 3 (counting from 0) portD
 while (digitalRead(3) == LOW);   //wait for high
 while (digitalRead(3) == HIGH);  //wait for low
```

but it would probably be too slow.

Note also that here:

```c++
    UDR0=(PINC&15)|(PIND&240);
```

the program takes advantage of the particular pin mapping of the Uno in
order to read 8 inputs with only two port reads (4 bits on
port C and 4 bits on port D). You could do even better on the Mega
if you use pins A8 through A15 for the data bus, and then read the whole
8-bit word as `PINK`.

There may be some other differences between the Uno and the Mega that
need to be taken into account, but the pin mapping is the only one that
is obvious to me just by quickly going through the code.

[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation
[For example]: https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno/blob/d64dcf0a8c9c04c5b4c5fe1da01fd2c6d9b35600/main.c#L34-L36


sender: user

message:
Communication between three NodeMCUs such that one in in AP mode, second one in AP+STA mode and the third NodeMCU in STA mode

I am able to establish a connection between first and second NodeMCU, but unable to do so for the third nodeMCU. I used the IP  address to establish connection.
Should I assign a different IP to each nodeMCU so that communication can take place?
In the code that I had written, i have taken the same IP for all three NodeMCUs, so   communication was possible between 1st nodemcu(in AP mode) and 2nd nodemcu(in STA+AP mode).
For the 3rd node mcu the IP taken was different. Can any one suggest what to do next.

sender: assistant

body: The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top esp8266 has SoftAP with 192.168.4.x, set for the SoftAP of the middle esp8266 IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to connect a TCP socket or send an UDP message.


message:
Can't Compile .ino using ArduinoJson Library

I am using an ESP32 NodeMCU for which I wrote working software before. This also occurs when I just try to compile without uploading, so no hardware problem.
I am using the newest version of **ArduinoJson(6.12.0)** and it is included:

`#include <ArduinoJson.h>`

The only Function where I use the Library (I'm not good at C/C++, so maybe there is an error):

    int DeserializeJson(char *json, int *pin, int *pinmode, int *timeInMilliseconds){

      StaticJsonDocument<1024> doc;
      DeserializationError error = deserializeJson(doc,json);

      if (error) {

        Serial.println("Parsing failed");
        return -1;
      }

      memcpy(&pin, doc["Pin"], sizeof( doc["Pin"]));
      memcpy(&pinmode, doc["Mode"], sizeof( doc["Mode"]));
      memcpy(&timeInMilliseconds, doc["TimeInMilliseconds"], sizeof( doc["TimeInMilliseconds"]));

      return 0;
    }

This is the error I'm getting (at least a part of it):

    In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8:0,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                     from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24: error: no matching function for call to 'variantAs(ArduinoJson6120_000001::VariantData* const&)'

         return variantAs<T>(_data);

                            ^

    In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOr.hpp:9:0,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOperators.hpp:9,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:12,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                     from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

     inline typename enable_if<is_integral<T>::value, T>::type variantAs(

                                                               ^

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note:   template argument deduction/substitution failed:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

     inline typename enable_if<is_same<T, bool>::value, T>::type variantAs(

                                                                 ^

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note:   template argument deduction/substitution failed:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T,

    exit status 1
    Fehler beim Kompilieren für das Board ESP32 Dev Module.

body:
In its own way, the compiler tries to say "I don't know how to convert `doc["Pin"]` to a `const void*`".

Indeed, ArduinoJson doesn't support conversion to `const void*`; it supports conversion to `const char*`, but that doesn't make sense here. Instead, you want to convert `doc["Pin"]` to an integer and assign it to the variable passed by the caller of `DeserializeJson()`.

The solution is to use the assignment operator instead of `memcpy()`:

```c++
*pin = doc["Pin"];
*pinmode = doc['Mode"];
*timeInMilliseconds = doc["TimeInMilliseconds"];
```


message:
Serial Module Echoing a `0x00`

I am having a problem with a MAXIM Serial module (Config A) with a simple repeating code from COM port. When sending a character (`k`:`0x6b`) I receive a (`0x00`) echo.

Without the module and just connecting the arduinos crossing the TX/RX cables, I do not have any echo.

The echo persists, disregarding of:

 - The speed (from 38400 to 2000000 bps),
 - Using or not the high speed options (2.3MOhm for 250000bps) of the MAXIM,
 - Using or not 120 ohm terminal resistors,
 - Both grounds are 0V, connecting them has no effect,
 - Removing the `A` (red) `B` (green) Serial Bus Cables (???). Message not send in this case, as expected (!).

What could be the problem?

**Devices**:

 - Two Arduino Mega 2560,
 - Two [MAX3292][1], one for each arduino,
 - AWG24 Cable, shorter than 7 in each.

**Config A**: With Module (`00` echo), Half Duplex (f.19 p.13).

[![Config A][2]][3]
[![Config A Datasheet][4]][5]

**Config B**: Without Module (No echo), only crossed cables

[![Config B][6]][7]

Code:

    long rate=38400;
    void setup() {
     Serial.begin(rate); while (!Serial);
     Serial1.begin(rate); while (!Serial1);
     pinMode(22,OUTPUT);
     pinMode(23,OUTPUT);
    }
    char s;
    void loop() {
     if (Serial.available()) {
      digitalWrite(22,1);
      digitalWrite(23,1);
      s=Serial.read();
      Serial1.write(s);
      Serial1.flush();
      digitalWrite(23,0);
      digitalWrite(22,0);
     }
     if (Serial1.available()){
       s=Serial1.read();
       Serial.write(s);
      }
    }

Execution: Four `k` sent, `0x00` echoes received. After this, four `k` send from other arduino, received successfully.

[![Exec A][8]][9]
[![enter image description here][10]][11]

**Epilogue.**

Actually, the problem was a resistor at the RO output, not shown in the diagram ("The problem is in the code you didn't post").

It was a voltage divider for a 5V3.3 conversion in the Arduino Due case, useless in the Arduino Mega, but still there.

Theorizing a reason, that resistor caused a spike at the output (?), thus forcing the module to interpret it as another byte, an empty one (?).

After removing the resistors, it worked perfectly.
Now I migrated this back into Arduino Due, but with a diode plus a pull up resistor as a 5V3.3 converter.

  [1]: https://datasheets.maximintegrated.com/en/ds/MAX3291-MAX3292.pdf
  [2]: https://i.stack.imgur.com/bJRCLm.png
  [3]: https://i.stack.imgur.com/bJRCL.png
  [4]: https://i.stack.imgur.com/Wy2a9m.png
  [5]: https://i.stack.imgur.com/Wy2a9.png
  [6]: https://i.stack.imgur.com/cwsI1m.png
  [7]: https://i.stack.imgur.com/cwsI1.png
  [8]: https://i.stack.imgur.com/02fXem.png
  [9]: https://i.stack.imgur.com/02fXe.png
  [10]: https://i.stack.imgur.com/UzgXim.png
  [11]: https://i.stack.imgur.com/UzgXi.png

body:
Check your wiring! My guess is the twisted pair (A-B swap).

I've checked your code, it seems right. Please note that /RE and DE were designed that way so you can simply connect them and control with only one pin.

I don't have the exact same hardware, I had MAX485 and Arduino Nano at hand. Nano only has one hardware serial, so I've used the SoftwareSerial library instead.
I've connected them, adjusted your code to my setup, and it worked. Here it is in case it helps to troubleshoot your issue. I've also optimized your version a little bit (but it worked before so the bug is somewhere else).

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX

const int dir_pin=9;
const int dir_transmit=1;
const int dir_receive=0;
long rate=38400;

void setup() {
    Serial.begin(rate); while (!Serial);
    mySerial.begin(rate); while (!mySerial);
    pinMode(dir_pin,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(dir_pin,dir_transmit);
        while(Serial.available())
        {
          s=Serial.read();
          mySerial.write(s);
        }
        mySerial.flush();
        digitalWrite(dir_pin,dir_receive);
    }
    while (mySerial.available()){
        s=mySerial.read();
        Serial.write(s);
    }
}
```


message:
Changing preferences.txt to 4-space tabs, how to AutoFormat existing code?

Title says it all really, but to elaborate, in my `preferences.txt` file, I've changed the `editor.tabs.size` variable to `4`, which works wonderfully, and now produces 4-space tabs as do my other IDEs for all the languages I write in.

However, I was told that using the `Tools->AutoFormat` feature would update all lines in my previously-written sketches that had the standard 2-space tabs with the new 4-space tab layout.

This isn't so. Whether I `CTRL-a` to select all and run the Auto Format function, or whether I leave everything de-selected, nothing happens.

Should auto-format "fix" the 'incorrect' indenting to the new style? If so, what am I missing?

I'm currently on Arduino IDE 1.8.5 on Linux Mint, if that makes a difference.

body:
The auto formatter (astyle) uses a separate configuration to the editor (crazy, I know, but that's the Arduino mentality for you...).

It uses a separate configuration, which is in the `lib` folder of your Arduino program, called `formatter.conf`.

* Copy that file to the same location as `preferences.txt` so it doesn't get overwritten when you upgrade the IDE.
* Edit the file and change `indent=spaces=2` to `indent=spaces=4`

The auto format should now be the same as the editor format.


message:
How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance)

I spent a great deal of time looking for any posts regarding this and came up empty.

The reason I needed to do this is that I am working on some proprietary code that will be released in an embedded device, but makes use of an LGPL 3.0 licensed library which requires (4.d.0) that I release "corresponding application code in a form ... permit the user to recombine or relink the application with a modified version of the library."

Since the application is on an embedded device, the "corresponding application code" works out to the pre-link .o file which is normally well hidden in the Arduino process.

body:
To extract the .o produced during compilation in the Arduino IDE, do the following:

 1. Go to the Arduino->Preferences menu item. This will open a preferences window.
 2. In the preferences window find the line that says "Show verbose output during" and make sure that compilation is checked. (you can leave upload on or off as you prefer).
 3. Click "OK" to close the preferences window.
 4. Compile (or compile and upload) your Sketch.

You will get lots of extra output. In the white text, you will either see messages about files being compiled or about "using previously compiled file". In either case, there will be a path provided which will indicate where your Sketch was compiled. On my Mac environment this is `/var/folders/<long random string>/T/arduino_build_<number>/sketch/<sketch_name>.ino.cpp.o`

The line where your sketch is compiled is very long, but the path is also visible in most of the library lines and you can just work down into `.../sketch/...` instead of `.../library/...` instead of scrolling so far to the right on the exactly correct line.

To find the exact line where your sketch is compiled, look for the line directly below a line which simply says "Compiling sketch..."

I know this is rather basic (now that I know how to do it), but it took quite a bit of digging to find it and I figured others might want an answer that's searchable.


message:
Serial.availableForWrite versus Serial.flush

Is there a difference between the following two line codes?

>> while (Serial.availableForWrite <= 0) {}

versus

>> Serial.flush()

Thanks!

body:
https://www.arduino.cc/reference/en/language/functions/communication/serial/availableforwrite/

> `availableForWrite` Get the number of bytes (characters) available for writing in the serial buffer without blocking the write operation

Write operations on Arduino streams wait if they can't write the data to output. You can use the count returned by `availableForWrite` to avoid this blocking.

https://www.arduino.cc/reference/en/language/functions/communication/serial/flush/

> `flush` Waits for the transmission of outgoing serial data to complete.

One use of `flush()` is to wait until the data are sent away before putting the MCU into sleep mode.


body:
The line

```c++
while (Serial.availableForWrite() <= 0) {}
```

waits until the serial output buffer is **not full**. Whereas

```c++
Serial.flush();
```

waits until the serial output buffer is **empty**.


message:
CNY70 from 3.3v instead of 5v?

I would like to use a CNY70 with arduino that is not 5v but 3.3v powered. On the web there most tutorials use 5v and 200 + 10k resistors (e.g. [here][1] and [here][2]). So as far as I understand for 3.3v I would have to use lower ones.

Can someone explain how those 200 or 10k were calculated? How could I use CNY70 with 3.3v (if it's possible at all) ?

  [1]: https://cdn2.bigcommerce.com/server3700/64749/products/1507/images/4789/cny70-2__95262.1543951318.1280.1280.jpg?c=2
  [2]: http://2.bp.blogspot.com/-DgKjxBA_j5s/Tk5kDuqXU5I/AAAAAAAAA5Q/U7fgmawtphQ/s1600/CNY70.jpeg

body:
The CNY70 is just an IR LED and IR Phototransistor.  You can treat the IR LED (emitter) portion of it just like any LED and size the resistor appropriately.

The receiver is just a phototransistor which can operate at anything from about 1V up to 32V with no need to adjust anything.  The resistor used there is merely a pullup resistor.  You can think of the receiver as a button. When enough IR light falls on it it turns "on".

On an Arduino you could even get away without the pullup resistor and use an input in `INPUT_PULLUP` mode.


message:
How to calculate illuminance from the output of a TCS34725 color sensor?

I am using Arduino UNO with the sensor with the following programm.

    #include <Wire.h>

    // TCS34725 I2C address is 0x29(41)
    #define Addr 0x29

    void setup()
    {
      // Initialise I2C communication as MASTER
      Wire.begin();
      // Initialise Serial Communication, set baud rate = 9600
      Serial.begin(9600);

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select Wait Time register
      Wire.write(0x83);
      // Set wait time = 2.4 ms
      Wire.write(0xFF);
      // Stop I2C Transmission
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select Atime register
      Wire.write(0x81);
      // Atime = 700 ms, max count = 65536
      Wire.write(0x00);
      // Stop I2C Transmission on the device
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select control register
      Wire.write(0x8F);
      // AGAIN = 1x
      Wire.write(0x00);
      // Stop I2C Transmission
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select enable register
      Wire.write(0x80);
      // Power ON, RGBC enable, wait time disable
      Wire.write(0x03);
      // Stop I2C Transmission
      Wire.endTransmission();
      delay(800);
    }

    void loop()
    {
      unsigned int data[8];

      // Start I2C Transmission on the device
      Wire.beginTransmission(Addr);
      // Select data register
      Wire.write(0x94);
      // Stop I2C Transmission on the device
      Wire.endTransmission();

      // Request 8 byte of data from the device
      Wire.requestFrom(Addr, 8);

      // Read 8 bytes of data
      // cData lsb, cData msb, red lsb, red msb, green lsb, green msb, blue lsb, blue msb
      if (Wire.available() == 8)
      {
        data[0] = Wire.read();
        data[1] = Wire.read();
        data[2] = Wire.read();
        data[3] = Wire.read();
        data[4] = Wire.read();
        data[5] = Wire.read();
        data[6] = Wire.read();
        data[7] = Wire.read();
      }

      // Convert the data
      float cData = (data[1] * 256.0) + data[0];
      float red = (data[3] * 256.0) + data[2];
      float green = (data[5] * 256.0) + data[4];
      float blue = (data[7] * 256.0) + data[6];

      // Calculate the final lux
      float luminance = (-0.32466 * red) + (1.57837 * green) + (-0.73191 * blue);

      // Output data to serial monitor
      Serial.print("Red color Luminance   : ");
      Serial.print(red);
      Serial.println(" lux");
      Serial.print("Green color Luminance : ");
      Serial.print(green);
      Serial.println(" lux");
      Serial.print("Blue color Luminance  : ");
      Serial.print(blue);
      Serial.println(" lux");
      Serial.print("IR Luminance          : ");
      Serial.print(cData);
      Serial.println(" lux");
      Serial.print("Ambient Light Luminance : ");
      Serial.print(luminance);
      Serial.println(" lux");
      delay(500);
    }

Is the output really in lux or is it counts? If it's counts, how can I calculate the illuminance in lux?

body:
In the chip's [datasheet][1] on page 8 in the chapter "RGBC Operation" (emphasis by me):

> The RGBC engine contains RGBC gain control (AGAIN) and four
> integrating analog-to-digital converters (ADC)for the RGBC
> photodiodes. The RGBC integration time (ATIME) impacts both the
> resolution and the sensitivityof  the  RGBC  reading.  Integration  of
> all  four  channels  occurs  simultaneously  and  upon  completion  of
> theconversion cycle, the results are transferred to the color data
> registers. **This data is also referred to as channelcount.**

So, if you read the values from the data registers, you get simple count values, which were determined by the ADCs connected to the channels. To get a value in lux, you need to calculate that yourself.

[Adafruit][2] has a library for their breakout board with this chip. In their tutorial it seems, that the library outputs a value in lux. Maybe you can also use this library, or you can check, how they are converting the values from the sensor to lux values.

  [1]: https://cdn-shop.adafruit.com/datasheets/TCS34725.pdf
  [2]: https://learn.adafruit.com/adafruit-color-sensors/overview


body:
The output of this program is a very wild guess at what the illuminance
may be. I would definitely no trust it. It uses the same formula as [the
function `Adafruit_TCS34725::calculateLux()`][calc-lux], from the
[Adafruit TCS34725 driver][driver]. Googling for the numeric
coefficients, I found that the likely source of this formula is the
application note [Calculating Color Temperature and Illuminance using
the TAOS TCS3414CS Digital Color Sensor][dn25]. That application note
seems serious, but it addresses a _different model_ of sensor from the
one you have. It also gives a formula that does not depend on the gain
nor the integration time (maybe that's not adjustable on the TCS3414CS),
which makes absolutely no sense if you have a TCS34725. I found an
[issue filed against the Adafruit driver][issue] that shows the formulas
used in the library are grossly wrong when compared against a
high-quality lux- and color-meter.

I suggest you try implementing the illuminance formula given in the
application note [DN40 – Lux and CCT Calculations using ams Color
Sensors][dn40]. This documents gives a generic formula with specific
coefficient matching different color sensor models, and it does give
coefficients specific for the TCS3472 family. Adafruit did use this
document to implement a color temperature calculation (function
`Adafruit_TCS34725::calculateColorTemperature_dn40()`), but they failed
to use it for the illuminance calculation.

[calc-lux]: https://github.com/adafruit/Adafruit_TCS34725/blob/1.3.0/Adafruit_TCS34725.cpp#L541-L559

[driver]: https://github.com/adafruit/Adafruit_TCS34725
[dn25]: https://ams.com/documents/20143/80162/TCS34xx_AN000517_1-00.pdf/1efe49f7-4f92-ba88-ca7c-5121691daff7
[issue]: https://github.com/adafruit/Adafruit_TCS34725/issues/21
[dn40]: https://ams.com/documents/20143/80162/ColorSensors_AN000166_1-00.pdf/c0b4a4b4-9948-f2a7-f8a1-36a8208bd0a9


message:
Convert String to IPAddress

How can i convert a String to IPAddress on arduino / esp ?

etc. "192.168.1.2"  -> IPAddress(192, 168, 1, 2)

Tried this

    void setup() {

      Serial.begin(115200);

      IPAddress apip;

      const char *apipch;
      apipch = "192.168.4.1";

    Serial.println(apip.fromString(apipch));

    }

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

But i just get an output "1"

body:
The `IPAddress` class has a member function `bool fromString(const char *address)`.

```c++
const char *apipch = "192.168.4.1";
IPAddress apip;

if (apip.fromString(apipch)) { // try to parse into the IPAddress
 Serial.println(apip); // print the parsed IPAddress
} else {
 Serial.println("UnParsable IP");
}
```


body:
You could do this:

    String myip="192.168.1.2"
    IPAddress local_IP;
    bool x= local_IP.fromString(myip);


body:
    IPAddress str2IP(String str) {

        IPAddress ret( getIpBlock(0,str),getIpBlock(1,str),getIpBlock(2,str),getIpBlock(3,str) );
        return ret;

    }

    int getIpBlock(int index, String str) {
        char separator = '.';
        int found = 0;
        int strIndex[] = {0, -1};
        int maxIndex = str.length()-1;

        for(int i=0; i<=maxIndex && found<=index; i++){
          if(str.charAt(i)==separator || i==maxIndex){
              found++;
              strIndex[0] = strIndex[1]+1;
              strIndex[1] = (i == maxIndex) ? i+1 : i;
          }
        }

        return found>index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
    }


message:
Alternative to delay() when using Ticker in ESP8622

When using the Ticker library on the ESP8266 you can't use the `delay()` function because Ticker functions are using the underlying timer. The [original Arduino library][1] says that you can use a Ticker as delay, but in the [ESP8266 implementation][2] things work differently. You "attach()" a callback function and specify the period.

**How can I generate a delay that doesn't require the underlying timer?**

(BTW, where is the documentation for the ESP8266 Ticker library? The [repository][2] has no documentation nor comments on the functions.)

  [1]: https://github.com/sstaub/Ticker
  [2]: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker

body:
use the ticker callback to increment a value. this value can be used as millis() substitute. actually the "millis" is made that way.

write a simple function to give you a delay. **this code assumes the callback function is interrupt/event driven like a systick timer in ARMs.**

    uint32_t ticks;

    void callbackFunc()
    {
       ticks++;
    }

    void myDelay(uint32_t del)
    {
       uint32_t tempTime = ticks;
       while (ticks < tempTime + del);
    }


message:
Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors)

I've read post that it's possible to connect multiple Ultra-Sonic Sensors to one Arduino.
But I have a few questions:

 1. If I use Arduino Uno, what is the maximum number of Ultra Sonic Sensors that I can connect one Arduino UNO?

 2. Is there any option to power Arduino UNO in some kind of low-power mode so I can achieve power autonomy for at least 90 days.(I'm referring to battey life, or solar powered solutions)

 3. Can Arduino UNO work on the low/high temperatures (e.g. -20 / +50 Celsius degrees), and what is the known work temperature range?

 4. How to secure jumpers/cables to work on extreme temperatures (e.g. -20 / +50 Celsius degrees)

    Thanks in advance :D

body:
 1. You did not specified, what kind of ultrasonic sensor you want to use so I assume use of "standard" ultrasonic Arduino modules (like hc-sr04), which need 4 pin (VCC, GND, TRIGGER and ECHO). Since Arduino Uno has got 20 IO pins (6 analog and 14 digital), you can use 10 pins as outputs for TRIG signals and 10 as inputs for ECHO signals and thus connect up to 10 ultrasonic modules to one Arduino Uno.
 2. In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
 3. Working temperature of Arduino Uno is -40 to 85 °C.
 4. One of the options is using a terminal shield with screw terminals, e.g something like [this][1].

  [1]: https://arduino-shop.eu/arduino-platform/1200-arduino-uno-terminal-shield.html


message:
Translating WS2812-LED-Strip-IDs when cutting up a strip to multiple parallel ones

Lets say i have 1 meter of WS2812 Strip at 60 LEDs per meter. Now i cut the strip up in to 6 single strips but keep the wiring the same and lay them out in parallel. So it would look something like this

1   |  11  |  21 ...

2   |  12  |  22 ...

3   |  13  |  23 ...

...

10   | 20   | 30 ...

Is there any library that would allow me to easily translate this? If i for example want to work with rows, turn a certain row in a certain color, treat certain sub-strips as if they were an individual one, etc etc...
I'm sure i can't be the first one who had this problem?

body:
No, there is no library.

It's just simple maths.

If all your strips are the same, then you just multiply the strip number by the number of LEDs per strip, and add the number of the LED you want in that strip.

So, assuming 10 LEDs per strip:

    lednumber = 10 * strip + led;

You can make a little macro to do it for you if you like:

    #define STRIP2LED(S, L) (((S) * 10) + (L))

Then you can use such things as:

    // Set all LEDs on strip 3 to red
    for (uint8_t i = 0; i< 10; i++) {
        leds[STRIP2LED(3, i)] = CRGB::Red;
    }


message:
"expected primary-expression before '.' token" in debug code

I'm making some code for school, and is adding debug code to it. When compiling, I get the error as written in the title. This is the code in question:

    #define DEBUG 1

    #ifdef DEBUG
    #define Serial.println(x) DEBUG_PRINT(x)
    #else
    #define DEBUG_PRINT(x)
    #endif

And the code in my void setup, which has Serial.begin:

    #ifdef DEBUG
    Serial.begin(9600);
    DEBUG_PRINT("Asteroid");
    #endif

What am I getting wrong? I get the feeling it's my define text, but I'm unsure.

Thank you for your time
Gaarden

body:
You defined the pre-processor macro the wrong way around.
Think it is like an assign statement. You come up with a name and assign something to it.

`#define SHORT_NAME(ARG) some_real_function_that_has_an_awkward_long_name(ARG)`

See the manual of your favourite compiler [GCC][1] for reference.
It is always a good idea to do that when using features you haven't used before. Sometimes it can be enlighting.

  [1]: https://gcc.gnu.org/onlinedocs/cpp/Macros.html


body:
In short: you have your macro backwards.

Macros are not formed as "Take this set of commands and call it X" but "Make this macro X and have it equate to this set of commands".

Where you have:

    #define Serial.println(x) DEBUG_PRINT(x)

it should instead read:

    #define DEBUG_PRINT(x) Serial.println(x)

When you call it, because the macro doesn't contain a semi-colon in it, you need to specify the semi-colon as if you were calling a function:

    DEBUG_PRINT("Aardvark");

You can omit the semi-colon only if you have a semi-colon in your macro:

    #define DEBUG_PRINT(x) Serial.println(x);

and then:

    DEBUG_PRINT("Aardvark")

By doing it that way your "empty" macro now does become truly empty when used.  Without the semi-colon in the macro you would have to use:

    DEBUG_PRINT("Aardvark");

Which for the empty variant would end up as:

    ;

Not always desirable, and can cause some problems.

So by adding the semi-colon into the macro you can omit it from the usage of the macro, and your empty variant now becomes:


message:
I2C communication problem with two slaves (atlas scientific) and one Nano (official)

I'm working on a project using an arduino Nano (official) and two peripherals from Atlas Scientific (pH and DO) communicating via i2c. Everthing works fine when i use a usb alimentation connected to the PC or to a 5V adaptater (typically a phone charger).

I want to use a 12V battery and a 12V DC 1.5A adaptater to power up my system, the problem is that it works fine for a moment (30 to 40 seconds) and then the pH start having problem with the communication and the led becomes red and the TX/RX leds from the arduino (which are connected to nothing start going crazy. I use 4.7k pull up resistors and an L7805ACV voltage regulator to go from 12 to 5V.

Attach, a part of the system schematics.[![enter image description here][1]][1]

If you have any clue, starting to be new idealess

EDIT : Here is the part of the program concerning the i2c communication :

```arduino
#include "Wire.h"

/*********************************************************************************************************
 *                                               Address
 *********************************************************************************************************
 */
int pH_address = 99;
int DO_address = 97;

/*********************************************************************************************************
 *                                         i2C CONFIGURATION
 *********************************************************************************************************
 */

byte received_from_computer = 0;
char sensor_data[20];
byte in_char_sensor = 0;
byte j = 0;
byte code = 0;
int time_ = 850;

void setup()
{
  Wire.begin();
}
void loop()
{
  pH = Get_i2C(pH_address);
  delay(200);
  DO = Get_i2C(DO_address);
  delay(200);
}

/**********************************************************************************************************
 *                                                  i2C
 * ********************************************************************************************************
 */

float Get_i2C(int address)
{
  char computerdata = 'R';
  Wire.beginTransmission(address);
  Wire.write(computerdata);
  Wire.endTransmission();

  delay(time_);

  Wire.requestFrom(address, 16, 1);
  code = Wire.read();
  while (Wire.available())
  {
    in_char_sensor = Wire.read();
    sensor_data[j] = in_char_sensor;
    j += 1;
    if (in_char_sensor == 0)
    {
      j = 0;
      break;
    }
  }
  return atof(sensor_data);
}
```

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

body:
Two ideas.

1: Count your grounds. If you count more than 1 you have a problem. Your system should have a single ground, so ANY connection on every component labeled GND should be connected to ground.

The reason multiple grounds are a problem is that your signals (other than differential signals) are measured relative to ground, so if two components have different ideas of what "ground" is they start to disagree about what constitutes a 1 and a 0.

2: Scope your power supply. Check that your 5V supply is still providing 5V. It's possible (although unlikely) that the L7805ACV can't supply enough current and your system is browning out. If possible have a look with an oscilloscope to check for noise on the 5V supply.

Your boards should already have decoupling capacators, but adding another won't hurt, so also try adding a 0.1uf cap between 5V and GND to eliminate any noise.


message:
Number of digits setting for serial printing the sensor output value

I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?

I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?

<!-- -->

body:
You can use the C function `sprintf`:

    char text[5];
    sprintf(text, "d", number);
    Serial.println(text);

The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.


body:
Three if statements look a bit simplistic, but are much better in code size than `sprintf`, if that's the only usage for sprintf.

     if (number < 1000) Serial.write('0');
     if (number < 100) Serial.write('0');
     if (number < 10) Serial.write('0');
     Serial.println(number);

Saves about 1.5kB Flash, compiled with Arduino 1.8.9 for an Uno


message:
In Nrf24lO1 pa+Lna,is there any indication led light?

How do I know that my **Nrf24lO1 pa+Lna **  is working or not? For that any separate led is there for on ?

body:
There is no led.

But you can use the [isChipConnected](http://tmrh20.github.io/RF24/classRF24.html#ac224c55270d26dbe7b4f3492ea3056b5) function in the [RF24 library](https://github.com/nRF24/RF24)


message:
SD card readline reading batched lines?

So, I am trying to transmit float data, over UART, from my Arduino to another machine. The log of this data is really large, so I am forced to put it on an SD card, and read it into the Arduino line-by-line, then transmit that single line.

The issue is that my code seems to be "grabbing" ~65 lines (or more) at a time, transmitting them over UART, then stopping (or crashing) the Arduino.

My log looks like this (a small snippet of the several thousands of lines):

    14.71927
    14.71795
    14.71787
    14.71787
    14.71787
    14.71799
    14.7175
    14.71836
    14.71746
    14.71787
    14.71923
    14.71878
    14.7184
    14.71791
    14.71893
    14.7184
    14.71746
    14.71799
    14.71746
    14.71795
    14.71874
    14.71795
    14.71878
    14.71836
    14.71881
    14.72235
    14.72781
    14.72872
    14.72917
    14.72826
    14.73188
    14.73278
    14.73595
    14.73783
    14.74227
    14.74231
    14.74363
    14.74683
    14.7495
    14.75492
    14.75899
    14.76396
    14.76807
    14.77033
    14.77161
    14.77262
    14.77978
    14.78524
    14.7884
    14.78746
    14.79695
    14.80238
    14.80652
    14.80648
    14.81055
    14.81191
    14.81865
    14.82234
    14.82095
    14.81733
    14.8286
    14.82908
    14.82999
    14.82682
    14.83673

And my code looks like this (I know it says 4Hz, but is at 1Hz, but that was to help "see" the "batch" grabbing and printing):
<!-- language-all: lang-cpp -->

    // Define our LED pins
    #define greenLED    6
    #define redLED      5

    // Define our serial BAUD rate
    #define BAUDrate    9600

    // To read data from the SD card
    #include <SD.h>

    // To print data to an LCD panel
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd( 0x3F, 16, 2 );

    void setup(){
        // Set LED pins as outputs
        pinMode( greenLED, OUTPUT );
        pinMode( redLED, OUTPUT );

        // LED output at start: GREEN = ON, RED = OFF
        digitalWrite( greenLED, HIGH );
        digitalWrite( redLED, LOW );

        // Begin wired comms with MSP board
        Serial.begin( BAUDrate );

        // Begin reading data from SD card
        SD.begin( 4 );                      // Need pin #4 for SD card bit-shifting
        File dataLog;                       // Store our data from the SD card
        dataLog = SD.open( "DATA.TXT", FILE_READ );
        String data = dataLog.readStringUntil( "\n" ); // Prime our data

        int i = 0;

        while( data != "" ){
            i++;
            Serial.print( i );
            Serial.print( "\t" );

            Serial.println( data );         // Send our data to MSP board
            lcdUpdate( data );              // Print our sent data to the LCD screen

            delay( 1000 );                   // Wait 1/4 of a second (4 Hz)

            data = dataLog.readStringUntil( "\n" );    // Reprime our data
        }

        // Close our data log to avoid corrupting SD card contents upon restart
        dataLog.close();

        // Switch our LEDs since we're finished streaming our data
        digitalWrite( greenLED, LOW );
        digitalWrite( redLED, HIGH );
    }

    void loop(){
    }

    // Prints the current data being sent over UART to an LCD screen
    void lcdUpdate( String ourData ){
        lcd.setCursor( 0, 0 );
        lcd.print( " Sending data:  " );
        lcd.setCursor( 0, 1 );
        lcd.print( "    " );
        lcd.print( ourData );
        lcd.print( "    " );
    }

Again, I want it to grab a single line, print it to the serial terminal, print it to the LCD, then grab a second line and repeat.  I'm not able to test the LCD (since I don't have one with me at the moment), but the serial terminal is giving me problems, so I'm assuming the LCD won't work, either.

I'm getting something, as a Serial Terminal output, along the lines of:

    1       14.71927
    14.71795
    14.71787
    14.71787
    14.71787
    14.71799
    14.7175
    14.71836
    14.71746
    14.71787
    14.71923
    14.71878
    14.7184
    14.71791
    14.71893
    14.7184
    14.71746
    14.71799
    14.71746
    14.71795
    14.71874
    14.71795
    14.71878
    14.71836
    14.71881
    14.72235
    14.72781
    14.72872
    14.72917
    14.72826
    14.73188
    14.73278
    14.73595
    14.73783
    14.74227
    14.74231
    14.74363
    14.74683
    14.7495
    14.75492
    14.75899
    14.76396
    14.76807
    14.77033
    14.77161
    14.77262
    14.77978
    14.78524
    14.7884
    14.78746
    14.79695
    14.80238
    14.80652
    14.80648
    14.81055
    14.81191
    14.81865
    14.82234
    14.82095
    14.81733
    14.8286
    14.82908
    14.82999
    14.82682
    14.83

It seems to want to stop somewhere between the 65th and 69th element, randomly.  I'm assuming that it's running out of buffer space, since it's grabbing everything from the SD card, instead of a single line, one at a time.

This has become more evident with my `i = 0` line, and that it isn't iterating for every line, just the once for the ~65 lines.

Am I reading the data in incorrectly, or am I parsing things incorrectly, or is what I'm trying to do simply not possible?

body:
Arduino's reference doesn't help with your readStringUntil call ([see SD's documentation][1]), but assuming it's the same as Stream's, it needs a character, not a string as a terminator.

Your output shows that your Arduino tried to read a line, but there were no line endings found - probably because of the '' vs. "". That's why your output starts with a 1 (i's value), and there no other line numbers after that, even though in your output clearly shows newlines.

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


message:
Using a Force Sensing Resistor and time input

So the code below measures how much force is exerted on the FSR. I would like to know what would I have to change in this code so that it can record for how long the FSR is being pressed for. So instead of "What force is exerted on the FSR?", I want to ask "How long is the FSR being pressed for?"

Any help will be most appreciated

    #include<SoftwareSerial.h>
    #include <Wire.h>
    SoftwareSerial bluetooth_port(0, 1); //ports for Rx and Tx
    int flexSensorPin; // The flex sensor for pin 0

    void setup()
    {

      Serial.begin(9600); // Start the serial transmission
    }

    void loop()
    {

      flexSensorPin = analogRead(A0); // Flex sensor pin
      Serial.print(flexSensorPin);
      Serial.println("EOL");

      delay(100);

    }

body:
Use the analog comparator implemented in AVRs. this function, monitors two analog levels and generates interrupts if one of them goes higher or lower than the other as set. use this interrupt to record/stop counting. on AIN connects to FSR, and the other to a potentiometer to define a threshold. here are some links to get you going.

http://www.gammon.com.au/forum/?id=11916
https://github.com/tardate/LittleArduinoProjects/tree/master/playground/AnalogComparator


message:
ESP8266 still connects to wifi even after flashed with empty sketch

So, my wifi is a hotspot password protected. I was developing a program until I decided to comment the ssid and passwords from it, to prevent the ESP from connecting to the internet. But then it still connected. After some debugging, I decided to upload an empty sketch. It still connects to the hotspot!

What is going on?! How does it still know my SSID and password when loaded with an empty sketch!?

body:
The Espressif esp8266 SDK remembers the SSID and password on flash to start connecting immediately after boot. The WiFi channel is stored in the RTC memory (cleared on power down)

You can control this with [WiFi.persistent()][1] and [WiFi.setAutoConnect()][2].

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/generic-class.html?highlight=persistent#persistent
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html?highlight=autoconnect#setautoconnect


message:
Do comments occupy space in compiled C++ sketch? Arduino / NodeMCU

I tend to leave old code around as comments until I am sure that my current version is stable.  Just the way I like working.  I am concerned that I may be unnecessarily bloating up my sketches.

Do comments occupy space in an Arduino IDE compiled C++ sketch for Arduino (Nano, Uno)?  Is it correct to suppose that the behavior would be the same for NodeMCU?

body: No.  Comments don’t take up any space.


body: The C/C++ processor (which processes only the #define & #include statements) is the first stage of the compilation process. It runs before the compiler does and strips out everything that isn't code. The compiler will never see your comments.


message:
How can one reset Arduino Nano from NodeMCU?

If one connects the `RESET` pin on an Arduino Nano to a digital pin on a NodeMCU, will the NodeMCU be able to reset the Nano by setting said pin to `LOW`?

body: Yes - grounding the reset pin over-rides the pullup resistor on the Atmega 328's reset pin. You may not be able to prevent the NodeMCU from resetting the Nano when it (NodeMCU) is reset, if that matters.


body:
yes it can.

and to make this answer a little longer...

 1. you don't need a level shifter as the pins are 5v tolerant. pullups aren't a problem
 2. you may use an optocoupler for isolation :)


body:
Yes, you can reset a 5 V Arduino with esp8266. I did it many times. The esp8266 doesn't have a problem with pull-up level current at 5 V.

On my picture io 0 of the esp-12F is wired to reset pin of Nano. The esp-12F runs [WiFiLink firmware][1] which can OTA upload sketch to ATmega328p and of course before flashing it must reset the ATmega.

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

  [1]: https://github.com/jandrassy/arduino-firmware-wifilink/wiki/Test-Setup
  [2]: https://i.stack.imgur.com/cPlO1.jpg


message:
LowPower.idle isn't waiting

I am trying to have my Arduino wait in a low power idle state given by the LowPower library made by rocketscream on an Uno. However, when I try to have it wait for 8 seconds, it seems to not pause at all. Does anyone know how to make it so it waits the full 8 seconds before running the next line of code?

Here is the code:

    #include "LowPower.h"

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

    void loop() {
       delay(100);
       Serial.println("above");
       delay(100);

       LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_ON, SPI_OFF, USART0_OFF, TWI_OFF);

       delay(100);
       Serial.println("below");
    }

I would expect this to print "above", then wait 8 seconds, then print "below",  then do it again. But what happens is it runs right through the LowPower.idle without doing anything and the output looks like:

> 1:12:14.547 -> above
>
> 21:12:14.746 -> below
>
> 21:12:14.845 -> above
>
> 21:12:15.044 -> below
>
> 21:12:15.144 -> above
>
> 21:12:15.376 -> below

...and so on.

If anyone has any ideas on how to make idle wait, that would be great.

Thanks!

body: FYI, this issue was brought up nearly 3 years ago, with no response from the author:  https://github.com/rocketscream/Low-Power/issues/36


message:
NRF24L01+ changing configuration after startListening

I have been trying to get two Arduino UNO talk to each other via NRF24L01's with TMRH20's NRF24 library. I tried many tutorials and examples and none of them worked. Most of them prints some error messages that's due to `radio.write` returning `false`.

After some troubleshooting I saw something weird. I set up the configuration (e.g. data rate) and when I call `startListening` it seems to be changed back.

This code:
```
void setup() {

    Serial.begin(9600);
    printf_begin();

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.printDetails();
    Serial.println();

    radio.startListening();
    radio.printDetails();
}
```

Outputs:
```
STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1  = 0xe7e7e7e7e7 0x4141417852
RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
TX_ADDR   = 0xe7e7e7e7e7
RX_PW_P0-6  = 0x00 0x20 0x00 0x00 0x00 0x00
EN_AA   = 0x3f
EN_RXADDR  = 0x03
RF_CH   = 0x4c
RF_SETUP  = 0x27
CONFIG   = 0x0e
DYNPD/FEATURE  = 0x00 0x00
Data Rate  = 250KBPS
Model   = nRF24L01+
CRC Length  = 16 bits
PA Power  = PA_MAX

STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1  = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
TX_ADDR   = 0xe7e7e7e7e7
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x3f
EN_RXADDR  = 0x03
RF_CH   = 0x02
RF_SETUP  = 0x0f
CONFIG   = 0x08
DYNPD/FEATURE  = 0x00 0x00
Data Rate  = 2MBPS
Model   = nRF24L01+
CRC Length  = 8 bits
PA Power  = PA_MAX

```

You can see that the address was set up correctly *before* `startListening` (`0x4141417852`) but *after* it reverted back to what I assume is the default value (`0xc2c2c2c2c2`). Data rate has also changed.

Is this normal?
---------------

The other Arduino UNO doesn't have `startListening` or `stopListening`, but if I print the configuration after `openWritingPipe` I see the correct configuration.

body:
The first thing that comes to my mind is that you are powering the nrf24L01 directly from the 3V3 pin of your Arduino Uno. __DO NOT do this.__

The 3V3 pin does not provide enough current for the nrf24L01. This renders the module completely unstable. You can:

* Use a decent capacitor across the VCC and GND on the module. (But I do not recommend going for that solution)
* Use a separate 3V3 power source that is capable of handling the current spikes of the nrf24L01. But don't forget to connect its ground to the Ardino Uno aswell.
* Use a [power module][1] that powers the nrf24L01 from Arduino Unos 5V rail.

  [1]: https://www.aliexpress.com/item/32949830523.html


message:
HLW8032 UART sends random data ( Registers Overflow often)

I designed  my own version of smart socket just like the Sonoff with power metering chip HLW8032. And when I read the data in ESP-12F the data doesn't have a fixed format.
To troubleshoot the issue, I bought [**HLW8032 Breakout Board**][1] and analyzed the data sent by HLW8032, and I found the results are the same as the board I designed.

And that made me think that I may be reading the data from the Serial port the wrong way.

HLW8032 sends 24 Bytes on the serial and the format should be like this:

    F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9C 2A 39 61 00 00 79
    F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9D C2 9F 61 00 00 78

The data that I receive is in this format,

    F2 5A 2 D3 70 6 BC D4 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 FB EC 17 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
    FD 84 7D 61 0 1 38 F2 5A 2 D3 70 6 AA 59 F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 2 D3 70 6 AA 59 0 3D 4F
    4 98 B4 4D E1 80 FE FF 1 61 0 1 38 F2 5A 1 61 0 1 38 F2 5A 2 D3
    70 6 AA 59 0 3D 4F 4 98 B4 4D E1 80 FE FF F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
    FE FF 1 61 0 1 38 F2 5A 2 D3 70 6 AA 59 38 F2 5A 2 D3 70 6 AA 59
    0 3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 4F 4 98 B4 4D E1 80 10 1B
    D4 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0 3D F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 13 4E 9E 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0
    3D 4F 4 98 B4 4D E1 80 14 E8 3 61 0 1 39 E1 80 16 82 67 61 0 1 39
    F2 5A 2 D3 70 6 AA 59 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0

We can see that the registers overflows again and again.
The code that I use to read the data is:

    #include <SoftwareSerial.h>
    #define BAUD_RATE 4800

    SoftwareSerial swSer(13, 12);

    void setup()
    {
      Serial.begin(BAUD_RATE);
      swSer.begin(BAUD_RATE);
    }

    byte data[24];
    void loop()
    {
      if (swSer.available() > 0) {
        int a = swSer.readBytes(data, 24);
        yield();
      }

      // Display
      for (int i=0;i<24;i++)
      {
        Serial.print(data[i],HEX);
        Serial.print(" ");
      }
      Serial.println();
    }

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

I feel that there is no issue in my hardware design, and the issue seems to be in the sketch.

----------

What can be the possible problem with my setup?

----------

How do I make the output of HLW8032 Stable with no overflow of registers?

----------

Is there any library someone can recommend me to read the data from HLW8032 on **SoftwareSerial**?

**Note:** After some troubleshooting I found that delay() cause the problem to be more worse. And won't receive a stream of Bytes whose first byte , second nibble is **F** like F2, F4, as from the datasheet , first four bits are 1s by default.

  [1]: https://www.electrodragon.com/product/energy-meter-hlw8032-breakout-board/
  [2]: https://i.stack.imgur.com/Mys1p.png

body:
First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.

Then I used an [HLW8032 Library](https://github.com/Khaalidi/HLW8032) (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.

So in short my issue resolved using two things:

 1. I swaped UART0 to GPIO15 and GPIO13 using `Serial.swap()`
 2. Used a [library for the HLW8032](https://github.com/Khaalidi/HLW8032)

Thanks to [@Juraj](https://arduino.stackexchange.com/users/37622/juraj) who provided the useful [link](https://arduino-esp8266.readthedocs.io/en/latest/reference.html?highlight=serial1#serial) about Serial Swap in ESP8266.
> Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

    #include "HLW8032.h"

    HLW8032 HL;

    void setup()
    {
     HL.begin(Serial,4);
     Serial.begin(4800);
        Serial.swap();
    }

    unsigned int V;
    void loop()
    {
     HL.SerialReadLoop();

     if(HL.SerialRead == 1)
     {
        V = HL.GetVol();
     }
    }

With this I can't print and see my debug prints on  GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.


message:
EEPROM: managing address mapping between firmware versions

Is there a common way to handle changes in the mapping between eeprom addresses and variables between firmware versions? It's not about the eeprom memory to survive the update, but to be(come) compatible with future sketches with a possibly different set of variables.

To make it clearer consider the following fictional scenario:

  A coffee machine has been programmed to measure `water_temperature` and the firmware is supposed to stop heating within a `temperature_hysteresis`
 below `set_temperature`. `set_temperature` is a persistent parameter that has been individually optimized be the user and must therefore survive any firmware update. As a configuration parameter also `temperature_hysteresis` is stored in the eeprom.
Now the manufacturer decides to update his machine with a PID-controller, making the parameter `temperature_hysteresis` obsolete while he introduces some new parameters for the controller's gains (`pid_gains`). How can he manage that the firmware keeps values that haven't been touched by the update (like `set_temperature`) while the additional parameter `pid_gains` is added.

I assume that obsolete parameters should be removed as there could be more updates with new parameters in the future. That's why simply incrementing the eeprom address and ignoring deprecated addresses probably won't work.

On the other hand, when re-using old addresses I wonder how a fragmentation of the eeprom can be avoided.
I came up with the idea of putting all configuration data into a json in the eeprom and to handle the problem a layer above by parsing the json for configuration data. But anyhow, that feels so wrong and might be too complicate.

Does anyone have experience with this kind of problem and knows how this routine is commonly implemented?

body:
There's lots of ways you could handle this.

Two thoughts right off the top of my head:

1. Have a "Version" identifier in the EEPROM.

The firmware then needs to know the EEPROM layout of all versions up to the current one. It can then read the EEPROM from the old version and write back a new format for the current version.

2. Have each entry in the EEPROM tagged with a "meaning".

This is not too different to your JSON idea (which you are right is horrible), but instead of lots of words you just use a simple number to identify the meaning of the value it is associated with.  Assuming that each stored value is an 8-bit byte (though it doesn't have to be), you could allocate "1" as "set_temperature", "2" as "temperature_hysteresis", "3" as "pid_gains", etc, Then the EEPROM might contain the bytes `1,96,2,5` and the firmware would know that the second byte is the `set_temperature` because it has a 1 in the first byte.

You can think of it as a "key / value" pair, but both the key and the value are just numbers.

To find the `temperature_hysteresis` you just scan through all the even EEPROM entries until you find `2`, then read the next entry. If you don't find a `2` then you use the default value.

Your firmware can then choose to either update an existing cell that is tagged with the right type (scan for type, update next cell), or it could erase all the values and replace them with just the ones it cares about - the choice is yours.

Any values that your firmware no longer cares about will be ignored, and potentially erased.


message:
Timer 1 Arduino - Create 2 Timers

I’m trying to output 2 separate frequencies using 2 output pins from an Arduino using the Timer 1 library. A snippet of the code is show below.

    void setup()
    {
     Serial.begin(9600);
     pinMode(button,INPUT_PULLUP);
     pinMode(button2,INPUT_PULLUP);
     pinMode(sig_out, OUTPUT);
     pinMode(sig_out2, OUTPUT);
    Timer1.initialize(1000);
    Timer1.pwm(sig_out,512,period);
    Timer1.pwm(sig_out2,512,period2);
    }

The issue is the way I’ve wrote this makes sense as I’ve initialised 2 outputs and 2 inputs but the ‘period’ is getting overwritten as there’s 1 timer and I’m not sure how to stop this. I was thinking about storing them in variables (like 'T1=' 'T2=') but it would still use the same timer.

I just wanted to know if there’s a way to use 2 timers so the Arduino outputs the frequencies separately.

body:
The Timer1 library only supports... Timer 1! So you only have one
hardware timer available. If you are using an Arduino Uno or anything
similar, you have a couple of other timers. However, unlike
Timer 1, which is a 16-bit timer, the others are 8-bit only. This
means they are very limited in the range and precision of the
frequencies they can generate. If you have an Arduino Mega, then you
have a few other 16-bit timers available. You may want to search for a
library called Timer3, which should work just like Timer1, while using
the 16-bit Timer 3.

If you don't find any suitable library, you may still be able to
generate your two signals using only Timer 1. Here is the trick:

 * set both PWM outputs to “toggle on compare match”
 * enable both compare match interrupts
 * in each of these ISRs, advance the compare match register by half a
   period of the corresponding signal.

For doing this you will need to dig into the low-level details of how a
timer actually works. I recommend you start by reading the
[Timers and counters][timer] tutorial by Nick Gammon.
Take the time to read and
study this. It's not a topic you will be able to master in just a
couple of hours.

[timer]: https://www.gammon.com.au/timers


message:
When GPS can't see satellites, how can I continue to tick off a smooth-ish time?

I'm getting 10 updates/sec from my GPS unit (The MTK3339 used in the Adafruit breakout board), and using it to update a clock display. This works well enough, though there's one minor problem that I'd like to solve and one major one that I have to solve.

The minor issue first; I don't get an update _every_ 100ms. I get one _roughly_ every 100ms... plus or minus about 20-30ms. If a late and an early update arrive back-to-back right when the display goes from n to n+1 seconds, it's noticeable that it's not ticking at a regular cadence. It's not fatal, but the arythmic stutter of it is deeply painful to watch.

The major issue is - what do I do when the GPS can't find a signal? Maybe the device is driving through a tunnel for a minute or there's some other sky obstruction. I still want the clock to update in a best-guess sort of way.

You can't just update the seconds display and then, 1000 (arduino-measured) milliseconds later, update the clock if a new message hasn't arrived. 1000 real-world milliseconds can be anywhere from 700 - 1400ms measured by an arduino, depending on the board and the quality of the crystal. Worse yet, the discrepancy is far from consistent within a single crystal. Seeing the processor speed up and slow down by several percent over the course of a few minutes isn't uncommon.

So what I'd like is a mechanism that will constantly smooth the received (GPS) time to give a best-estimate of current actual time. I'm okay with it being a second or two off (at most) from real time, as long as the cadence feels like actual seconds, and a loss of GPS for a few minutes can be quickly corrected when the signal is re-acquired.

I'm somewhat aware of (strikethrough)DIP(/strikethrough) PID methods, but I'm not sure how to apply them here. It seems that someone must have solved the problem for the sake of syncing internet time, so I shouldn't be reinventing a solution.

body:
An accuracy of 700-1400 ms seems like a big issue on your side. Usually it's like +- 10-20 ms. Are you able to provide your code? Or at least important parts of it? Is it possible that you used the delay function?

If so, you should definitely read into the millis function, and how to use it as a timer. This will significantly improve the "accuracy". Because upon calling the delay function, the chip not only waits a given amount of seconds. The chip also calls the yield function. This one is mostly used to make sure that all background work is done before continuing.

What also might me a problem is every type of modification of the chip clock. I've seen some code where people modify the frequency of the PWM-signal. This also affects the clock in every other way.


body:
> You can't just update the seconds display and then, 1000
> (arduino-measured) milliseconds later, update the clock if a new
> message hasn't arrived.

Why not? I'd do just that:

 - Maintain an in-memory clock
 - Update whenever a GPS message arrives
 - Every 1000ms (by millis), tick the clock if a message hadn't arrived, and in any case, update the display.

Something like:

    SimpleTimer Timers;
    unsigned long MyClock_sec = 0;
    bool clockIsTicked = false;

    void setup()
    {
       Timers.setInterval(10L,  GpsCallback);     // if msg, upd MyClock & set flag
       Timers.setInterval(1000, DisplayCallback); // if no flag, ++MyClock; upd display
    }

    void loop(){
       Timers.run();
    }

    void GpsCallback(void){
       // if gps message {
       //    MyClock = <<GPS_TIME>>;
       //    ++clockIsTicked;
       // }
    }

    void DisplayCallback(void){
       if( !clockIsTicked )
          ++MyClock;

       // update the display
       clockIsTicked = false;
    }

(Not compiled or tested - consider it a pseudo-code outline).


body:
What you want, namely something to “_smooth the received (GPS) time_”,
is called a [GPS disciplined oscillator][gpsdo]. Obviously, you are not
after the high accuracy of commercial GPSDOs, but the working principle
of what you are describing is essentially the same.

> what do I do when the GPS can't find a signal?

In GPSDO lingo, this is called the “holdover” state. At this point you
rely solely on your local oscillator (here, `millis()` or `micros()`),
and steer it to correct for is natural drift, as determined while the
GPS reception was good. Or you can go fancy, measure the chip
temperature, and apply a temperature compensation.

> I'm somewhat aware of DIP methods, but I'm not sure how to apply them
> here

I guess you mean “[PID][]”.

You apply this to the _phase_ of the oscillator. If the local oscillator
is ahead of the GPS (positive phase error), you lower its frequency. For
example, you could increment the seconds count every 1,000,100
microseconds (as measured by `micros()`), instead of every 1,000,000.
This will make your clock a little bit slow, and resynchronize it with
the GPS. Conversely, if your clock is behind the GPS, you slightly
increase its frequency to make it run faster.

In other words, the _error value_ of your PID is the phase error of your
clock, and the _control variable_ is the frequency adjustment. By
applying the PID technique this way, you are building what is known as a
[phase-locked loop][pll], or PLL. This is the standard way of
implementing a GPSDO.

> It seems that someone must have solved the problem for the sake of
> syncing internet time

Sure, but NTP implementations can be quite complex, as they have to deal
with multiple servers having different round-trip delays and different
levels of trust. I am not aware of any Arduino library that does
anything similar. You may search for “time synchronization” or “PLL”. If
you don't find any, you can pick a PID library and apply it to your
oscillator.

A couple of final remarks:

1. You wrote “_speed up and slow down by several percent over the course
   of a few minutes isn't uncommon_”. This shows there is something
   _awfully wrong_ with either your Arduino or your code. Over a few
   minutes, you expect frequency variations of the order of _one part
   per million_ on an Arduino clocked off a ceramic resonator, and a few
   _parts per billion_ if yours is clocked off a crystal. See this
   [experimental study on the stability of an Arduino clock][jorisvr].
   This stability problem is the very first thing you should investigate
   and fix.

2. Many GPS modules have the option to give you a 1PPS (one pulse per
   second) signal. If you can use this signal, you may get a quite
   accurate measurement of your phase error. Relying on the NMEA
   sentences will give you lots of jitter, which you would then have to
   compensate for by setting the time constant of the PLL to a very long
   value.

[gpsdo]: https://en.wikipedia.org/wiki/GPS_disciplined_oscillator
[PID]: https://en.wikipedia.org/wiki/PID_controller
[pll]: https://en.wikipedia.org/wiki/Phase-locked_loop
[jorisvr]: http://jorisvr.nl/article/arduino-frequency


message:
Uploading Firmware to Atmega1284p using ESP8266 with AVRISP as programmer

I am trying to flash a new Firmware to my Ender 3 Pro.

I am using the ESP8266 as an ISP via AVRISP over Wifi.

I have a 10mF capacitor between the ground and reset of the ESP8266

I followed this thread: https://arduino.stackexchange.com/questions/44702/esp8266-as-isp-program-for-atmega16?newreg=af926103f4bd475dba01b4dada1ea79b

When uploading I get the following output on console:

    C:\Users\Chry>"I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/bin/avrdude" -C "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"
    -v -V -p atmega1284p -c arduino -P net:192.168.178.59:328 -b 115200 -D -U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i

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

             System wide configuration file is "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : net:192.168.178.59:328
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: ser_drain(): read error: Falscher Parameter.

    avrdude: ser_drain(): read error: Falscher Parameter.

    avrdude: ser_drain(): read error: Falscher Parameter.

             AVR Part                      : ATmega1284P
             Chip Erase delay              : 55000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    10   128    0 no       4096    8      0  9000  9000 0xff 0xff
               flash         65    10   256    0 yes    131072  256    512  4500  4500 0xff 0xff
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
             Hardware Version: 4744608
             Firmware Version: 0.2
             Topcard         : STK502
             Vtarget         : 1.8 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

    avrdude done.  Thank you.

I can't seem to get it to work. Does anyone have any ideas?

I tried programming it directly:
I use the standard Arduino ISP sketch on my ESP8266 and try to upload that way. Directly connected the ESP8266 to my computer. I get sync-problems now: avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x61
The Board in the arduino IDE is set to Sanguino 1284p and the programmer is set to Arduino as ISP.

body: I assume that you have to wrap the directory in the option `-U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i` with `"`s. I don't promise that it'll work with that change, but `C:\Users...` will definitely confuse the parser due to the `:`!


message:
How to make procedures triggered remotely

I am installing lights in a model train and there are multiple prototypical lighting procedures that need to be activated. The lights are connected as follows:
Headlight Top - Pin 1
Headlight Bottom - Pin 2
Front Right Marker - Pin 3
Front Left Marker - Pin 4
Rear Right Marker - Pin 5
Rear Left Marker - Pin 6
Rear Left Headlight - Pin 7
Rear Right Headlight - Pin 8
Front Right Ditch Light - Pin 9
Front Left Ditch Light - Pin 10

I would like to simply address a forward procedure which would turn on pins 1, 2, 3, 4, 5, 6, 9, and 10. This is the lighting configuration when the loco is shifted into the forward gear. For reverse, pins 3, 4, 5, 6, 7, and 8 would be activated. There will be a few others too but those are the primary procedures. Is there a way I could set up a variable which names all those pins at once? Or is there some other way I could name a forwards or backwards lighting procedure with a single short name such as "Procedure 2"? I am using Arduino IDE.

body:
perhaps an array and a loop? (dont have the Arduino IDE atm, so sorry about any typos)

    int lights[] = {1, 2, 3, 4, 5, 9, 10};
    int count = 7;//because there are 7 items in the array
    //

    main(){
        for (int i = 0; i < count; i++){
             digitalWrite(lights[i], HIGH);
             delay(1000);
        }
    }

EDIT: still no IDE, but here is a little more depth.

forward(true) = forward lights on

forward(false) = forward lights off

reverse(true) = reverse lights on

reverse(false) = reverse lights off

 void forward(bool state){
  int lights[] = {1, 2, 3, 4, 5, 6, 9, 10};
  int count = sizeof(lights) / sizeof(lights[0]);

  for (int i = 0; i < count; i++){
   switch (state){

    case true: //turn on
     digitalWrite(lights[i], HIGH);
     break;

    case false: //turn off
     digitalWrite(lights[i], LOW);
     break;
   }
   //delay(1000); //optional delay between lights?
  }
 }

 void reverse(bool state){
  int lights[] = {3, 4, 5, 6, 7, 8};
  int count = sizeof(lights) / sizeof(lights[0]);

  for (int i = 0; i < count; i++){
   switch (state){

    case true: //turn on
     digitalWrite(lights[i], HIGH);
     break;

    case false: //turn off
     digitalWrite(lights[i], LOW);
     break;
   }
   //delay(1000); //optional delay between lights?
  }
 }


body:
> I would like to simply address a forward procedure which would turn on
> pins 1, 2, 3, 4, 5, 6, 9, and 10.

And what about pins 7 and 8? You didn't say what to do with them in the
forward procedure. Should they be turned off? Should they stay in
whatever state they were before? I know it is kind of obvious to you,
but it doesn't hurt being specific, for the benefit of those lacking the
required background. Lacking a complete specification, we are left to
making assumptions.

kei, in his answer, assumed that any pin you did not mention should be
left alone, in whatever state it was before. In this answer I will
instead assume that you want to _always_ control the 10 pins, turning
each of them either on or off.

With this assumption, the obvious solution is to have, for each
procedure, an array of 10 “states” (either `HIGH` or `LOW`), and loop
through the array setting each pin to its appropriate state:

```c++
for (int i = 0; i < LED_COUNT; i++)
    digitalWrite(led_pins[i], pattern[i]);
```

Here, `pattern[i]` is the state associated to `led_pin[i]` in this
specific procedure. Now, since all these pins are consecutive, you don't
need the `led_pins` array, and you can replace `led_pins[i]` by
`i + FIRST_LED_PIN` (i.e. `i+1`).

This way you can implement as many procedures as you want, each one
being defined as a simple 10-number array. I would add a _single
function_ to activate any procedure. This function would take as an
argument a pointer to the light pattern you want to apply:

```c++
const uint8_t FIRST_LED_PIN = 1;
const int LED_COUNT = 10;
const uint8_t formward_pattern[LED_COUNT] = {
    HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW,  LOW,  HIGH, HIGH
};
const uint8_t reverse_pattern[LED_COUNT] = {
    LOW,  LOW,  HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW,  LOW
};

void set_led_pattern(const uint8_t *pattern)
{
    for (int i = 0; i < LED_COUNT; i++)
        digitalWrite(i + FIRST_LED_PIN, pattern[i]);
}
```

With this in place, you can set the light pattern of the forward
procedure by issuing the single statement:

```c++
set_led_pattern(formward_pattern);
```

and for the reverse procedure:

```c++
set_led_pattern(reverse_pattern);
```


message:
74HC595 not working properly

I've used the following code to light 8 yellow leds sequentially but it only runs as it's supposed to be on Proteus. However in my breadboard the 8 leds keeps blinking all together, the resistors used are 220 ohms. Also when i'm trying to change the value of the variable "leds" to be for example 0x0F, it doesn't light, I've read in the Arduino shiftout tutorial that 0.1F capacitor on the latch pin will even the flickers so now I'm really confused.
```
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(100);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);

}
```

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

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

body:
SOLVED!
 i've tried many solutions to make it work but it just didn't and here are the solutions i tried
a) to use  0.1µf or 10µf between VCC and ground pin of the 74hc595 .
b) to set the clockPin and dataPin zero before sending data .
c) replacing the resistors from 220 ohm to 470 .

however,  i connected pin13 of the 74HC595 to an arduino pin and drive it to zero so the 8 output are ready to go then digitalWrite(out_enable_Pin, HIGH) ,send data as shown in the following code then digitalWrite(out_enable_Pin, LOW) again .

```
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int out_enable_Pin=13;
int resetPin=5;
char leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(out_enable_Pin, OUTPUT);
  pinMode(resetPin, OUTPUT);
}

void loop()
{
  digitalWrite(out_enable_Pin, LOW);
  digitalWrite(resetPin, HIGH);

  for (int i = 0; i <255; i++)
  {
    leds=i;
    updateShiftRegister();
    delay(1000);
  }
}

void updateShiftRegister()
{
    digitalWrite(out_enable_Pin, HIGH);
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, MSBFIRST, leds);
   digitalWrite(out_enable_Pin, LOW);
   digitalWrite(latchPin, HIGH);
}
```


message:
Arduino ESP8266 communication

I saw two peculiar things while googling this subjects.

1. Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?

2. Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

body:
> Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?

There is some uncertainty as to whether the ESP8266 has 5V tolerant inputs or not.  This uncertainty stems from differences in an early Chinese datasheet translated by the community, and the current English datasheet.  It's better to err on the side of caution though and translate your 5V signal from the Arduino to a 3.3V one with either a proper logic level translator or a resistive divider (note that the latter can limit the maximum baud rate you can use).

You can read more here:

* https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

> Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Bad information begets bad information. People copy poor quality examples and tutorials and pass that bad knowledge on to others1.

Many Arduino boards only have one hardware UART port, and that is shared with the USB connection to the PC.  It is hard to reliably use that UART for other serial communication, since doing so will break your ability to upload code while your hardware is connected.  So it's simpler in that case to use SoftwareSerial (or one of the better implementations).

However, I would never advocate using SoftwareSerial unless you *absolutely have to*.  It barely functions at 115200 baud (one of the common default ESP8266 baud rates).  If you have a convenient hardware UART then really you *must* use it, for the sake of your sanity if nothing else.

----

1: Even worse though are the examples where people use SoftwareSerial to communicate over the pins of a hardware UART... that's just plain stupid...


message:
How to count the number of rising edges on DS3231 rtc?

I am using a DS3231 rtc and I would like to get millisecond accuracy from it so I decided to use the 32kHz generated clock from it. I wrote a code that would count the rising edges or falling edges using an interrupt with (RISING or FALLING parameters) but I get only zeros on my Serial board for the count.

Here is the code I am using :

    #include <DS3231.h>
    #include <RTClib.h>
    #include <Wire.h>
    #include "rtc.h"
    #define InterruptPin 3

    volatile long lcnt = 0;

    RTC_DS3231 rtc;

    void setup() {
      Wire.begin();
      Serial.begin(74880); // init serial port
      pinMode(InterruptPin, INPUT_PULLUP);
      rtc.begin();
      rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
      attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
    }
    void loop() {
      unsigned long a=millis();
      if (a<1000){
      Serial.println(lcnt);
      }
    }

    void fcnt(){
      lcnt+=1;
    }

I just want to check how many rising edges I have in 1s. What is strange is that this code used to work and now it doesn't ^^'... I don't know if I changed something by mistake or deleted something useful.

Can somebody help me to resolve this little problem ?

Thanks a lot for your time !

body:
I'm not sure why you're getting 0 as such, but your interrupt and variable methodology leaves a lot to be desired (probably the cause of the "tutorials" you followed).

My primary concern is that you are using a 32-bit "long" variable in an interrupt, and referencing that directly outside the interrupt.  The Arduino is an 8-bit system, which means that all accesses to that variable take many instructions to arrange (splitting it down into 4 8-bit values, manipulating it, recombining it, etc).  Because of this no operations on that variable are "atomic".

You need to make them atomic.  If you don't then it's perfectly possible for the interrupt to trigger and modify the value in the middle of you doing something with that value.

The simplest way of making it atomic is to disable interrupts, then copy the value to another variable and/or modify it, and enable interrupts again.

Here's an example that I would consider stable:

    #include <DS3231.h>
    #include <RTClib.h>
    #include <Wire.h>
    #include "rtc.h"
    #define InterruptPin 3

    volatile uint32_t lcnt = 0;

    RTC_DS3231 rtc;

    void setup() {
      Wire.begin();
      Serial.begin(74880); // init serial port
      pinMode(InterruptPin, INPUT_PULLUP);
      rtc.begin();
      rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
      attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
    }

    void loop() {
      static uint32_t ts = millis();
      uint32_t a = millis();
      if (a - ts >= 1000) {
        ts = a;
        noInterrupts();
        uint32_t currentCount = icnt;
        icnt = 0;
        interrupts();
        Serial.println(currentCount);
      }
    }

    void fcnt(){
      lcnt+=1;
    }

That should print the number of pulses over successive 1 second periods.


body: I used the same code as yours and simply changed the datatype from uint32_t to unsigned long and it started working. May be you can try the same.


message:
Second item in array not gets assigned from struct object, ArduinoJson

I got the below code generated [this amazing](https://arduinojson.org/v6/assistant/) tool.

```
const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(4) + 2*JSON_OBJECT_SIZE(7);
DynamicJsonDocument doc(capacity);

JsonObject config = doc.createNestedObject("config");
config["type"] = "power_plug";
config["chip_id"] = "12345";
config["mac_address"] = "abc";

JsonArray config_attachments = config.createNestedArray("attachments");

JsonObject config_attachments_0 = config_attachments.createNestedObject();
config_attachments_0["name"] = "socket";
config_attachments_0["input_type"] = "toggle_switch";
config_attachments_0["on_state"] = "on";
config_attachments_0["off_state"] = "off";
config_attachments_0["pin_type"] = "output";
config_attachments_0["pin"] = 15;
config_attachments_0["current_state"] = "on";

JsonObject config_attachments_1 = config_attachments.createNestedObject();
config_attachments_1["name"] = "socket_1";
config_attachments_1["input_type"] = "toggle_switch";
config_attachments_1["on_state"] = "on";
config_attachments_1["off_state"] = "off";
config_attachments_1["pin_type"] = "output";
config_attachments_1["pin"] = 12;
config_attachments_1["current_state"] = "off";

serializeJson(doc, Serial);
```
This prints out the desired json properly. but when amend single line from the second array item, to take the `on_state` from my struct object `d_config`,
```
Serial.println(">>" + d_configs.peripherals[1].current_state);
Serial.println(">>" + d_configs.peripherals[1].on_state);
config_attachments_1["on_state"] = d_configs.peripherals[1].on_state;
```
the parsing gets quiet unexpected, and some of the keys from serialised string json gets missing. For above case, This gets printed in serial monitor;

```
>>off
>>on
{"config":{"type":"power_plug","chip_id":"12345","mac_address":"abc","attachments":[{"name":"socket","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":15,"current_state":"on"},{"name":"socket_1","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":12}]}}
```
**NOTE** in the second item of `attachments`, the key `current_state` is entirely missing.
When I assign all values from this struct object, the serialised json misses many more keys... and the behaviour is quite unexpected. here is how I have defined my structs;

```
typedef struct Peripheral{
    String name;
    String input_type;
    String on_state;
    String off_state;
    String pin_type;
    String current_state;
    int pin;
};

typedef struct {
  String type;
  String chip_id;
  String mac_address;
  Peripheral peripherals[10];
} DeviceConfig;
```
I am not sure if its an issue during serialization or something else... :/
Any help would be highly appreciated :) .

**UPDATE** When I added three items inside attachments, then the serialized json string is missing some keys for only the last item. Seems like only the last item on the list is having problem getting serialized.

body:
[ArduinoJson](https://arduinojson.org) stores strings differently depending on their types:

* for `const char*`, it saves a pointer;
* for other types (`char*`, `String`...) it copies the string.

Because ArduinoJson stores the copy of the string in the `JsonDocument`, you must increase the capacity of the `JsonDocument`.

In your case, you pass `Peripheral::current_state`, which is a `String`, so ArduinoJson makes a copy in the `JsonDocument`. Increasing `capacity` by a few bytes should solve the problem.

Note that the [ArduinoJson Assistant](https://arduinojson.org/v6/assistant/) also computes the number of bytes required to store all the strings. Look for "Additional bytes for strings duplication" on the right panel.


message:
Can an arduino Uno control led, sound and smoke?

I'm pretty new to this and I've not seen anyone answer this question yet - so I figured I would ask.

I have a vape mod that is set up to expel smoke with a trigger. I want to merge this trigger to the arduino so that the arduino can then have 2 single buttons. One would trigger a specific led set (8 LEDS), the vape mod, and sound through 2 external speakers for about 5 seconds. I'd like the second button would trigger another specific LED set (8), vape mod and sound (through two external speakers) for 3 seconds. I have acquired a 555 chip, which I've researched can control the timing of the triggers yet can't find anything about how much power is needed for these types of things.

If I'm able to have the LEDs, Sound, and Vape mod separately how do I combine these to control them all with a single push of a trigger?

However, again, the main thing I'm wanting to know is if an Arduino Uno can trigger all of these devices at a single time or if it would drain too much power?

Any help is truly appreciated! Also, if there is anything that you think I need to take into consideration that I haven't already - feel free to make suggestions. Like I said, I'm just starting out and I know I should start with simpler projects but I'm just really interested in whether or not this can be done.

All the best,

body:
The arduino has more than enough **processing** power to manage those tasks mentioned. You probably won't need that 555. Playing music is possible as long as the arduino doesn't have to process the file itself. But switching on an external player is no problem (with what so ever circuitry).

The **electrical** power is another story, you probably will need extra power-supplies, but nobody can say without knowing your exact setup.