message:
Replace char based on user input

I am developing a hangman game on tinyduino(tinycircuits) and I am currently stuck on how to **properly** replace a ```char``` based on user input within a ```for loop```. My current code does actually replace the correct underscore(blank), if a user inputs a correct letter.

As per the game hangman, it will print out a series of blanks(in my case, underscores) based on number of letters, that serve as placeholders for the correct letter and will reveal the letter only if a user inputs a correct letter.

However, whenever a user inputs another correct letter (after inputting a correct letter prior), my program creates another 'line' and replaces the underscore in that new line instead.

For example, say the word to guess is kotlin. If user inputs 'k', my console shows me:
```
k_____
```
The output above is still correct.
But, when the user inputs another letter, say 'o' which is also correct, the result I get is:
```
k______o____
```
To further re-emphasize, now if a user inputs 't', I would get:
```
k______o______t___
```

What do I need to modify in my code in order to replace the underscores in the original line whenever a user enters a correct letter? Below is my current code.

```
if (k == 1) { // Str1 is "kotlin"
    display.setCursor(10,50);
    length = strlen(Str1);

    String user_input = String(phone_input);
    String word = String(Str1);

    for (i = 0; i < length; i++) {
      word[i] = '_';

      if (user_input == "k") {
        word[0] = 'k';
      }

      if (user_input == "o") {
        word[1] = 'o';
      }

      if (user_input == "t") {
        word[2] = 't';
      }

      if (user_input == "l") {
        word[3] = 'l';
      }

      if (user_input == "i") {
        word[4] = 'i';
      }

      if (user_input == "n") {
        word[5] = 'n';
      }

      display.print(word[i]);
      SerialMonitorInterface.print(word[i]);
    }
  }
```

body:
Attention  spoiler (If it's ok for you just to enhance it to a playable version by enhancing the shortcuts! )

If you want to replace single characters in a word, `String` and
`std::string` is way too much overhead. Use good old char [] instead.

    const char* result { "kotlin" }; // shortcut
    const size_t size = 6; // shortcut

    char guess[size+1]; // The guessed intermediate result

    const byte wrongMax = 22;
    byte wrong = 0; // number of wrong guesses

    void setup() {
      for (char& c : guess) c='_';
      guess[size] = 0;

      Serial.begin(9600);
      Serial.println(guess);
    }

    void loop() {
      if (strcmp(result,guess)== 0) {
        Serial.println("Got it !"); while (1){} // Stop, reset required
      }
      if (wrong >= wrongMax) {
        Serial.println("Failed !"); while (1){} // Stop, reset required
      }

      int c = Serial.read();
      if (c >= 'a' && c <= 'z') {
        // shortcut: only lower characters allowed
        byte p;
        for (p=0; p < size; p++) {
           if (c == result[p] && guess[p] == '_') {
             // found a new correct one
             guess[p] = c;
             break;
           }
        }
        if (p == size) {Serial.print( ++wrong ); Serial.println( " wrong guesses");}
        Serial.println (guess);
      }
    }


sender: user

message:
Send a 2d PROGMEM array over SoftwareSerial

I have a 2d array:

    const byte messages_for_measurement[2][8] PROGMEM =
    {
      { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
      { 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 },
    };

I want to send one of these sub-array over software serial.

Initially, this produced junk data:

    swSerial.write( messages_for_measurement[0], sizeof(messages_for_energy_meter[0]) );

Then I learned about `pgm_read_byte_near()` and `pgm_read_word()`. I tried every combination but I did not get this to work:

    swSerial.write(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0]))), sizeof(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0])));

and

    swSerial.write(pgm_read_byte_near(&pgm_read_word(messages_for_measurement[0]))), sizeof(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0])));

and

    swSerial.write(char(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0])))), sizeof(char(pgm_read_byte_near(pgm_read_word(messages_for_measurement[0]))));

and

    swSerial.write(char(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0])))), sizeof(char(pgm_read_byte_near(pgm_read_word(&messages_for_measurement[0]))));

How can I send the sub-array over serial, when the 2d array is in PROGMEM?

sender: assistant

body:
The `write()` method from `SoftwareSerial` (which is inherited from the
abstract `Print` class) does not support printing PROGMEM-based binary
buffers. The `print()` method does have some PROGMEM support, but it is
limited to printing NUL-terminated character strings, and is meant to be
used with the `F()` macro. You could coerce this method into printing
your data, but this would require you to add a null byte at the end of
each inner array, and the trick would break if you ever have to send a
null byte.

Also, the `pgm_read_stuff()` macros cannot read an array at a time. You
could do achieve this with `memcpy_P()`, but that would require
allocating an array in RAM. I think the simplest solution here is to get
the bytes from the flash one by one with `pgm_read_byte()`:

```c++
const byte *message = messages_for_measurement[0];
size_t size = sizeof messages_for_measurement[0];
for (size_t i = 0; i < size; i++) {
    swSerial.write(pgm_read_byte(&message[i]));
}
```

Note that the first line does not attempt to access the array data: it
only copies into `message` the address of the first byte: this is the
decay-to-pointer semantics.


message:
power 12v solenoid from DC jack of Arduino Uno

I was wondering if it is possible to power up a 12V solenoid valve from the DC jack of the Arduino Uno, provided that I'm powering the Arduino from the same jack:
[![enter image description here][1]][1]

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

body: Sure, that's the same as if you were directly soldering a second plug to your power supply. Just make sure the power supply delivers enough current for your solenoid (the power used by the Arduino will be comparably negligible).


message:
Having a problem with DS18B20 getTempC using an array containing the addresses of the sensors

I have been struggling with this and am at a total loss as to why its not working.
Here is my program:

```lang-cpp
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is Arduino pin A0
#define ONE_WIRE_BUS A0

// Setup a oneWire instance
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// Define array for holding all the sensors addresses and load addresses.
//======================================================================
DeviceAddress SensorAddr [13] =
                 {
 ( 0x28, 0xAA, 0x30, 0x41, 0x38, 0x14, 0x01, 0x14 ), // Sensor 1
 ( 0x28, 0xAA, 0x24, 0x31, 0x38, 0x14, 0x01, 0xDF ), // Sensor 2
 ( 0x28, 0xAA, 0xE4, 0x30, 0x38, 0x14, 0x01, 0x72 ), // Sensor 3
 ( 0x28, 0xAA, 0xD4, 0xC2, 0x38, 0x14, 0x01, 0x80 ), // Sensor 4
 ( 0x28, 0xAA, 0x6C, 0xDA, 0x38, 0x14, 0x01, 0xD5 ), // Sensor 5
 ( 0x28, 0xAA, 0xCA, 0x39, 0x38, 0x14, 0x01, 0xBB ), // Sensor 6
 ( 0x28, 0xAA, 0x75, 0x28, 0x38, 0x14, 0x01, 0x2C ), // Sensor 7
 ( 0x28, 0xAA, 0xFB, 0xB2, 0x38, 0x14, 0x01, 0xBF ), // Sensor 8
 ( 0x28, 0xAA, 0x0F, 0x3A, 0x38, 0x14, 0x01, 0xC3 ), // Sensor 9
 ( 0x28, 0xAA, 0x6F, 0x26, 0x38, 0x14, 0x01, 0xF8 ), // Sensor 10
 ( 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x6A, 0x74, 0xF1 ), // Sensor 11
 ( 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x7D, 0x29, 0x55 ), // Sensor 12
 ( 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x73, 0xAC, 0x3A )  // Sensor 13
                   };

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

//Test first Sensor Address  - This works
//=======================================

  byte Sensor1Test[8] = { 0x28, 0xAA, 0x30, 0x41, 0x38, 0x14, 0x01, 0x14};
  Serial.print("Test Sensor 1: ");
  float tempTest = sensors.getTempC( Sensor1Test );
  Serial.print(tempTest, 2);
  Serial.print("\xC2\xB0"); // shows degree symbol
  Serial.print("C");
  Serial.println();
}

void loop(void)
// Get all temperatures - This does not work??
//============================================

{
  sensors.requestTemperatures();
  for (int S =0; S<13; S++)
      {
        Serial.print("Sensor # "); Serial.print(S+1); Serial.print(": ");
        float tempC = sensors.getTempC(SensorAddr [S]);
        Serial.print(tempC,2);
        Serial.print("\xC2\xB0"); // shows degree symbol
        Serial.print("C");
        Serial.println();
        delay(1000);
      }
 Serial.println();
}
```

[![This is the result][1]][1]

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

body:
The `DeviceAddress` internally is defined as an array of `uint8_t` (see [definition](https://github.com/milesburton/Arduino-Temperature-Control-Library/blob/master/DallasTemperature.h#L75):
```c++
typedef uint8_t DeviceAddress[8];
```
That is, each address is an array itself.
```
DeviceAddress Sensor1 = { 0x28, 0xAA, 0x30, 0x41, 0x38, 0x14, 0x01, 0x14 };
```

So if you have 13 `DeviceAdrress`, you are dealing with a two-dimension array, and you need to declare it as:
```
#define NUMBER_OF_SENSORS 13
DeviceAddress SensorAddr [NUMBER_OF_SENSORS] = {
 { 0x28, 0xAA, 0x30, 0x41, 0x38, 0x14, 0x01, 0x14 }, // Sensor 1
 { 0x28, 0xAA, 0x24, 0x31, 0x38, 0x14, 0x01, 0xDF }, // Sensor 2
 { 0x28, 0xAA, 0xE4, 0x30, 0x38, 0x14, 0x01, 0x72 }, // Sensor 3
 { 0x28, 0xAA, 0xD4, 0xC2, 0x38, 0x14, 0x01, 0x80 }, // Sensor 4
 { 0x28, 0xAA, 0x6C, 0xDA, 0x38, 0x14, 0x01, 0xD5 }, // Sensor 5
 { 0x28, 0xAA, 0xCA, 0x39, 0x38, 0x14, 0x01, 0xBB }, // Sensor 6
 { 0x28, 0xAA, 0x75, 0x28, 0x38, 0x14, 0x01, 0x2C }, // Sensor 7
 { 0x28, 0xAA, 0xFB, 0xB2, 0x38, 0x14, 0x01, 0xBF }, // Sensor 8
 { 0x28, 0xAA, 0x0F, 0x3A, 0x38, 0x14, 0x01, 0xC3 }, // Sensor 9
 { 0x28, 0xAA, 0x6F, 0x26, 0x38, 0x14, 0x01, 0xF8 }, // Sensor 10
 { 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x6A, 0x74, 0xF1 }, // Sensor 11
 { 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x7D, 0x29, 0x55 }, // Sensor 12
 { 0x28, 0xFF, 0x64, 0x1E, 0x1E, 0x73, 0xAC, 0x3A }  // Sensor 13
};

for (int s=0; s<NUMBER_OF_SENSORS; S++) {
  float tempC = sensors.getTempC(SensorAddr[s]);
}


message:
Multiple if else statements for distance-triggered LEDs

I have a sketch that calculates simple distance from the device to the nearest preset GPS coordinate (there are 3 in total) and I would like to have LEDs in the neopixel strip light up according to the proximity of the location.

I managed to make it work with only one 5mm led and a simple if (shortestDist < 10) then digitalWrite(ledPin, HIGH); - else ledpin low. But I want to use a neopixel strip with 7 leds to light up according to various distance criteria.

In my attempt here, I tried to make specific leds light up when 50, 30 and 10m away but it doesn't work properly, and it's a pretty crude approach, as are my coding "skills" :D

I would also like some help on how to make some kind of shorthand for specific led strip setup depending on distance - for example at 50m distance, 2 leds red, 5 leds off, at 30m distance 5 leds red, 2 leds off and so on.

Hope someone can assist the newb :D Currently the leds don't all shut off when the distance is higher than 50.

    void loop()
    {

    while (ss.available() > 0)
        gps.encode(ss.read());
    if (gps.location.isUpdated())
    {
        Serial.print(F("Lat Lon = "));
        Serial.print(gps.location.lat(), 6);
        Serial.print(", ");
        Serial.println(gps.location.lng(), 6);
    }
    else if (millis() - last > 1000)
    {
        Serial.println();
        if (gps.location.isValid())
        {
            double shortestDist;
            for (int i = 0; i < 3; ++i)
            {
                double distanceToDest =
                    TinyGPSPlus::distanceBetween(
                        gps.location.lat(),
                        gps.location.lng(),
                        positions[i].lat,
                        positions[i].lon);
                if (!i || distanceToDest < shortestDist)
                    shortestDist = distanceToDest;
            }
            Serial.print(F("Next in range = "));
            Serial.print(shortestDist, 2); // decimal
            Serial.println(" m");

            if (shortestDist < 50)
            {
              pixels.clear();
              pixels.setPixelColor(0, pixels.Color(0, 250, 0));
              pixels.setPixelColor(1, pixels.Color(0, 0, 0));
              pixels.setPixelColor(2, pixels.Color(0, 0, 0));
              pixels.setPixelColor(3, pixels.Color(0, 0, 0));
              pixels.setPixelColor(4, pixels.Color(0, 0, 0));
              pixels.setPixelColor(5, pixels.Color(0, 0, 0));
              pixels.setPixelColor(6, pixels.Color(0, 250, 0));
              pixels.show();
              delay(50);
            }

            else if (shortestDist < 30)
            {
              pixels.clear();
              pixels.setPixelColor(0, pixels.Color(0, 250, 0));
              pixels.setPixelColor(1, pixels.Color(250, 250, 0));
              pixels.setPixelColor(2, pixels.Color(0, 0, 0));
              pixels.setPixelColor(3, pixels.Color(0, 0, 0));
              pixels.setPixelColor(4, pixels.Color(0, 0, 0));
              pixels.setPixelColor(5, pixels.Color(250, 250, 0));
              pixels.setPixelColor(6, pixels.Color(0, 250, 0));
              pixels.show();
              delay(50);
            }

            else if (shortestDist < 10)
            {
              pixels.clear();
              pixels.setPixelColor(0, pixels.Color(250, 0, 0));
              pixels.setPixelColor(1, pixels.Color(0, 250, 0));
              pixels.setPixelColor(2, pixels.Color(0, 0, 0));
              pixels.setPixelColor(3, pixels.Color(250, 0, 250));
              pixels.setPixelColor(4, pixels.Color(0, 0, 0));
              pixels.setPixelColor(5, pixels.Color(0, 250, 0));
              pixels.setPixelColor(6, pixels.Color(250, 0, 0));
              pixels.show();
              delay(50);
            }

            else
            {
              pixels.clear();
              pixels.setPixelColor(0, pixels.Color(0, 0, 0));
              pixels.setPixelColor(1, pixels.Color(0, 0, 0));
              pixels.setPixelColor(2, pixels.Color(0, 0, 0));
              pixels.setPixelColor(3, pixels.Color(0, 0, 0));
              pixels.setPixelColor(4, pixels.Color(0, 0, 0));
              pixels.setPixelColor(5, pixels.Color(0, 0, 0));
              pixels.setPixelColor(6, pixels.Color(0, 0, 0));
              pixels.show();
              delay(50);
            }

        }
        if (gps.charsProcessed() < 10)
            Serial.println(F("No GPS data."));
        last = millis();
        Serial.println();
    }
}

body:
 * Common inexpensive GPS modules are likely to report positions that appear to jump around by perhaps 5 meters in good conditions.  Many factors affect GPS accuracy and this uncertainty.  Some are listed [here][1].  It might be problematic to implement a 10 meter distance threshold feature unless conditions are favorable.

 * Consider constraining your "if" tests more.  For example, use "if ((shortestDist <= 50) && (shortestDist > 30))" instead of "if (shortestDist < 50)".  Continue similarly with the other "if" tests.  Otherwise, once shorttestDist is less then 50 only the 1st "if" test is executed as it will become true and stay true and none of the other "it" tests will be considered.

 * Consider only using mills(). The posted code uses delay() & millis(). Calling delay() is fine but using millis() is almost always better. Mixing the 2, though, should be avoided.

 * The logic in the code might be incorrect. It appears GPS data is only process and the LEDs updated when GPS information is unavailable (not new).

 * When writing embedded firmware, always consider hardware problem sources. Many find small batteries problematic during momentary current demands.  [Batteries with small Amp-Hour][2] ratings are more prone to dropping their voltage during a high current events.  Such as when a processor operates a relay or activates a sensor.

  [1]: https://www.gps.gov/systems/gps/performance/accuracy/
  [2]: https://en.wikipedia.org/wiki/Ampere_hour


message:
Alternative to GPS location being calculated by radius around a point

Hopefully the thread title isn't confusing - I'm trying to find out how would it be possible to make a different way of proximity warning with GPS.

Default/simplest way is by forming a radius around a goal waypoint, so the proximity criteria will get triggered when you're "inside" the circle. I know about geofencing but that does seem very demanding and complex, so I'd like to ask if something like shown in this pic would be achievable.

So instead of proximity criteria being a radius around a waypoint, forming a circular geofence so to speak, would it be possible to create a half-circle like this, at a specific angle.

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

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

body:
Let

 - (`x`, `y`) be the Cartesian coordinates of the vector going from the
   waypoint to your position

 - `radius` be the radius of the circle

 - `theta` be the orientation of the straight line, in radians.

You can then build a unit vector normal to the straight line:

**n** = (cos(θ+π/2), sin(θ+π/2)) = (−sin θ, cos θ)

You are on the colored side of the line if the scalar product of **n**
with (`x`, `y`) is positive.

In code:

```c++
bool is_inside(float x, float y)
{
    float product = - x * sin(theta) + y * cos(theta);
    float r2 = x * x + y * y;
    return r2 <= radius * radius && product >= 0;
}
```


message:
EspAsyncWebServer process HTTPS to HTTP

I read this [issue][1]. But I didn't understand it.
Like the author I don't have an SSL certificate and I don't want to have one (because if I had one I could live with HTTPS!).

I just want to process any `https://<url>` request like it was `http://<url>`. It can be a redirect but the answer states:

    server.on("/redirect/internal", HTTP_GET, [](AsyncWebServerRequest *request){
      request->redirect("/hello");
    });

    server.on("/redirect/external", HTTP_GET, [](AsyncWebServerRequest *request){
      request->redirect("https://techtutorialsx.com/");
    });

Ok, but how to detect if the request was HTTP or HTTPS?

  [1]: https://github.com/me-no-dev/ESPAsyncWebServer/issues/1143

body:
This isn't something you can do.

What you're asking for is like saying "I have to screw something together but I really only want to use a hammer, so how do I hammer the screw?". The answer is, you don't.

In this case the ESP32 is a server. The web browser is a client. The web browser is speaking HTTPS. When the browser makes an HTTPS request to the server, HTTPS is the **only** thing the browser will accept. HTTPS include a security layer (that's the "S" part) which is what requires certificates. If the server is not capable of handling that security layer (which it's not if it doesn't have an SSL certificate) then the only thing it can do is reject the connection by either not listening for it or immediately closing it

There is no communication between the client and server if the server isn't configured with certificates and can't speak TLS (the security layer) with the client. Allowing the server to downgrade the security when the client requests it would be a huge general security issue for the web. It's designed to not allow this.

Either support HTTPS properly, get the client to speak HTTP, or just don't do this at all. Those are your options.

As for detecting HTTP vs HTTPS, it depends on the port your server listened on. If you listen on port 80, you get HTTP requests. If you listen on port 443 you get HTTPS. If you're not listening on a port, the request of that type is refused (reset).


message:
Best way to "hack" a library without forking it

I'm using Visual Studio Code and PlatformIO.
I added some libraries to my project using `platformio.ini`:

    lib_deps =
     olikraus/U8g2@^2.34.4
     crankyoldgit/IRremoteESP8266@^2.8.4
     plerup/EspSoftwareSerial@^6.16.1
     rlogiacco/CircularBuffer@^1.3.3
     https://github.com/me-no-dev/ESPAsyncWebServer.git
     makuna/NeoPixelBus@^2.7.0
     adafruit/Adafruit BusIO@^1.13.2
     bblanchon/ArduinoJson@^6.19.4
     adafruit/Adafruit PN532@^1.2.2
     khoih-prog/ESPAsync_WiFiManager@^1.15.1
     https://github.com/guestisp/ESP32AsyncDNSServer.git

Now, let's say I have to "hack" few lines of code inside a library to fit my needs.
Since it's a very specific change (not something that can be useful to others) I can easily change directly the source code without forking it on github.

The downside is every time I download again the libraries (or set up another dev machine) I lose all my changes.

I can also move the downloaded library to the `lib/` subfolder in the project tree, removing the dependency from `lib_deps`.

I wonder if there is a more reliable way to do this, i.e. applying a patch after downloading the code (yocto-like).

body:
Use a local source control and repository of your choice. Obtain the latest published rev of the library and make your changes to it (I assume you have already done this, probably a number of times). Check in your changed revision of the library to your local repository. When a new rev becomes available, obtain it and *merge* it into your local repository.

Update:
> One problem of this approach is I will end up with nested
> repositories.

I'm coming from old-school source control - file management. rcs, in my case (don't laugh). I'm guessing your local modifications affect only one or a few of the library files. Mightn't something that simple - a file-level merge - solve your issue (regardless of which tool you choose to do it)?


message:
Multiple unique I2C devices interfere

I'm trying to make a fairly simple program that interfaces with the [Adafruit TSL2591 light sensor](https://www.adafruit.com/product/1980) as well as a [MAX30102 pulse oximeter](https://www.amazon.ca/MAX30102-Detection-Concentration-Compatible-Arduino/dp/B07ZQNC8XP). They both use I2C for communication. I'm using the recommended libraries for both, [Adafruit_TSL2591_Library *Version 1.4.3*](https://github.com/adafruit/Adafruit_TSL2591_Library) and [SparkFun_MAX3010x_Sensor_Library *Version 1.1.2*](https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library) respectively. This is all running on an Arduino UNO, although I will be transferring it to a NANO in the near future. All of the following is using *Version 2.0.2* of the Arduino IDE.

The issue I'm running into is that both sensors will work perfectly fine in isolation, but when trying to run at the same time it locks up and outputs nothing.

[Example code](https://github.com/adafruit/Adafruit_TSL2591_Library/blob/db71874052f1aab68250160689f8d158fef53ad4/examples/tsl2591/tsl2591.ino) that works for the Light sensor.

[Example code](https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library/blob/72d5308df500ae1a64cc9d63e950c68c96dc78d5/examples/Example8_SPO2/Example8_SPO2.ino) that works for the pulse oximeter.

I know my wiring is good because the sensors work individually with either program even when both sensors are plugged in simultaneously.

The code that almost works:
```
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

MAX30105 particleSensor;

const byte LUX_ADDR = 0x29;
const byte OX_ADDR = 0x57;

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);

#define MAX_BRIGHTNESS 255

#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
//Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
//To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-bit data.
uint16_t irBuffer[100]; //infrared LED sensor data
uint16_t redBuffer[100];  //red LED sensor data
#else
uint32_t irBuffer[100]; //infrared LED sensor data
uint32_t redBuffer[100];  //red LED sensor data
#endif

int32_t bufferLength; //data length
int32_t spo2; //SPO2 value
int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
int32_t heartRate; //heart rate value
int8_t validHeartRate; //indicator to show if the heart rate calculation is valid

void setup()
{
  Serial.begin(115200); // initialize serial communication at 115200 bits per second:

  // Initialize sensor
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST, OX_ADDR)) //Use default I2C port, 400kHz speed
  {
    Serial.println(F("MAX30105 was not found. Please check wiring/power."));
    while (1);
  }

  byte ledBrightness = 60; //Options: 0=Off to 255=50mA
  byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
  byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
  byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
  int pulseWidth = 411; //Options: 69, 118, 215, 411
  int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

  particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings

  light_sensor_details();

  light_sensor_configure();

}

void loop()
{
  bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

  //read the first 100 samples, and determine the signal range
  for (byte i = 0 ; i < bufferLength ; i++)
  {
    while (particleSensor.available() == false) //do we have new data?
      particleSensor.check(); //Check the sensor for new data

    redBuffer[i] = particleSensor.getRed();
    irBuffer[i] = particleSensor.getIR();
    particleSensor.nextSample(); //We're finished with this sample so move to next sample

    Serial.print(F("red="));
    Serial.print(redBuffer[i], DEC);
    Serial.print(F(", ir="));
    Serial.println(irBuffer[i], DEC);
  }

  //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
  maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

  //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
  while (1)
  {
    //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
    for (byte i = 25; i < 100; i++)
    {
      redBuffer[i - 25] = redBuffer[i];
      irBuffer[i - 25] = irBuffer[i];
    }

    //take 25 sets of samples before calculating the heart rate.
    for (byte i = 75; i < 100; i++)
    {
      while (particleSensor.available() == false) //do we have new data?
        particleSensor.check(); //Check the sensor for new data

      redBuffer[i] = particleSensor.getRed();
      irBuffer[i] = particleSensor.getIR();
      particleSensor.nextSample(); //We're finished with this sample so move to next sample

      //send samples and calculation result to terminal program through UART
      Serial.print(F("red="));
      Serial.print(redBuffer[i], DEC);
      Serial.print(F(", ir="));
      Serial.print(irBuffer[i], DEC);

      Serial.print(F(", HR="));
      Serial.print(heartRate, DEC);

      Serial.print(F(", HRvalid="));
      Serial.print(validHeartRate, DEC);

      Serial.print(F(", SPO2="));
      Serial.print(spo2, DEC);

      Serial.print(F(", SPO2Valid="));
      Serial.println(validSPO2, DEC);
    }

    //After gathering 25 new samples recalculate HR and SP02
    maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

    light_sensor_read();

  }
}

void light_sensor_details () {

  sensor_t sensor;
  tsl.getSensor(&sensor);

  delay(500);

}

void light_sensor_configure () {

  delay(200);
  tsl.setGain(TSL2591_GAIN_MED);
  delay(200);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);
  delay(200);
  tsl2591Gain_t gain = tsl.getGain();

}

void light_sensor_read() {

  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;

  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}

```

The pulse oximeter part will function correctly with the last two lines of `setup()` and the last line of `loop()` commented. `light_sensor_details();`,`light_sensor_configure();` and `light_sensor_read();` respectively. The output with these two lines commented is as follows:

```
red=4229, ir=3967
red=4530, ir=3790
red=3629, ir=4104
red=3563, ir=5211
red=4555, ir=9076
red=7091, ir=16753
red=13068, ir=23695
red=10753, ir=11273
...
red=31031, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31044, ir=48283, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31017, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31027, ir=48306, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31022, ir=48291, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=31016, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30997, ir=48294, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30981, ir=48268, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30966, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
red=30981, ir=48293, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0
...
```
(An expected output given my finger wasn't on the sensor for this.)

If I uncomment the 2nd last line of `setup()` then it still manages to show the red and ir values but never starts to show the calculated values. Instead it will occasionally (unpredictably) show chunks of invalid characters, like so:

[![][1]][1]

Going further and uncommenting the other two lines simply locks up and prints nothing to the serial monitor.

Also to clarify the three light sensor related functions do work in their own file, I'll include it here for the sake of completeness:

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);

void setup()
{
  Serial.begin(115200); // initialize serial communication at 115200 bits per second:

  light_sensor_details();
  light_sensor_configure();
}

void loop()
{
  light_sensor_read();
}

void light_sensor_details () {

  sensor_t sensor;
  tsl.getSensor(&sensor);

  delay(500);

}

void light_sensor_configure () {

  tsl.setGain(TSL2591_GAIN_MED);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);

  tsl2591Gain_t gain = tsl.getGain();

}

void light_sensor_read() {

  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;

  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}
```
Running this outputs:
```
...
Lux: 41.283641
Lux: 36.879783
Lux: 10.549278
Lux: 2.826355
Lux: 11.158865
Lux: 1.489472
Lux: 1.713600
Lux: 31.461915
Lux: 48.357471
Lux: 50.827312
...
```

I think the issue is something to do with the I2C bus, but because both sensors use their own libraries for communication I can't use the online examples for manually starting and stopping communication with the *Wire* library. I can't find anyone else online with this issue or any examples of multiple I2C devices that I'm able to make use of (to my understanding).

Am I on the right track with it being an I2C problem? Is there a simple fix that I'm simply unaware of? Or is there a separate issue with my code?

Many thanks for any help!

Edit: Changed Title

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

body:
It turns out the issue was with limited dynamic memory. The MAX30105 requires a lot of space for its calculations and adding anything else, whether that be another sensor or even a software serial connection, would crash it. Even using `Serial.println()` put it over the edge. **It became unstable beyond around 89% full, or about 250 bytes of empty dynamic memory.**

I ended up using a 32u4 equipped board to solve the memory issue and it worked perfectly after that.

It had nothing to do with I2C.


message:
Driving APA102C strips from Mega 2560

I have written (cobbled together from code snippets) an Arduino program that pushes various patterns down 160 APA102C LED strips (5). I originally was using a 5V 40A power supply and everything worked peachy. That was when the length from the clock and data pins was maybe 6-8 inches. Now I am try to get ready for a XMAS parade and attaching 100 LED strips. I have the power but the data and clock pins aren't getting to the strips. Is there some quick and dirty (not a real electronics guy here, just a code pusher) method to get signals out to the strips, maybe 6 feet? I would greatly appreciate any help I could get and I'm sure the kiddies would have Santa throw some extra goodies your way if I could get this figured out. I've got like 10 days.....YIKES!!!!

Thanks so much!!!!
And Happy Holidays

Joe B

body:
For a quick and dirty way you could cut a few LEDs from your strip, so that you have a number of single LEDs. Then you can place one LED after X feet of cable. Each LED receives its own data and outputs the signal for the next LED. So the signal after an LED is of the same quality as of the first signal. At least that is what can be done with other similar RGB LED strips. I would bet, that this is also the case for this type.

Before wiring everything up you should probably experiment a bit with the cable length. Test how long you can make the cable until you see problems. Then make the cables inbetween the LEDs shorter than that.

If you don't want these intermediate LEDs to light up, you can set them to off in your program.

Another - not so quick and dirty - way would be to put one microcontroller near the start of each cluster of strips (where one or multiple or all strips start) and let them communicate with a master microcontroller using an interface for longer distances (like RS485).

Depending on your situation the quick and dirty method might be enough.


message:
Arduino code works when connected to laptop, not when connected to battery or wall socket

So I have an Arduino nano, and I am using two SG90 servos, and 1 BMP280, and 1 MPU6050. My code works fine when I plug my nano into my computer, but when I connect the battery to my nano, it doesn't run. The servo moves to 90 degrees, but it seems that it is not detecting the sensor data and not moving the servo. I commented out all calls to `Serial`.
Here is my code:
```
/***************************************************************************
  This is a library for the BMP280 humidity, temperature & pressure sensor

  Designed specifically to work with the Adafruit BMP280 Breakout
  ----> http://www.adafruit.com/products/2651

  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
  to interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

// MPU
#include <MPU6050.h>

// Servo
#include <Servo.h>

Servo servoY;
Servo servoX;

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

#define BMP_SCK  (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS   (10)

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void pitch_roll_yaw(){
  // Serial.print("Pitch: ");
  // Serial.println(pitch);

  // Serial.print("Roll: ");
  // Serial.println(roll);

  // Serial.print("Yaw: ");
  // Serial.println(yaw);
  int thsjsojf = 1;
}

void setup() {
  // Servo
  servoY.attach(8);
  servoY.write(90);

  servoX.attach(9);
  servoX.write(90);

  // Serial.begin(115200);
  // while ( !Serial ) delay(100);   // wait for native usb
  // Serial.println(F("BMP280 test"));
  unsigned status;
  //status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
  status = bmp.begin();
  if (!status) {
    // Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
    //                   "try a different address!"));
    // Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16);
    // Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
    // Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
    // Serial.print("        ID of 0x60 represents a BME 280.\n");
    // Serial.print("        ID of 0x61 represents a BME 680.\n");
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */

  // MPU
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    // Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

}

int incrementPitch = 0;
int curAngle = 90;
int incrementPitchDown = 0;

void loop() {
    timer = millis();
    // Read normalized values
    Vector norm = mpu.readNormalizeGyro();

    // Calculate Pitch, Roll and Yaw
    pitch = pitch + norm.YAxis * timeStep;
    roll = roll + norm.XAxis * timeStep;
    yaw = yaw + norm.ZAxis * timeStep;

    float normalY = norm.YAxis;

    // Serial.print(F("Temperature = "));
    // Serial.print(bmp.readTemperature());
    // Serial.println(" *C");

    // Serial.print(F("Pressure = "));
    // Serial.print(bmp.readPressure());
    // Serial.println(" Pa");

    // Serial.print(F("Approx altitude = "));
    // Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
    // Serial.println(" m");

    // pitch_roll_yaw();

    //TODO: This works, but if pitch > 1 and the servo arm is already at max, it doesn't move. Fix.
    // TODO: If pitch < 1. move the servo in the opposite way by 5 degrees. Need to track current angle.
    if(pitch>1){
      // Serial.println("PITCH IS GREATER++++++THAN 1, MOVING Y SERVO");
      servoY.write(curAngle+incrementPitch);
      curAngle = curAngle+incrementPitch;
      // Serial.print("Pitch: ");Serial.println(pitch);
      if(curAngle>180){
        // This is just so we don't print the current angle if curAngle > 180. This can be antything.
        int something = 1;
      } else {
        // Serial.print("Current Angle of Y servo: ");Serial.println(curAngle);
      }
      incrementPitch+=6;
    } else if(pitch<-1){
      // TODO: If pitch is < -1, then we move the servo in 5 degree increments starting at the current angle. Right now it jumps some degrees, check the if(pitch>1) for errors? MUST FIX.
      // Serial.println("Pitch is LESS---------THAN 1, MOVING Y SERVO");
      servoY.write(curAngle-incrementPitchDown);
      curAngle = curAngle-incrementPitchDown;
      incrementPitchDown+=6;
    }

    // Serial.println();
    delay(200);
}
```
ALso, none of the other threads solve my problems.

body:
If are you powering the servo's via your Nano (and thus the USB port), this will cause problems. The Servo's need need 500/700 mA each (>1 Amp total). My laptop USB is 500mA, so rotating two servo's will cause a power drop (voltage goes down due the draw of current).

in my experience using servo's when connected to a computer/laptop is not reliable. This will happen: the servo rotates, the power drops causing the Microcontroller to restart or cause problems (voltage) for the  sensor.


message:
How do I put a LiquidCrystal_I2C class in a Lcd class?

I want to make my main code cleaner so I was thinking of making a Lcd class which I can use every time I need to print on lcd. So my main code every time I try to print text I need to call :
```
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Text 1st line");
lcd.setCursor(1,0);
lcd.print("Text 2nd line");
```

The problem is I need to create a class called Lcd which initialises the LCD display through LiquidCrystal_I2C.h and calls it's functions in order to print as I want.
Below I will post some code which is totally wrong but I guess it can give you the idea of what I am trying to do:

**LcdControl.hpp**

```
class LcdControl{
    public:
        LcdControl();
        void printOnLcd(int data,int column,int line);
        void printOnLcd(char data,int column,int line);
};
```

**LcdControl.cpp**

```
#include <LiquidCrystal_I2C.h>
#include <Arduino.h>
#include "LcdControl.hpp"

LcdControl::LcdControl(){
    LiquidCrystal_I2C lcd(0x27,20,4);
    lcd.init();
    lcd.init();
    lcd.backlight();
}

void LcdControl::printOnLcd(int data,int column,int line){
    lcd.clear();
    lcd.setCursor(column,line);
    lcd.print(data);
}

void LcdControl::printOnLcd(char data,int column,int line){
    lcd.clear();
    lcd.setCursor(column,line);
    lcd.print(data);
}
```

body:
Potentially, your `lcd` local of the constructor becomes member instead:

```c++
class LcdControl{
    public:
        LcdControl();
    // ...
    private:
        LiquidCrystal_I2C lcd;
```

There it is accessible from all of your member functions and (without splitting hairs) exists for the lifetime of `LcdControl` variable. The way you have it currently the `lcd` instance is [local to][1] the constructor, so inaccessible elsewhere (e.g. inside `printOnLcd()`) and dies when the constructor returns.

The construction of the `lcd` member happens in the `LcdControl()` [member initializer list][2]:

```c++
LcdControl::LcdControl()
    : lcd(0x27,20,4)
{
```

Newer standards of C++ allow some forms of initialization to be done where it's declared as member. I'm not going to recheck the standards now. But the above way should work regardless of which Arduino core and version you have.

The call to the lcd's `init()` may need to be done in an counterpart `init()`/`begin()` in your own class. When you do something that can fail in the constructor you have little opportunity to detect/handle this when done in the constructor on an embedded device like an Arduino where your class may be to make a global and where exceptions aren't supported; some Arduino's support exceptions and some don't. For an Arduino fallible part of initialization/contruction of often separated out so you can control how and where/when that failure happen, often in `setup()` and without reliance on exceptions.

There are a lot of ways to achieve something similar. The above seems closest to what you're attempting in the question. It may not necessarily make the most sense in your particular usage. You can want to have the class have a member pointer or member reference instead of a member instance, but you need to be more careful about their respective lifetimes. It is often a mistake to do initialization in inner layers of your code without providing the user of it any control. E.g. not allowing the user of your `LcdControl` class to initialize it's own `LiquidCrystal_I2C` instance and pass that in or to allow passing in the parameters for the `LcdControl` class to use.

  [1]: https://www.arduino.cc/reference/en/language/variables/variable-scope-qualifiers/scope/
  [2]: https://en.cppreference.com/w/cpp/language/constructor


body:
You could also use an inheritance model where the the base class is the original library LiquidCrystal_I2C and you simply create a new derived class, in this case LcdControl. In LcdControl, you simply pack in your additional methods. The only slight complexity is that you have to invoke the constructor of the base class LiquidCrystal_I2C when the constructor of the derived class LcdControl is called.

Here it is in a simulation:  https://wokwi.com/projects/349238619253244498

Code:

```
#include <LiquidCrystal_I2C.h>

class LcdControl : public LiquidCrystal_I2C {
  public:

    LcdControl( uint8_t lcd_Addr, uint8_t lcd_cols, uint8_t lcd_rows) :
      // base class constructor
      LiquidCrystal_I2C ( lcd_Addr, lcd_cols, lcd_rows ) {
    }

    void printOnLcd(const char * data, int column, int line) {
      LcdControl::clear();
      LcdControl::setCursor(column, line);
      LcdControl::print(data);
    }

} ;

LcdControl lcd(0x27, 20, 4);

void setup() {

  Wire.begin() ;
  lcd.init() ;
  lcd.backlight();

  lcd.printOnLcd( "hello world2", 0 , 0 ) ;
  delay(1000) ;

  lcd.printOnLcd( "hello world3", 1 , 2 ) ;

}

void loop() {

}

```


message:
3.5mm jack frequency response at low frequency (20Hz)

I'm trying to drive a bass shaker at low frequencies, down to 20Hz, with an Arduino. Has anyone ever done something like this?

I found an audio amp that takes in 3.5mm aux, and I was hoping to get a 3.5mm jack to drive the amp from an Arduino. However, I can't find any technical specs on audio jacks so I am not sure if they support low frequencies. Are there any audio jacks with frequency response data available?

If not, are there other ways to achieve this?

body: You can send DC (i.e. 0 Hz) through an audio jack, so I would not worry about its low-frequency response.


message:
Fubarino (microchip pic32mx), Second timer interrupt is not firing

```
volatile uint32_t counter_timer = 0;
void __USER_ISR myISR() {
  counter_timer++;
  clearIntFlag(_TIMER_3_IRQ);
}

void __USER_ISR myISR_timer_four() {
  clearIntFlag(_TIMER_4_IRQ);
  TMR4 = 0x16E3600;
  Serial.print("hi\n");
    if(PORTAbits.RA10 != 1){
      LATAbits.LATA10 = 1;
    }
    else{
      LATAbits.LATA10 = 0;
    }
}

void setup{

  T3CONbits.TCS = 0b0; // Timer Clock Source Select bit
  T3CONbits.TCKPS = 0b000; //0b111; // Timer Input Clock Prescale Select bits
  T3CONbits.ON = 0b1; //0;//0b1;
  asm("nop \n");

  T4CONbits.TCS = 0b0;
  T4CONbits.TCKPS = 0b000;
  T4CONbits.T32 = 0b1;
  TMR4 = 0x16E3600; // half of 48mHz.
  T4CONbits.ON = 0b1;

  setIntVector(_TIMER_3_VECTOR, myISR);
  setIntPriority(_TIMER_3_VECTOR, 4, 0);
  clearIntFlag(_TIMER_3_IRQ);
  setIntEnable(_TIMER_3_IRQ);

  setIntVector(_TIMER_4_VECTOR, myISR_timer_four);
  setIntPriority(_TIMER_4_VECTOR, 1, 0);
  clearIntFlag(_TIMER_4_IRQ);
  setIntEnable(_TIMER_4_IRQ);

 TRISAbits.TRISA10 = 0;  // Fubarino onboard yellow led
}

void loop() {
delay(500);
Serial.println(counter_timer);
Serial.println(TMR4, DEC);
}
```

Hi,

i wanna use multiple interrupts, i got the information from a document i got from: Majenko Technologies.
the interrupt bound to Timer3 works, this was the example code in the pdf.
now i "assembled" a second interrupt bound to timer4, copy, paste and adapt, but that isn't working.

i can print the "content" of the timer4 register and it's running.

have i done something wrong?
search engine didn't yield a answer.

body: The problem was that you need to combine the even and the next odd timer (see datasheet of the microchip pic you're using) to form a 32 bit timer.


message:
Simple FastLED sketch that crashes when led strip is long but not when its shorter

I have a pretty simple sketch that crashes, and crashes hard (Platform.io console says "Disconnected (read failed: [Errno 6] Device not configured)" and I need to power off/on the Arduino to continue.

The sketch does not crash and seems to work fine when I use a smaller number of LEDS but crashes after a few seconds when I use a longer number of LEDS.  Seems like a strange hardware issue because the sketch looks simple! I have added a lot of Serial.print(ln)'s to verify it is doing what I think it is, and it does... until the crash!

This will run forever, but if I change cNumLeds from 60 to 160 it crashes (and my actual LED strip has 300 LEDs and I use all of them in other sketches).

    #include <Arduino.h>
    #include <FastLED.h>

    const uint16_t cDataPin = 15;
    const uint16_t cNumLeds = 60;

    CRGB leds[cNumLeds];

    void setup() {
       Serial.begin(9600);
       FastLED.addLeds<WS2812B, cDataPin, GRB>(leds, cNumLeds).setCorrection(TypicalLEDStrip).setDither(true);
       FastLED.setBrightness(127);
       FastLED.clear();
       FastLED.show();
       FastLED.delay(100);
    }

    uint16_t offset = 0;
    CRGB colors[] = {CRGB::White, CRGB::Red, CRGB::White, CRGB::Green, CRGB::White, CRGB::Black};
    byte numColors = sizeof(colors)/sizeof(colors[0]);
    uint32_t cycle = 75;

    void loop() {
      EVERY_N_MILLISECONDS(cycle) {
        for (uint16_t i = 0; i < cNumLeds; i++) {
            leds[i] = colors[(i + offset) % numColors];
        }
        offset = (1 + offset) % cNumLeds;
      }
      FastLED.show();
    }

Any tips for debugging greatly appreciated ! (And apologies in advance for my C++ style, I am a confirmed C programmer trying not to do any damage in C++)

body:
> powering from the 5V Arduino pin.

You should not do this. You can fry the voltage regulator or the protection diode doing this (depending on how you supply the power).

When you draw more current from a power source than it can supply, first the voltage will drop. If the voltage drops enough the Arduino will brown out and reset as soon as the voltage is up again. If you keep drawing that much power, you can fry parts of the power source (in this case your Arduino). Sometimes this is reversible, when the power source has some kind of emergency shutdown (like the voltage regulator of a genuine Arduino Uno). Otherwise it will get destroyed.

When controlling power hungry devices like LED strips you should connect their power lines directly to your power supply (given it has the correct voltage). That way the current doesn't have to flow through the Arduino. Also you need a power supply, that can handle your peak current. The RGB strips with WS2812 drivers can draw up to 60mA per LED (on white in full brightness). So for a strip with 160 of them it would be a current of `60mA * 160 = 9.6A`. Add a little headroom and you would need a power supply, that can at least provide 10A of current.

> But i have run other sketches, much more complex, on the whole of the 300 led strip, so not sure I get why this sketch is having a power issue.

We haven't seen your previous sketches. But most likely you had a lower current, because you didn't light up all LEDs at once and/or only at lower brightness. The drawn current depends on how bright you set each LED (to be specific each color of each LED, since one RGB LED is actually 3 LEDs with the colors red, green and blue in one casing). So your current was low enough to not brown out the power from the Arduino.


message:
Arduino Nano Doesn't Upload Any Code After Connecting It In Reverse (Rotated 180°)!

I've Made A PCB Which Includes An Arduino Nano. I Soldered Some Female Pin Headers Instead Of Soldering The Arduino Itself, So That I Can Easily Plug/Unplug The Arduino Board.

It Was All Good, ***Until*** I Accidentally Plugged The Arduino Nano Rotated 180°, Which Made Arduino Pin(12) Connected To The Vin(11.1v) At The PCB, And Arduino (Tx) Pin Plugged Into Pin(13)'s Place At PCB, And So On ...

The PCB's Power Was On (11.1v @ VIN Place At The PCB).

Now,
 - When I Power The Arduino Board It Looks Normal, 5v Pin And Vin Pin Works Good, No Power Issues, But The  Arduino IDE doesn't Upload Any Sketches To It, It Gives Me This Error:
```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
```

- I Tried Burning Bootloader With The IDE It Gave Me This:
```
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Error while burning bootloader.
```

- I Tried To Upload Code With The IDE But Used USBsp Programmer, It Gave Me This:
```
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

the selected serial port
 does not exist or your board is not connected
```

- I Tried To Program The Board Using USBasp Programmer -with ICSP pins- and avrdude, It Gave Me This:

```
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.
```
- I Also Tried To Upload Code, Or Burn Bootloader Using Another Arduino, But Didn't Work!

- But When I Connect It To The Computer Using The Usb Cable, The IDE Detects It, And It Allows Me To Open The Serial Monitor!

***So, What's The Problem? Is It Completely Broken, Or It Can Be Repaired??***

I Suppose That The Atmega Is Burnt, As 11.1v Was On Pin(12), And Pin(11) Was Connected To Ground!!

body:
Apparently your Nano is dead.

Depending on the specific device and your skills, you can try to replace the AVR on it. Please be aware that you need to flash the bootloader on it.


message:
How to allow cross-domain requests with ESP8266WebServer.h ? - CORS policy: Access-Control-Allow-Origin

With an nodeMCUv2 I want:
- to start a wifi server with ESP8266WebServer.h
- serve a root html page which will interact with the ESP and fetch external data

**Issue:**
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'

Tried to make CORS happy, by either one of the followings, but didn't help:

.sendHeader("Access-Control-Allow-Origin", "*");

.enableCORS(true);

```
#include <ESP8266WebServer.h>
ESP8266WebServer srvAmb(80);
void handleRoot(){
// srvAmb.sendHeader("Access-Control-Allow-Origin", "*");
   srvAmb.enableCORS(true);
   srvAmb.send(200,"text/html; charset=utf-8", myRootWebPagWithJSExternalFetch);
}
void setup(){
...
    srvAmb.on("/", handleRoot);
...
```
Part of the served root html page:

```
try{
  const Qresponse = await fetch( "https://zenquotes.io/api/random" );
  const Qdata = await Qresponse.json();
  console.log(Qdata);
  ...
} catch (error) {
  console.error(error);
}
```
Console log in Chromium:

> Access to fetch at 'https://zenquotes.io/api/random' from origin '192....' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So, how does one fetch external data from the browser running on PC, smartphone, etc?

Thanks

P.S. One could ask the server to fetch the data, prior to supplying the html page, but that's not esp server's job.

P.P.S. I hadn't the credit to create tag keywords such as:
fetch, CORS, Allow-Origin, policy

REM: under https://arduino.stackexchange.com/questions/58457/how-to-allow-cross-domain-requests-on-esp8266webserver/91419#91419

it is suggested that .sendHeader("Access-Control-Allow-Origin", "*") could be deprecated, very well but ArduinoIDE does not raise any warning; anyway suggested solution fails.

Looking at the source code https://github.com/esp8266/ESPWebServer/blob/master/src/ESP8266WebServer.cpp,
the method sendHeader() on line 238, has a 3rd parameter(a boolean) that if set to true, puts before the passed name & value before the already passed header, otherwise puts it after, aka the declarative order is important.

Viz, what's the valid header the esp server needs to send??
Especially, has Chromium details, states:

> Request URL: zenquotes.io/api/random

> Request Method: GET

> Status Code: 200

> Referrer Policy: strict-origin-when-cross-origin

See also: https://javascript.info/fetch-crossorigin

body:
The issue is URL specific.

Indeed, if I change API, namely

    const Qresponse = await fetch( "https://zenquotes.io/api/random" );

by for example:

    const Qresponse = await fetch( "https://api.open-meteo.com/v1/meteofrance?latitude=49.71&longitude=4.16&daily=sunset&timezone=Europe/Berlin" );

then it works.

I presume that I comes from network developper tools info in Chromium:
> Referrer Policy: strict-origin-when-cross-origin

claiming a strict origin for zenquotes.io's API.
My esp server code being:

    void handleRoot(){
        srvAmb.sendHeader("Access-Control-Allow-Origin", "*", 1);
        srvAmb.send(200,"text/html; charset=utf-8", myRootWebPagWithJSExternalFetch);
    }

Remark, with or without the additional 3rd param of sendHeader() it works.


message:
Fading out a led with reed switch loop

I was hoping to get some help on the fading led which I am working on.

For my project I need to have a led, which when it is placed next to a magnet, continuously shines, but as soon as it is taken away it has to fade out in a certain amount of time. So far I managed to write the code which detects when the light is taken away from the magnet and fades out, but when the magnet is nearby again, the led lights up and keeps shining, no matter  if I take it away from the magnet or not. So how I could solve this? I tried to exit the loop function, but then this process happens only once, which is not what I want. I am also using reed switch to detect the magnet, but if you have other sensor suggestions, let me know. I'm including the code down here.

Thank you for your help in advance:)

    int ledPin = 9;
    int brightness = 255;
    int fadeAmount = 5;
    const int reedPin = 2;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(reedPin, INPUT_PULLUP);
    }

    void loop() {
      int proximity = digitalRead(reedPin);
      if (proximity == HIGH) {
        Serial.println("Switch opened");
        while (brightness >= 0) {
          analogWrite(ledPin, brightness);
          brightness = brightness - fadeAmount;
          delay(30);
          Serial.println(brightness);
        }
      }
      else {
        Serial.println("Switch closed");
        analogWrite(ledPin, brightness);
        Serial.println(brightness);
      }
    }

body:
Your current problem probably comes from the fact, that you execute the fading loop, even if `brightness` is already zero, and that you don't reset it to zero after fading.

    while(brightness >= 0){
       ...
       brightness = brightness - fadeAmount;
       ...
    }

Imagine we are at the point, where `brightness` is 5. The while condition is true, since 5 > 0. Then we execute the code in the loop, setting `brightness` to 0. We again check the while condition. It is still true, since `0>=0`. So after executing the code in the loop again, `brightness` is now -5. But `analogWrite()` only takes a 1 byte unsigned (!) integer, aka `uint8_t`, while `int` is a 2 byte signed (!) integer. So only the lower byte of that integer will be used and interpreted as unsigned. So -5 gets interpreted as 251, which you see as lighting up in full brightness.

Easy fix would be to set `brightness` to zero after the while loop:

    brightness = 0;

---

That said, I would suggest a completely different route, which will make your code way more responsive, by using the non-blocking coding principle from the `BlinkWithoutDelay` example, that comes with the Arduino IDE.

As you did, I would use a global `brightness` and `fadeAmount` variable, but also one to hold a timestamp:

    unsigned long timestamp=0;

Then in `loop()` we can first do the fading to zero by using the `millis()` function as a clock:

    if(millis()-timestamp > 30){
        brightness = brightness - fadeAmount;
        if(brightness < 0) brightness = 0;
        timestamp = millis();
    }

That will decrement the `brightness` variable to zero without blocking with a `delay()`. The speed can be changed by changing the number `30` to something different. This number has the unit milliseconds.

Then we can check for the reed switch and set `brightness` to 255, if it is activated:

    if(!digitalRead(reedPin)){
        // reedPin is LOW
        brightness = 255;
    }

So as long as the magnet is at the reed switch, this code will set `brightness` to 255.

And finally we need to write the value of `brightness` to the output pin:

    analogWrite(ledPin, brightness);

So as a full code:

    int ledPin = 9;
    int reedPin = 2;

    int brightness = 0;
    int fadeAmount = 5;
    unsigned long timestamp = 0;

    void setup(){
        pinMode(ledPin, OUTPUT);
        pinMode(reedPin, INPUT_PULLUP);
    }

    void loop(){
        if(millis()-timestamp > 30){
            brightness = brightness - fadeAmount;
            if(brightness < 0) brightness = 0;
            timestamp = millis();
        }

        if(!digitalRead(reedPin)){
            // reedPin is LOW
            brightness = 255;
        }

        analogWrite(ledPin, brightness);
    }

I've tested this with a normal button (currently no reed switch here). It should work as expected.


message:
PWM with a TRANSISTOR on flexible LED filament

I would like to create a custom lighting, with **PWM** capability, powered **from battery**. I would like to use **flexible led filaments**, and since those **consumes more than 40mA**, I can't use them directly on a board. I found a link explaining to use a **MOSFET** transistor, to dim my leds. So the transistor that I need would be one with a 5v power supply, and a 5v Voltage input.

The problem is that I can't find any transistor matching those specs. I also noticed that they have a heatsink, which mean that they need to dissipate heat, and are therefore not power efficient (which i do not like). Am I missing something ?

Any help will be apreciated, thanks !

  [1]: https://arduino.stackexchange.com/questions/38398/how-to-drive-500w-of-leds

body:
Welcome! You are missing some information. A transistor will work but you will lose about 0.7 Volts when it is on. That voltage times the current will tell you how many watts it needs to dissipate. The data sheet will give you all this information.  The transistor is a current controlled device so there will not be a Base voltage rating. You can determine the current for the base by dividing the load current by the HFE then adding a bit.

By connecting more than 20 mA to the port pins especially more than 1 may destroy the Arduino. Surprise the LED is also a current device so you need to limit the current into it. This can easily be done with a resistor.

The MOSFET would be the easiest solution. Put a resistor maybe 10K from the port pin to ground. The reason is the port pins are floating from power on until your software defines and sets there level. Then connect the port of the Arduino to the gate of the MOSFET which has its source grounded. Connect the LED(s) to the drain and place a resistor in series with the LED and + voltage. It can be 12 Volts or whatever you like. You will need to size the current limiting resistor to the LED(S) appropriately and be sure the voltage rating of the MOSFET is at least 10% higher then the voltage.

There is a great book available called the Arduino Cookbook, getting that and reading it will be a big help to you.


body:
You cannot find a MOSFET with that exact rating, because transistors can be used with all voltages inside of their specific limits. Most MOSFETs can be used with way higher voltages than 5V.

What you need is a logic level MOSFET, which means, that it will be in saturation (aka being fully ON) at the typical logic level of 5V on its gate. In the datasheet of a MOSFET you will find a diagram which shows the drain current depending on the gate-source voltage. At your logic level (5V in this case) you want the curve approaching a plateau.

Another important value is `R_DS(on)`. That is the resistance of the MOSFET when its on. The lower the resistance, the lower will the power lost to heat.

> I also noticed that they have a heatsink, which mean that they need to dissipate heat, and are therefore not power efficient (which i do not like).

Every MOSFET dissipates some energy as heat, since no MOSFET can have `R_DS(on)` of zero. The typical heat sink flap is meant to dissipate the heat for keeping the MOSFETs temperature in the specified range, even when drawing the maximum specified current. The datasheet of a MOSFET has a section with maximum ratings. There you should see the maximum drain current `I_D` with its corresponding needed temperatures. For example have a look at [this datasheet][1] of a random logic level MOSFET from mouser. There is no specification of how hot the case gets with a specific current, since this depends on the suroundings, but the datasheet states, that it will support up to 80A, when you keep the case to a temperature of 25°C.

It also states what electrical power it can dissipate with its package: `P_D`. You should look at how much current you need for your LED filament. You can calculate the dissipating power with `P = R * I²` (P being power, R the resistance R_DS(on) and I the current through the MOSFET).

  [1]: https://eu.mouser.com/datasheet/2/308/1/FDP5800_D-1808068.pdf


message:
Ability to calculate bearing related distance with Arduino GPS

Pardon if there's a more precise/technical way of formulating this question :)

What I'm currently working on is a proximity warning with Arduino. There's a preset GPS location in the sketch and if I'm moving closer to it, once I cross a set distace threshold, action is triggered.

I think picture will do better explaining on what challenge I wish to overcome here. Calculating simple "straight line" distance between my current geolocation and the preset destination is easy, but as you can see in the illustration I made, it works from all directions.

100 meter from the target is valid here from any point, or any bearing that the subject might be approaching, which is tedious and not what I want to achieve.

Lower illustration shows what I'd wish to achieve - achieve the trigger criteria only if approaching the destination from certain "bearings"...if that's the right way to phrase it. Hope someone understands what I'm trying to do, if you have some pointers where to start looking and if this can even be achieved on Arduino - do let me know :) Thanks a lot

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

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

body:
Before suggesting a possible solution consider these aspects of the problem:

 1. The question assumes a "flat earth".  For small distances this assumption likely contributes an error that can be ignored.  For larger distances consider calculating the [great circle distance][1].
 2. Consider not every GPS module populates all [NMEA][2] fields.  If bearing is supplied consider it is not valid unless the GPS module has moved more than the current accuracy of that GPS module.

While the criteria is simple (only alarm when approaching a given latitude and longitude (or [MGRS][3] coordinate) while traveling on a certain bearing), the implementation can be troublesome and / or tedious.  Consider noise.  The position of the GPS module might vary 10 meters while stationary.  Resulting in a false bearing.  The person carrying the GPS may not walk a straight line.  This additional noise may result in never raising an alarm.  If the GPS is carried in a car, roads may not exist for direct travel to the given latitude and longitude. Again, the alarm may never be given.

As it turns out, the assumptions made here indicate bearing is not a good criteria when determining direction of approach to a given latitude and longitude.  Rather, it may be simply the relation between the current latitude and longitude and the given latitude and longitude that offers the best solution.

  [1]: https://en.wikipedia.org/wiki/Great-circle_distance
  [2]: https://www.gpsworld.com/what-exactly-is-gps-nmea-data/
  [3]: https://en.wikipedia.org/wiki/Military_Grid_Reference_System


message:
How "fast" could GPS data be refreshed while moving and does it depend on the mcu?

I'm using Nano Every and SIM33EAU GPS module for my project and today I went riding shotgun to test how it works when moving on the road. I am using u8g2 library and one of the things that I have printed on the screen is gps.course.deg - which is as the name suggest, course of the GPS module's movement in degrees.

Next to my Arduino device I had a phone with some compass app, and the course was somewhat correct while we were moving at normal traffic speed, but the update rate was vastly different and I don't know why. The only "delay" in the sketch I have is this;

      if (gps.location.isUpdated())
      {
        Serial.print(F("Lat Lon = "));
        Serial.print(gps.location.lat(), 6);
        Serial.print(", ");
        Serial.println(gps.location.lng(), 6);
      }

      else if (millis() - last > 500)
      ...

I wasn't able to check the Serial Monitor as I didn't have a laptop, so only reading from GPS module was what was being printed on the small OLED screen. So is the lagging update something on the GPS module side and how it works, or is it perhaps OLED not being able to refresh?

body:
GPS modules deliver position updates in very different frequencies, depending on model and configuration (where changeable). Cheaper modules only provide an update every 1 second, while better ones have 5 or 10 Hz position update. Check the documentation for your module to get that information.

Additionally, it is of course possible to "cheat", by calculating an extrapolation, using the last position, direction and speed. Since speed and direction don't typically change very quickly, that works quite well and can give position updates at arbitrary rates.


message:
Stoplight Simulator - White LED not turning on with button press

I am working on a relatively simple stoplight simulator that uses four LEDs - red, green, yellow, and white - in addition to a button. The 3 colored stoplight LEDs cycle as a real stoplight would. If the button is pressed while the green LED is on, the white light should turn on while the green light is still on (this can only be allowed to happen once). Previously, the stoplight cycle didn't work, but now the white light isn't turning on with the button press (see below)

Edit: The stoplight cycle now works, thanks to all your input, but the white light still doesn't come on when I press the button. This could be an issue using delay instead of millis(), but I'm not sure the easiest way to implement a fix. Any tips? My code is below. Thank you!

```
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay = 4000; //adjust test timings to reqs
const int y_delay = 2000;
const int r_delay = 3000;

int g_ledState;
int buttonState;
bool counter = false;

const int buttonPin = 2;

//green led function with conditional for white led
void green_light(){
  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState = 1;
  buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && g_ledState == 1 && counter == false){
  digitalWrite(w_led, HIGH);
    counter = true;
  }
  else{
    digitalWrite(w_led, LOW);
    counter = true;
  }
}

void yellow_light(){
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void red_light(){
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
//main stoplight cycle
  green_light();
  delay(g_delay);
  yellow_light();
  delay(y_delay);
  red_light();
  delay(r_delay);
}
```

body:
You need to try it this way

```
allowed to happen once). My code compiles, but none of the lights turn on when I run it. I'm pretty sure I set the circuit correctly, so I want to see if I'm missing any issues in my code (below). Thank you!

//variables
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay = 1000;
const int y_delay = 500;
const int r_delay = 1000;
int g_ledState;
int buttonState;

const int buttonPin = 2;

//LED functions
void green_light(){

  int counter=0;

// conditional to let button turn on the white LED IF green LED is on and the white LED cycle hasn't already been run
if (buttonState == HIGH && g_ledState == 1 && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);
    counter=0;
  }

  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=1;
  button state=digitalRead(buttonPin);

}

void yellow_light(){
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void red_light(){
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  g_ledState=0;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

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

//main stoplight cycle
  green_light();
  delay(g_delay);
  yellow_light();
  delay(y_delay);
  red_light();
  delay(r_delay);

}

```

Note that using delay is not that advisable but this way might help.

Here is another method using millis(), note that it hasn't been tested with arduino. If the compiling gives an error try modifying some things

```
//variables
const int g_led = 3;
const int y_led = 4;
const int r_led = 5;
const int w_led = 6;
const int g_delay;
const int y_delay;
const int r_delay;
int g_ledState;
int buttonState;
int oldbuttonState;
const int buttonPin = 2;

/* you can remove this one
Switch (white){
case 1:
//do nothing
break;

case 2 :
   buttonState=digitalRead(buttonPin);

   // conditional to let button turn on the white LED IF green LED is on and the white LED cycle hasn't already been run
if (buttonState == HIGH && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);

  }
counter=buttonState;
//switch to case 3
 white=3;
break;

case 3 :
//switch back to case two and continue reading the button
white=2;
break;
*/

}
//LED functions
void green_light(){

  digitalWrite(g_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);

// start reading the button
  // I added this for better performance
int rep=millis;
while((millis-rep) < 3000){
digitalRead(buttonpin);
if (buttonState == HIGH && counter == 0){
  digitalWrite(w_led, HIGH);
    counter =1;
  }
  else{
    digitalWrite(w_led, LOW);

  }
counter=buttonState;

}
  g_delay=Millis();

}

void yellow_light(){
//stop button reading
  white=1;
  digitalWrite(y_led, HIGH);
  digitalWrite(g_led, LOW);
  digitalWrite(r_led, LOW);
  digitalWrite(w_led, LOW);
  y_delay=millis();

}

void red_light(){
 //stop button reading
  white=1
  digitalWrite(r_led, HIGH);
  digitalWrite(y_led, LOW);
  digitalWrite(g_led, LOW);
  digitalWrite(w_led, LOW);
  r_delay=millis();
}

Switch (cases){
//main stoplight cycle
case 1 :
  green_light();
  /// wait for 3 seconds
  if (millis() - g_delay >=3000){
     yellow_light();
}
 cases=2;
 break;

case 2 :
  /// wait 2 seconds
  if (millis() - y_delay >=2000){
     red_light();
}
cases=3;
break;

 case 3 :
 // wait 5 seconds
  if (millis() - r_delay >=5000){
      cases=1;
}
cases=1;
break;

}

void setup() {
  // put your setup code here, to run once:
  pinMode(g_led, OUTPUT);
  pinMode(y_led, OUTPUT);
  pinMode(r_led, OUTPUT);
  pinMode(w_led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

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

}

```

It haven't been tested but just try it out


body:
You don't have any circuit details... SO...

Where most indicator LEDs need 2 to 2.2 volts and 8 to 25mA,
white LEDs typically need 3.1V and 25mA minimum to turn on.

Also micro processors have limits to the current a pin can deliver
If you are using a 3.3v micro not all the voltage will make it to the LED.

look up the spec sheets on the micro and white LED.  I have a feeling you are going to find either the micro pin or the supply an issue.

Try switching out a colored LED for testing the code.
If the LED works then try going to some driver circuit to power the white LED.


message:
Passing variable into catch() exception

I'm working with a try{} catch(){} exception right now and I want to change a Variable. For this my board has to connect to the Internet and with a try{} statement it will try to do so. If it fails I simply want to set the variables to 0.

      try {
        timeClient.update();
        ntp_seconds  = timeClient.getSeconds();
        ntp_minutes = timeClient.getMinutes();
        ntp_hours = timeClient.getHours();
      }
        catch () {
         ntp_seconds = 0;
         ntp_minutes = 0;
         ntp_hours = 0;
      }

I am getting this error: Compilation error: expected type-specifier before ')' token
I know that I somehow have to pass my variables into the catch() "function" but somehow I can't pass variables in like I would with normal functions.

body:
The Arduino IDE does not support the C++ try/catch exception handling construct and explicitly disables this feature.
See: https://forum.arduino.cc/t/try-catch/180063 for a fuller explanation.


body:
You might want to refresh your knowledge about the `try`-`catch` statement by reading the respective chapter in your C++ book.

You need to declare an exception parameter in `catch`, which you can ignore:

```c++
  try {
    timeClient.update();
    ntp_seconds  = timeClient.getSeconds();
    ntp_minutes = timeClient.getMinutes();
    ntp_hours = timeClient.getHours();
  }
  catch (exception& ignored) {
    ntp_seconds = 0;
    ntp_minutes = 0;
    ntp_hours = 0;
  }
```


message:
Does ADXL 345 accelerometer not wirk with Arduino Uno without soldering?

I followed the Adafruit tutorials to wire the ADXL 345 with Ardiuno Uno, but it is not able to detect the sensor.  It did not mention that I need to solder the ADXL 345.  Is soldering necessary?

body:
Some boards and wires are built so that plugging them together should work fine.  For example the following picture [from embedded.com][1] of an Arduino, ready made wires with pins at the ends and a bread board should connect with no soldering:

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

And if your [Analog Devices ADXL-350 chip][3] is already soldered onto a [PCB][4] with 1/10 inch headers as in this picture [from Adafruit.com][5]:

[![enter image description here][6]][6]

... you should be able to connect the Arduino to the accelerometer with out soldering.

However, if the header and ADXL-450 PCB from Adafruit are not soldered together, as is the case in this picture:
[![enter image description here][7]][7]

... you will have to solder them as outlined on [this Adafruit web page][8].

  [1]: https://www.embedded.com/building-arduino-breadboards-without-jumper-wires/
  [2]: https://i.stack.imgur.com/vf1H5.png
  [3]: https://www.analog.com/en/products/adxl350.html#product-overview
  [4]: https://en.wikipedia.org/wiki/Printed_circuit_board
  [5]: https://www.adafruit.com/
  [6]: https://i.stack.imgur.com/Xaoc3.jpg
  [7]: https://i.stack.imgur.com/2p7ra.jpg
  [8]: https://learn.adafruit.com/adxl345-digital-accelerometer/assembly-and-wiring


message:
FastLED EVERY_N_SECONDS - does it generate static code?

I realize my question is not precise, so I have a simple contrived example to illustrate better what I am asking.

I am trying to use EVERY_N_SECONDS inside a member function of a class that is invoked in the sketch's loop() method. And this works fine, but when I have two instances of the class, each has its member function called in the loop(), but one instance seems to "win" and the other instance never seems to hit the inside of the EVERY_N_SECONDS block.

For example, the following code produces this output (I expected both a2 and a1 to appear in "a2 is in the EVERY_N_SECONDS loop"):

    a1 is in the loop
    a1 is in the EVERY_N_SECONDS loop
    a2 is in the loop
    a1 is in the loop
    a1 is in the EVERY_N_SECONDS loop
    a2 is in the loop
    a1 is in the loop
    a1 is in the EVERY_N_SECONDS loop
    a2 is in the loop

Here is the code, a silly little program to illustrate the question:

    #include <Streaming.h>
    #include <FastLED.h>

    class A {
    public:
     String tag;
     void loop()
     {
       Serial << tag << " is in the loop" << endl;
       EVERY_N_SECONDS(2) {
          Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
       }
     }
    };

    A a1, a2;

    void setup() {
      Serial.begin(9600);
      a1.tag = "a1";
      a2.tag = "a2";
    }

    void loop() {
      a1.loop();
      a2.loop();
      FastLED.delay(5000);
    }

body:
Assuming that the [link of chrisl][1] points to the relevant source...

Your source code:
```c++
    EVERY_N_SECONDS(2) {
        Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
    }
```

expands to (line split for readability):
```c++
    static CEveryNSeconds PER__COUNTER__(2);
    if( PER__COUNTER__ ) {
        Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
    }
```

So, yes, the instance controlling the conditional statement is `static`.

This is the [definition of `CEveryNSeconds`][2]:
```c++
template<typename timeType,timeType (*timeGetter)()>
class CEveryNTimePeriods {
public:
    timeType mPrevTrigger;
    timeType mPeriod;
    CEveryNTimePeriods() { reset(); mPeriod = 1; };
    CEveryNTimePeriods(timeType period) { reset(); setPeriod(period); };
    void setPeriod( timeType period) { mPeriod = period; };
    timeType getTime() { return (timeType)(timeGetter()); };
    timeType getPeriod() { return mPeriod; };
    timeType getElapsed() { return getTime() - mPrevTrigger; }
    timeType getRemaining() { return mPeriod - getElapsed(); }
    timeType getLastTriggerTime() { return mPrevTrigger; }
    bool ready() {
        bool isReady = (getElapsed() >= mPeriod);
        if( isReady ) { reset(); }
        return isReady;
    }
    void reset() { mPrevTrigger = getTime(); };
    void trigger() { mPrevTrigger = getTime() - mPeriod; };
    operator bool() { return ready(); }
};
typedef CEveryNTimePeriods<uint16_t,seconds16> CEveryNSeconds;
```

Its `operator bool()` returns only **once** the value `true`, if the period is elapsed. The first instance of your `A` receives this `true`, but never the second instance.

These are the relevant methods, sorted and formatted for better understanding:
```c++
    operator bool() {
        return ready();
    }

    bool ready() {
        bool isReady = (getElapsed() >= mPeriod);
        if ( isReady ) {
            reset();
        }
        return isReady;
    }

    timeType getElapsed() {
        return getTime() - mPrevTrigger;
    }

    void reset() {
        mPrevTrigger = getTime();
    }
```

  [1]: https://github.com/FastLED/FastLED/blob/5eaea812de970393bee4dcd17f9e4d17bf7a9f37/src/lib8tion.h#L1387
  [2]: https://github.com/FastLED/FastLED/blob/5eaea812de970393bee4dcd17f9e4d17bf7a9f37/src/lib8tion.h#L1323


message:
slower clock frequency than expected on attiny202

I am programming an attiny202 which as per [datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny202-402-AVR-MCU-with-Core-Independent-Peripherals_and-picoPower-40001969A.pdf) can run up to 20Mhz, but after compiling/uploading this simple code to the attiny202 and watch the PA2 pin on the oscilloscope, I see that the pin oscilates at ~2.5MHz which is around 10x slower than I would expect, this is even I disable prescaling, am I missing something? (I am new into programming microcontrollers)

> note:
> VCC is 5V (from lab bench PSU)

main.c
```c
#include <avr/io.h>

int main(void)
{
  // no prescaling (if lesss than 4.5V, this is overclocking)
  _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0);

  PORTA_DIR = _BV(2);

  while(1)
  {
    PORTA_OUTTGL = _BV(2);
  }
}
```

Makefile
```
PRG = main

CC = avr-gcc
MCU_TARGET = attiny202
OPTIMIZE = -Os

OBJCOPY = avr-objcopy
UART = /dev/ttyUSB0

all: $(PRG).elf $(PRG).hex

$(PRG).elf: $(PRG).c                                                                                »       $(CC) -g -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) $(PRG).c -o $(PRG).elf

%.hex: %.elf
»       $(OBJCOPY) -j .text -j .data -O ihex $< $@

clean:
»       rm *.elf *.hex

burn: $(PRG).hex
»       pymcuprog -t uart -d $(MCU_TARGET) -u $(UART) write -f $(PRG).hex --erase --verify
```

bitmaps from oscilloscope:

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

same picture with more measurement information:

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

  [1]: https://i.stack.imgur.com/oS5vf.png
  [2]: https://i.stack.imgur.com/LOf6q.png

body:
You are constantly toggling a pin in software. This involves copying the register data to the working register, toggling the bit and writing the result back.

This takes way more than only 1 clock cycle. So the resulting frequency is way lower. With only software you just cannot get near the clock frequency of the microcontroller.


body:
Just as a complement to chrisl's answer, if you disassemble the compiled
program, you should see that your infinite loop looks like this:

```lisp
1:  sts  0x0407, r24  ; write to PORTA_OUTTGL
    rjmp 1b           ; jump back to previous instruction
```

These instructions take two cycles each, for a total of four cycles per
loop iteration. The loop is thus expected to run at F\_CPU÷4 = 5 MHz.
Since a cycle of the output waveform takes two toggles, you expect to see
2.5 MHz on the oscilloscope.

You should be able to speed this up by writing to the virtual port
register `VPORTA_IN` instead of `PORTA_OUTTGL`. Virtual port registers
are equivalent to regular port registers, but they are mapped into the
I/O space of the microcontroller. This allows the compiler to replace
the `sts` instruction by the shorter and faster `out` instruction. The
loop should then complete in only 3 CPU cycles and output a waveform at
3.33 MHz.


message:
If Arduino digital pins can be used as power supply pins then why do we need VCC pins?

VCC pins work the same as digital outputs , don't they? So why do we still need VCC pins to
power components

body:
Digital IO pins and Vcc are very different.

When using the digital IO functionality of a pin, the pin is connected to the  digital IO hardware inside the microcontroller. This hardware is a driver, that can drive the pin to either LOW or HIGH (0V or Vcc) depending on a bit in a register. Though this driver can only provide a very limited amount of current. The absolute maximum is specified as 40mA peak, but you should not exceed 20mA continuously. So technically you can power a component from a digital pin (just like you can drive an LED through a digital pin), but only if it does NOT draw over 20mA. That is a rather small current. So in general nobody would recommend doing that. If you draw too much current from a digital pin, you can destroy its IO hardware.

The Vcc pin is the power **input** for the microcontroller on the board. The microcontroller needs this to be at the right voltage (5V for the Arduino Uno), to work properly. This power can come from different sources: The voltage regulator (via barrel jack or Vin), USB or directly provided through the Vcc pin. As long as the voltage stays in the correct range, it will work.

You can utilize the Vcc pin to power external components. Though this is just connecting these components to the power supply in parallel with your microcontroller. The current for the components will not be drawn through the microcontroller, but only through the copper traces on the board from your power source. That is also the reason why the power output of the Vcc pin cannot be controlled via software: It is just directly electrically connected to the power source of the microcontroller. Nothing in between.

---

So: Don't power anything other than components with really small current draw from IO pins. If you do it, always make sure beforehand that the current will be small enough (below 20mA).

If the components need more current, you can power them through the Vcc pin. Only use the IO pins for control in that case. For some components (like motors, bright LED lights, etc) you might need additional hardware for controlling them (like a transistor/MOSFET/driver chip).

And keep in mind, that the current through the Vcc pin is also limited. Depending on your power source you can draw up to 1A (including the Arduino itself) from the voltage regulator on a genuine Arduino. If you need to draw more current than that, you need to connect the components to a power source outside of the Arduino. For example you can connect them to the power source, that you connected to the Arduino directly, so that the high current doesn't need to flow through the Arduino, but can directly go to the high power components.


message:
float miscalculation when int32_t variable is divided by 10

i want to ask, how to get correct float value from uint32_t or long variable is devided by 10??

    long var3 = 1139399025;
    int a = 3;
    int b = 10;
    void setup() {
      Serial.begin(9600);
      Serial.println((float)a/b,2);
      Serial.println((float)var3/b,2);
    }
    void loop() {
    }
result

    0.3
    113939904.00

it give 113939904.00 instead of 113939902.50, plase how to fix that?

body:
1139399025 is not a floating point number: the largest odd integer that
can be exactly represented as a `float` is
224 − 1 = 16777215. Then, when `var3` is
cast to `float`, it gets rounded to the closest float, which
is 1139399040. This is quite a small error, especially considering
that, in this range, only multiples of 128 can be exactly
represented as floats.

Dividing 1139399040 by 10 gives 113939904, which happens to be a float.
The floating point division gives then the _exact_ result, which is what
gets printed. Indeed, floating point operations do not always give
inexact results: sometimes they are exact. However, unless you know what
you are doing, exact results only happen by luck. In general, expect
each floating point operation to make a _relative_ rounding error in the
range of 10−7.

A highly recommended read: [What Every Programmer Should Know About
Floating-Point Arithmetic][1].

**Edit**: If you want to print the value of an integer divided by 10,
you can divide the number using [Euclidean division][]. Print the
quotient, then the decimal point, then the remainder:

```c++
Serial.print(var3 / 10);  // quotient
Serial.print('.');
Serial.println(var3 % 10);  // remainder
```

As these are all integer operations, there is no rounding error
involved. Obviously this trick doesn't work for arbitrary divisors.

[1]: https://floating-point-gui.de/
[Euclidean division]: https://en.wikipedia.org/wiki/Euclidean_division


message:
Use Arduino MEGA generate 40kHz multiple square wave signal with 10 phase

I want to use Arduino-mega generate multiple square wave signal,the siganl is 40kHz and it can be used to drive ultrasonic transducer.

So,I use the trategy in article "[Ultraino: An Open Phased-Array System for
Narrowband Airborne Ultrasound Transmission][1]",which apply 10 bit signal with sequence of '0' or '1' in PORTA,PORTC...etc to get a square wave signal like Fig 1.

[![Fig.1 square wave signal][2]][2]

Fig.1 square wave signal

----------

Then I change the sequence pattern to shift phase,and just only 10 phases,some problem happen.

I am curious about the principle of this method:

 1. Why the sequence can generate signal with 40kHz?Does it mean Arduino will cost serval microseconds executing command like `POTRA=0x1`. I try to change the length of the array,it will no longer generate the square wave well.

 2. When I execute the shift function `shiftPhase`,it have 10 phase.In 5 phase it will move the square wave like Fig.2,the other 5 phase will be like Fig3,the duty of square wave is changed,just like inverted.So,how does it happen,just with change the sequence of 0,1?

[![Fig.2 shift wave success][3]][3]
Fig.2 shift wave success

----------

[![Fig.3 shift wave failed][4]][4]
Fig.3 shift wave failed

----------

the code I use is:
```
#include <avr/sleep.h>
#include <avr/power.h>
#define N_PATTERNS 1
#define N_PORTS 10
#define N_DIVS 10
#define COMMAND_SWITCH 0b00000000
#define COMMAND_DURATION 0b00110000
#define MASK_DURATION 0b00111111
#define COMMAND_COMMITDURATIONS 0b00010000

#define WAIT(a) __asm__ __volatile__ ("nop")
#define OUTPUT_WAVE(pointer, d)  PORTA = pointer[d*N_PORTS + 0]; PORTC = pointer[d*N_PORTS + 1]; PORTL = pointer[d*N_PORTS + 2]; PORTB = pointer[d*N_PORTS + 3]; PORTK = pointer[d*N_PORTS + 4]; PORTF = pointer[d*N_PORTS + 5]; PORTH = pointer[d*N_PORTS + 6];  PORTD = pointer[d*N_PORTS + 7]; PORTG = pointer[d*N_PORTS + 8]; PORTJ = pointer[d*N_PORTS + 9]
static byte bufferA[N_PATTERNS * N_DIVS * N_PORTS];
static byte bufferB[N_PATTERNS * N_DIVS * N_PORTS];
static byte animation[100] = {
                            0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
                            };

String str="";
void shiftPhase(byte* p,int len,int inter,int stepsize,byte id)
{
  byte mask=0xff-id;
  byte q[10]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};
  for(int i=0;i<10;i++)
  {
    q[i]=p[i*inter];
  }
  for(int i=0;i<10;i++)
  {
    p[i*inter]=(q[(i+stepsize+10)]&id)|(mask&q[i]);
  }
}

void setup()
{
  //set as output ports A C L B K F H D G J
  DDRA = DDRC = DDRL = DDRB = DDRK = DDRF = DDRH = DDRD = DDRG = DDRJ = 0xFF;
  //low signal on all of them
  PORTA = PORTC = PORTL = PORTB = PORTK = PORTF = PORTH = PORTD = PORTG = PORTJ = 0x00;
  //clear the buffers
  for (int i = 0; i < (N_PATTERNS * N_DIVS * N_PORTS); ++i) {
    bufferA[i] = bufferB[i] = 0;
  }
   for (int i = 0; i < 100; ++i)
   {
      bufferA[i] =  animation[i];
   }

  // disable everything that we do not need
  ADCSRA = 0;  // ADC
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_usart1_disable();
  power_usart2_disable();

  Serial.begin(9600);

  byte bReceived = 0;
  bool byteReady = false;
  bool emittingA = true;
  byte* emittingPointerH = & bufferA[0];
  byte* emittingPointerL = & bufferA[N_PORTS * N_DIVS / 2];

LOOP:
  OUTPUT_WAVE(emittingPointerH, 0);
  OUTPUT_WAVE(emittingPointerH, 1);
  OUTPUT_WAVE(emittingPointerH, 2);
  OUTPUT_WAVE(emittingPointerH, 3);
  OUTPUT_WAVE(emittingPointerH, 4);
  OUTPUT_WAVE(emittingPointerL, 0);
  OUTPUT_WAVE(emittingPointerL, 1);
  OUTPUT_WAVE(emittingPointerL, 2);
  OUTPUT_WAVE(emittingPointerL, 3);
  OUTPUT_WAVE(emittingPointerL, 4);

  byteReady = Serial.available();
  if(byteReady!=0)
  {
      str="";
      str=char(Serial.read());
      Serial.println(str);
      if(str=="1")
      {
        shiftPhase(bufferA,10,10,1,0x1);
      }
      if(str=="2")
      {
        shiftPhase(bufferA,10,10,-1,0x1);
      }
    }
 while(Serial.read()>=0){}
  goto LOOP;

}

void loop() {}
```
Thanks a lot!

The code of the article can be see in [link][5].

  [1]: https://ieeexplore.ieee.org/document/8094247
  [2]: https://i.stack.imgur.com/xAe7X.jpg
  [3]: https://i.stack.imgur.com/8xGIO.jpg
  [4]: https://i.stack.imgur.com/8F3p9.jpg
  [5]: https://github.com/asiermarzo/Ultraino/blob/master/DriverBoards/ArduinoMega64/firmware/DriverMEGAStatic/DriverMEGAStatic.ino

body:
Shiny100 asked:
> Does it mean Arduino will cost several microseconds executing command
> like `POTRA=0x1`.

I tried compiling `POTRA=0x1` and I got this:

```lisp
ldi r24, 0x01  ; load 0x1 into register r24
out 0x02, r24  ; output register r24 to PORTA (I/O address 0x02)
```

These are both single cycle instructions, so the sequence takes
2 cycles, i.e. 0.125 µs at 16 MHz. Your code, however,
does a lot more that that. The macro `OUTPUT_WAVE()` involves reading
ten values from RAM and writing them to ten different ports. The first
call to this macro gets compiled into this:

```lisp
lds r24, 0x028D ; r24 = bufferA[0]
out 0x02, r24   ; PORTA = r24
lds r24, 0x028E ; r24 = bufferA[1]
out 0x08, r24   ; PORTC = r24
lds r24, 0x028F ; r24 = bufferA[2]
sts 0x010B, r24 ; PORTL = r24
lds r24, 0x0290 ; r24 = bufferA[3]
out 0x05, r24   ; PORTB = r24
lds r24, 0x0291 ; r24 = bufferA[4]
sts 0x0108, r24 ; PORTK = r24
lds r24, 0x0292 ; r24 = bufferA[5]
out 0x11, r24   ; PORTF = r24
lds r24, 0x0293 ; r24 = bufferA[6]
sts 0x0102, r24 ; PORTH = r24
lds r24, 0x0294 ; r24 = bufferA[7]
out 0x0b, r24   ; PORTD = r24
lds r24, 0x0295 ; r24 = bufferA[8]
out 0x14, r24   ; PORTG = r24
lds r24, 0x0296 ; r24 = bufferA[9]
sts 0x0105, r24 ; PORTJ = r24
```

The `out` instruction is still single cycle, but `lds` (load from
memory) and `sts` (store to memory) take two cycles each. You may notice
that only ports A through F are accessed with the `out` instruction.
This is because they are mapped in the I/O address space of the
microcontroller. The other four ports are accessed using the slower
`sts` instruction on memory-mapped addresses.

If you count your cycles, you should get 34 cycles for the whole
sequence, which is 2.125 µs at 16 MHz. Ideally, you would like
this to take 2.5 µs (1/10 of a cycle of a 40 kHz signal). You
may notice that the code you took inspiration from has a few
instructions between successive calls to `OUTPUT_WAVE()`. It looks to me
like those were carefully timed to get as close as possible to
2.5 µs per phase. This approach is obviously fragile: any tiny
change in the code, or even a compiler upgrade, can throw off your
carefully timed code.

**Edit**: The second question, if I understand it correctly, is about
the change in duty cycle. The waveforms have a _nominal_ duty cycle of
50%: the signal is LOW over 5 time slots (5/10 of the cycle), then
HIGH for the next 5 time slots. The time slots, however, do not
have all the same length. The first nine last 2.125 µs each. The
last one, however, is somewhat longer, because it takes the duration of
the code handling the serial port, and the two cycles of `goto LOOP;`.
If the longer time slot happens when the output is HIGH, you get an
actual duty cycle higher than 50%. If it happens when it is HIGH, you
get a shorter duty cycle, like in your “shift wave failed” example.