body:
I am setting up 3 servos (**2 position servos and 1 '360' continuous rotational servo**) with Arduino. but I failed to run these independently. It runs one after another. I wish to run it in loop independent to each other. Here is the code which I use to run positional servo and CR (360) servo. default servo positions are 90.
*CR 360 servo should be running independently 90-60-120-90 (in loop)
*Pos servo should be running one after another (in loop)

**To run positional servos (tilt/pan):**

    //tilt servo
        for (pos = 90; pos >= 60; pos -= 1)     //90 ~ 60
      {
        tiltservo.write(pos);
        delay(30);
      }

      for (pos = 60; pos <= 120; pos += 1)      //60 ~ 120
      {
        tiltservo.write(pos);
        delay(30);
      }

      for (pos = 120; pos >= 90; pos -= 1)       //120 ~ 90
      {
        tiltservo.write(pos);
        delay(30);
      }

    //pan servo
    for (pos = 90; pos >= 60; pos -= 1)          //90 ~ 60
      {
        panservo.write(pos);
        delay(30);
      }

      for (pos = 60; pos <= 120; pos += 1)       //60 ~ 120
      {
        panservo.write(pos);
        delay(30);
      }

      for (pos = 120; pos >= 90; pos -= 1)       //120 ~ 90
      {
        panservo.write(pos);
        delay(30);
      }

**To run CR 360 servo:**

     legservo.writeMicroseconds(1600);      //CW
     delay(5000);                           //run for 5s
     legservo.writeMicroseconds(1300);      //CCW
     delay(5000);                           //run for 5s

Tried this to independently run CR servos, but how to put some wait (3s-4s) in between FW and RW.

    if (millisNow - lastMillis >= 10000)
    {
    lastMillis = millisNow;
    if (crservoState == 0)
     {
       legservo1.writeMicroseconds(2150); //FW
       crservoState = 1;
     }
      else
     {
       legservo1.writeMicroseconds(850);  //RW
       crservoState = 0;
     }
    }

**Trial code after suggestions:**

    uint32_t milliSNow = millis();

      if (milliSNow - lastTimeServoRotate >= 1000)
      {
        if (crservoState == 0)
        {
          if (milliSNow - lastTimeServoRotate >= 10000)
          {
            legservo1.writeMicroseconds(2150);    //FW run
            crservoState = 2;
            lastTimeServoRotate = milliSNow;
          }
        }

        if (crservoState == 1)
        {
          if (milliSNow - lastTimeServoRotate >= 10000)
          {
            legservo1.writeMicroseconds(850);     //RW run
            crservoState = 3;
            lastTimeServoRotate = milliSNow;
          }
        }

        if (crservoState == 2)
        {
          if (milliSNow - lastTimeServoRotate >= 3000)
          {
            legservo1.writeMicroseconds(1500);    //FW STOP
            crservoState = 1;
            lastTimeServoRotate = milliSNow;
          }
        }

        if (crservoState == 3)
        {
          if (milliSNow - lastTimeServoRotate >= 3000)
          {
            legservo1.writeMicroseconds(1500);     //RW STOP
            crservoState = 0;
            lastTimeServoRotate = milliSNow;
          }
        }
      }

title: How to Independently run positional and continuous servos using millis()?

Answers: 1

body:
This is covered in the [Blink Without Delay][blink] Arduino tutorial.
Let me paraphrase the main part of the example code here:

```c++
uint8_t ledState = LOW;
uint32_t lastTimeLedChanged = 0;

void loop() {
    uint32_t now = millis();
    if (now - lastTimeLedChanged >= 1000) {

        // Save the last time we updated the LED.
        lastTimeLedChanged = now;

        // Compute the new state of the LED.
        if (ledState == LOW) {
            ledState = HIGH;
        } else {  // ledState is HIGH
            ledState = LOW;
        }

        // Set the LED to the computed state.
        digitalWrite(LED_BUILTIN, ledState);
    }
}
```

This will make the LED cycle between its two possible states at the
desired rate. You can apply this principle as-is to your continuous
rotation servo.

For the positional servos, the same principle can still be applied, but
there is a catch. Whereas both the LED and the CR servo cycle between
two states, the pair of positional servos goes through many states
(<s>92</s> 240 if I counted correctly). You will thus need:

- more variables to store the current state of the servo pair
- more code to compute the new desired state
- more code to update the state

In order to figure out how to represent the state, you have to look at
your current `delay()`-based code, see how many calls to `delay()` are
performed on each full cycle, and figure out how to identify each of
these calls. Each of these delays corresponds to one state of your
system. I would say that you need one variable to know in which of the
`for` loops you are, and another variable to know the last position you
wrote to the servo in that loop. I will call each of the original `for`
loops a “phase”. There are <s>two</s> six such phases:

* phase 0: tilt: 90° → 60°
* phase 1: tilt: 60° → 120°
* phase 2: tilt: 120° → 90°
* phase 3: pan: 90° → 60°
* phase 4: pan: 60° → 120°
* phase 5: pan: 120° → 90°

**Note** there were only two `for` loops in the original question, but
it was then edited to include six loops, thus I edited my answer.

An then you will need to store the time of the last update, thus:

```c++
int phase = 0;  // which of the six phases we are in
int pos = 90;   // last position written to a servo
uint32_t lastTimeServoMoved = 0;
```

Once you have the proper variables to describe the state, updating it is
not hard. If you have reached the end of a phase, move to the next one.
Then update the position by one step. Thus:

```c++
void loop() {
    uint32_t now = millis();
    if (now - lastTimeServoMoved >= 30) {

        // Save the last time we updated a positional servo.
        lastTimeServoMoved = now;

        // Compute the new state.
        if (phase == 0 && pos == 60)
            phase = 1;
        else if (phase == 1 && pos == 120)
            phase = 2;
        else if (phase == 2 && pos == 90)
            phase = 3;
        else if (phase == 3 && pos == 60)
            phase = 4;
        else if (phase == 4 && pos == 120)
            phase = 5;
        else if (phase == 5 && pos == 90)
            phase = 0;
        if (phase == 1 || phase == 4)
            pos += 1;
        else
            pos -= 1;

        // Set the servo to the computed state.
        if (phase < 3)
            tiltservo.write(pos);
        else
            panservo.write(pos);
    }
}
```

I personally do not like this kind of repetitive code. If you are
comfortable with data structures, I would recommend using an array of
structs to store all the information describing the moves that are done
in each phase:

```c++
struct {
    Servo *servo;   // which servo to move
    int step;       // steps by which it moves
    int final_pos;  // final angular position
} moves[] = {
    { &tiltservo, -1, 60 },   // tilt:  90 ->  60
    { &tiltservo, +1, 120 },  // tilt:  60 -> 120
    { &tiltservo, -1, 90 },   // tilt: 120 ->  90
    { &panservo,  -1, 60 },   // pan:   90 ->  60
    { &panservo,  +1, 120 },  // pan:   60 -> 120
    { &panservo,  -1, 90 }    // pan:  120 ->  90
};
```

Then the actual code becomes simpler:

```c++
void loop() {
    uint32_t now = millis();
    if (now - lastTimeServoMoved >= 30) {

        // Save the last time we updated a positional servo.
        lastTimeServoMoved = now;

        // Compute the new state.
        if (pos == moves[phase].final_pos) {
            phase +=1;
            if (phase == 6)
                phase = 0;
        }
        pos += moves[phase].step;

        // Set the servo to the computed state.
        moves[phase].servo->write(pos);
    }
}
```

[blink]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay


body:
I am currently trying to create a project to setup a HomeKit remote control to control my smart home devices with the [Arduino-HomeKit-ESP8266 library](https://github.com/Mixiaoxiao/Arduino-HomeKit-ESP8266).

I am currently using a Arduino-based TinyCircuit device with the Atmel ATWINC1500 WiFi module. Is there any solutions available or any way to **modify the code** to make it work with my current WiFi shield, as it uses the [WiFi101 library](https://www.arduino.cc/en/Reference/WiFi101) instead of the [WiFi library](https://www.arduino.cc/en/Reference/WiFi)?

I am trying to test the "ConnectWithWPA.ino" from the WiFi101 examples with the HomeKit library. The code requires a "pgmspace.h" which I am not too sure what is it for.

ConnectWithWPA.ino:
```
/*

 This example connects to an unencrypted WiFi network.
 Then it prints the  MAC address of the WiFi shield,
 the IP address obtained, and other network details.

 Circuit:
 * WiFi shield attached

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */
#include <SPI.h>
#include <WiFi101.h>
#include <arduino_homekit_server.h> // INSERTED CODE

//access the config defined in C code
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

extern "C" homekit_server_config_t config; // INSERTED CODE

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWiFiData();

  arduino_homekit_setup(&config); // INSERTED CODE
}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  printCurrentNet();

  arduino_homekit_loop(); // INSERTED CODE
}

void printWiFiData() {
  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP A'ddress: ");
  Serial.println(ip);
  Serial.println(ip);

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);

}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:
  byte bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}
```

It produced this error when verifying:
```
Alternatives for osapi.h: []
ResolveLibrary(osapi.h)
  -> candidates: []
In file included from libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/settings.h:171:0,
from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/types.h:27,
from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/ed25519.h:26,
from \libraries\HomeKit-ESP8266\src/crypto.h:12,
from \libraries\HomeKit-ESP8266\src/arduino_homekit_server.h:15,
from \ConnectWithWPA.ino:17:
\libraries\HomeKit-ESP8266\src/user_settings.h:15:10: fatal error: osapi.h: No such file or directory
 #include "osapi.h"
          ^~~~~~~~~
compilation terminated.
```

After adding [osapi.h](https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/osapi.h) into the HomeKit src folder.
```
Alternatives for user_config.h: []
ResolveLibrary(user_config.h)
  -> candidates: []
In file included from \libraries\HomeKit-ESP8266\src/user_settings.h:15:0,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/settings.h:171,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/types.h:27,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/ed25519.h:26,
                 from \libraries\HomeKit-ESP8266\src/crypto.h:12,
                 from \libraries\HomeKit-ESP8266\src/arduino_homekit_server.h:15,
                 from \ConnectWithWPA.ino:17:

\libraries\HomeKit-ESP8266\src/osapi.h:29:10: fatal error: user_config.h: No such file or directory
 #include "user_config.h"
          ^~~~~~~~~~~~~~~
compilation terminated.
```

After adding one example of [user_config.h](https://github.com/pubnub/ESP8266/blob/master/include/user_config.h) into the HomeKit src folder.
```
Alternatives for pgmspace.h: []
ResolveLibrary(pgmspace.h)
  -> candidates: []
In file included from \libraries\HomeKit-ESP8266\src/homekit_debug.h:12:0,
                 from \libraries\HomeKit-ESP8266\src/user_settings.h:16,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/settings.h:171,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/types.h:27,
                 from \libraries\HomeKit-ESP8266\src/wolfssl/wolfcrypt/ed25519.h:26,
                 from \libraries\HomeKit-ESP8266\src/crypto.h:12,
                 from \libraries\HomeKit-ESP8266\src/arduino_homekit_server.h:15,
                 from \ConnectWithWPA.ino:17:
\libraries\HomeKit-ESP8266\src/esp_xpgm.h:15:10: fatal error: pgmspace.h: No such file or directory
 #include <pgmspace.h>
          ^~~~~~~~~~~~
compilation terminated.

```

My TinyCircuit uses these components:
 - TINYZERO PROCESSOR BOARD
 - TINYSCREEN OLED TINYSHIELD
 - [WIFI TINYSHIELD (ATWINC1500)](https://tinycircuits.com/collections/communication/products/wifi-tinyshield-atwinc1500)
 - Lithium Ion Polymer battery - 3.7V 150MAH

title: Can the Arduino-HomeKit-ESP8266 library be used with the WiFi101 library?

Answers: 0


body:
I want to encrypt and decrypt like 200 char strings on arduino mega, but I failed to find any library/code that can do that. Do you have any experience with doing that? Thanks.

I'd like to use any asymmetric encryption
The key should be ideally at least 128bit long.

title: Encrypting and decryption RSA (Or other asymetric encryption) on Arduino Mega

Answers: 0


body:
I need to get interrupts at one of three specific rates: 1920, 2000, and 2400 per sec, at a fairly high precision (~10 ppm). I've asked about this on Electronics but I think here might be more appropriate.

I can't use the standard 16MHz with internal timers, since 16MHz / 2400 (for example) gives 66666.666... counts.

I would use an external standard, but I don't seem to be able to find one that fits the need. Something small and precise at 48KHz / 96KHz etc would be fine.

Alternatively, I could swap the crystal / resonator for one running at 18.432MHz, which divides evenly by those freqs and shouldn't tax a 328p. Can I even do that on a Nano, or some clone / comparable, with the required 10ppm?

-- extra removed --

title: Procedure for changing frequency of Nano or similar

Answers: 1

body:
You could use an internal timer.

You are using interrupts, and you are probably aware that interrupt
handling inevitably incurs some jitter. Thus, if you do not mind an
extra single CPU cycle of jitter, you could reconfigure the timer on
each interrupt in order to control the _average_ interrupt period.

Here is how I would do it, with Timer 1 running in normal mode (CTC mode
would require an extra operation):

```c++
// Interrupt period in units of 1/2^16 CPU cycles.
// For 2.4 kHz, that is 16000/2.4*65536 = 436906666.666...
uint32_t interrupt_period = 436906667;

ISR(TIMER1_COMPA_vect) {
    // Update the timer for the next interrupt.
    static uint32_t accumulator;
    accumulator += interrupt_period;
    OCR1A = accumulator >> 16;

    // The periodic task goes here...
}

void setup() {
    // Configure Timer 1.
    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS10);    // clock @ F_CPU
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt
}

void loop(){}
```

Here, `accumulator` is a 32-bit extension of the timer's output compare
register. The upper 16 bits are copied into the actual timer
register, whereas the lower 16 bits ensure that the accumulated
error never exceeds one cycle.

This way of updating the timer should only take about 2 µs per
interrupt. It is a constant time operation, so it doesn't add extra
jitter to your task, other than the single cycle of jitter induced by
rounding to the next edge of the CPU clock.

There are a couple of caveats though:

1. This can only work on an Arduino clocked off a crystal (e.g., a
   Micro). Those clocked off a ceramic resonator (Uno...) would be too
   unstable in frequency to meet your 10 ppm requirement.
2. Even though a crystal is more than stable enough to meet your
   requirement, it is unlikely to be accurate enough. You will then need
   to calibrate it, e.g. by outputting a PWM signal (`analogWrite()`)
   into a frequency meter. Then adjust the variable `interrupt_period`
   according to the measured clock frequency.

------------------------------------------------------------------------

**Edit**: I added the timer configuration to the code, and here comes an
explanation of how this code works.

Think of the timer as a digital alarm clock. It measures time in units
of CPU cycles instead of hours and minutes. It rolls over every
216 cycles instead of every 1440 minutes. But it is
otherwise a regular alarm clock. It has two alarms called “COMPA” and
“COMPB”, but you only need one. In order to perform a periodic task, you
turn the alarm on and, every time it rings, you advance the alarm time
by the required period. That is, you set:

new alarm time = previous alarm time + task period

Note that the addition has to be computed modulo the roll-over period of
your clock : 1440 minutes for a regular alarm clock,
216 cycles for the timer. Thankfully, the arithmetics on
unsigned numbers do this automatically.

Now, lets say the task period is 43 minutes and 35 seconds,
but the alarm can only be set with a resolution of one minute. What you
can do is compute the “ideal” alarm time on paper (this is the
`accumulator` variable), and truncate it to the resolution of the clock
when setting the alarm. If you start at 00:00:00, you will compute the
next ideal time to be 00:43:35 and set the alarm to 00:43. When it
rings, you add the period to the previously computed time, you get
01:27:10, and you set the alarm to 01:27. Etc. Here is the list of the
alarm times as computed and as actually set on the clock:

    computed  set
    ───────────────
    00:00:00  00:00
    00:43:35  00:43
    01:27:10  01:27
    02:10:45  02:10
    ...

Note that, even though the limited resolution of the alarm setting
creates some jitter, the _average_ task period is still exactly
43 minutes and 35 seconds.

The code I wrote above does exactly the same. The “ideal” alarm time is
computed as a fractional number of CPU cycles, written down in binary
fixed point, with 16-bits on each side of the radix point. In hex, it is
1A0A.AAAB CPU cycles. The computed alarm times are multiples of this
period, whereas the times actually written to OCR1A are the same
truncated to an integer:

    computed   set
    ───────────────
    1A0A.AAAB  1A0A
    3415.5556  3415
    4E20.0001  4E20
    682A.AAAC  682A
    ...


body:
Over the past few months, I've been working on a wearable computer mouse using an Arduino and a 9-dof sensor. Most of the sketch is complete, and works as expected.

Recently, I started investigating how to enable a non-technical user to adjust the sensitivity of the device. Currently, I do this by changing a couple of variables in the sketch. My goal is to be able to create a basic GUI, with some buttons (perhaps unsurprisingly), to accomplish the same.

Requirements:
- ability to adjust sensitivity (couple of variables inside sketch) of arduino device through a GUI
- does not slow down sketch (I read that you can use serial, but wouldn't constantly checking for serial slow down the operation of the microcontroller?)
- can be saved as an executable (easy to set up for a nonprogrammer)

It's fine for the solution to upload a new sketch to the microcontroller, or change variables in the EEPROM. Whatever you suggest is best. I came across [this][1], and a few other similar topics, but due to my inexperience was unable to judge whether that's the best way forward.

I'm not looking for a complete solution, of course. Rather, I would really appreciate any guidance on what the basic "structure" of the solution should be. Then I can determine which parts I can do myself, and which I'll need to seek help on.

Thank you very much for looking at this.

  [1]: https://arduino.stackexchange.com/questions/13335/how-do-i-upload-sketch-and-parameters-through-a-user-interface

title: How to change variable/sketch through a GUI

Answers: 1

body:
Reflashing (and with that recompiling) the sketch for every variable change is very over-the-top.

As you already want to write your own program for the PC I would suggest using `Serial`. That will be the easiest to implement. This would work like the following:

- On the Arduino: You regularly check if there is data in the `Serial` buffer, read if in that case. You read until a newline character `\n`, which acts as message delimiter (to distinguish one message from the other). If a full message was received (meaning: you read the newline character) you process the message and write the new values to EEPROM (for saving them permanently).

- On the PC application: Let the user determine each value. You open the Arduinos COM port (the user will have to select the correct one) to communicate via Serial. Then you send each value, that you want to write to the Arduino, in a specific format. For example `<value_name>:<value>`. And don't forget the newline character at the end. Then you can close the COM port and exit the application.

This requires the user to choose the corresponding COM port. With using a custom USB profile (I think a custom HID profile should also be able to receive data) you could eliminate that, but this is a big step in difficulty for you to program.

> I read that you can use serial, but wouldn't constantly checking for serial slow down the operation of the microcontroller?

No, not really. The actual receiving of data is done by the USB hardware. As processing load you only have the placing of data in the buffer (happens inside an ISR), which only is done when actual data is received, and the checking if there is data in the buffer. That also needs very short time. It should not interfere with your sampling rate. The 9-DoF sensor is most likely way slower. The actual processing of the data is also only done when you actually send data. Here the longest will be saving the data in EEPROM.

So all in all you have little to no impact on performance.


body:
I want to extract the file name `MyFile.txt` out of a path which is stored in a string `"C:\\MyDirectory\\MyFile.txt";`

I found a simple [c code](https://stackoverflow.com/questions/8520560/get-a-file-name-from-a-path?answertab=votes#tab-top?#answer-8520815) which does the job.

```
string filename = "C:\\MyDirectory\\MyFile.bat";

// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
    filename.erase(0, last_slash_idx + 1);
}

// Remove extension if present.
const size_t period_idx = filename.rfind('.');
if (std::string::npos != period_idx)
{
    filename.erase(period_idx);
}
```

I had to alter few things for arduino code
example replace `find_last_of` with `lastIndexOf`, `erase` with `remove` and `rfind` with `lastIndexOf`

Here the `ino` file

```
#include<string>
void setup() {
  Serial.begin(9600);

}

void loop() {
   String filename = "C:\MyDirectory\MyFile.bat";

// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.lastIndexOf("\\");
if (std::string::npos != last_slash_idx)
{
    filename.remove(0, last_slash_idx + 1);
}

// Remove extension if present.
const size_t period_idx = filename.lastIndexOf('.');
if (std::string::npos != period_idx)
{
    filename.remove(period_idx);
}
Serial.println(filename);
delay(1000);
}
```
Expected output `MyFile`

When I look into Serial Monitor I get
```
c$$⸮'<;⸮⸮/<⸮⸮$⸮''⸮;,#$$⸮'<;⸮⸮'<⸮⸮$⸮''⸮:$#$$⸮'<;⸮⸮'<⸮⸮$⸮''⸮;$#$$⸮'
```

What am I doing wrong?

title: String operations printing random character on Serial Monitor

Answers: 1

body:
> ```c++
> #include<string>
> ```

Remove this. Arduino uses its own `String` class, different from the STL
`string`.

> ```c++
> String filename = "C:\MyDirectory\MyFile.bat";
> ```

There is no `'\M'` escape sequence in C++ strings. You probably mean
`"C:\\MyDirectory\\MyFile.bat"`.

> ```c++
> const size_t last_slash_idx = filename.lastIndexOf("\\");
> ```

`String::lastIndexOf()` returns an `int`, not `size_t`.

> ```c++
> if (std::string::npos != last_slash_idx)
> ```

No `std::string` here. `String::lastIndexOf()` returns `-1` to signify
that the character was not found.

With all these fixes, your sketch should work as intended.


body:
I am testing a project on Arduino Nano. I copy-paste the code on the Arduino IDE and click "Upload". I see:

```
No device found on cu.usbserial-<unique id>
An error occurred while uploading the sketch
```

The computer sees the board: when I disconnect the board from the USB socket, the list of ports in `Tools > Port` no longer shows this port.

The error thing happens:
- if I press the reset button first, then click "Upload"
- if I change the USB cable (I tried 5 different ones, one of which worked a few years ago, the last time I used this same board)
- if I use a [simple blink code](https://arduino-tutorials.net/tutorial/blinking-led-on-arduino)
- if I connect to a different USB port
- if I upgrade the Arduino IDE to the latest software from arduino.cc .

The `Get board info` command shows that the computer can read the VID and the PID, but not the serial number or the board type. If I connect an Arduino Uno to the same socket, I can see the serial number and the board type, but I get the same error message (just with a different port ID). Neither boards show signs of degradation.

The Boards Manager shows that the Arduino AVR Boards, which include Arduino Uno and Arduino Nano, are installed.

When I click "Upload", the IDE compiles the program, then the Nano's L LED blinks, then the TX blinks, then a pause, then the L, then the RX, then the L, then the RX, and then the IDE shows the error. So I suspect that the error is not what the IDE says.

Furthermore, the connection between the Arduino and the IDE is working because the Serial Monitor shows the output of the previous program (at 9600 baud).

Some Arduinos can reset by connecting RX to GROUND and uploading code, but this one does not have an RX pin.

How can I debug this error?

title: How to debug "No device found on cu.usbserial, An error occurred while uploading the sketch"

Answers: 1

body:
It seems that everything is working as it should and the computer and the board can see each other. The only thing left to do is to select the board type so the IDE knows how to send the code in a way that the board can interpret.

Select `Tools > Board > Arduino AVR Boards > Arduino Nano`.

If you have an old or non-Arduino board, try the old bootloader in the processor, as in  https://arduino.stackexchange.com/questions/51729/ch340-nano-avrdude-stk500-getsync-not-in-sync-resp-0xa4 .


body:
I'm messing about with an Arduino Mega2560r3 and failing to get timer 4 to trigger on the rising edge of an external clock. It only ever triggers on the falling edge.

I've tried

         TCCR4B = (1 << CS42) | (1 << CS41) | (1 << CS40);
and

         TCCR4B = (1 << CS42) | (1 << CS41);
... one of which should do the trick, but now I've pulled all my hair out and I'm turning to the wider community to see what I'm not seeing!

```
void setup() {
  DDRE = (1 << PE5);   //Dig pin 3 as output

  noInterrupts();
// Configure Timer 4 (only ICP4 (pin 49) and ICP5 (pin 48) are connected with Arduino MEGA2560 r3)
  TCCR4A = 0;
  TCCR4B = 0;
  TCCR4B = (1 << CS42) | (1 << CS41) | (1 << CS40);    // CTC mode does not reset when using force
  TIMSK4 = (1 << ICIE4);    // enable capture interrupt
  interrupts();
}

ISR(TIMER4_CAPT_vect)
{
  PORTE ^= (1 << PE5);  // Toggle PE5
}
```

Scope output below - blue is external clock (yes I know it's a sine wave!) and magenta is pin 3 output

[![falling edge trigger output][1]][1]

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

title: Unable to use rising edge interrupt for external clock Arduino 2650

Answers: 1

body:
You seem to be mixing up two very different things.

1. You can use an external signal to drive the timer. That is, the timer
   will “tick” on the edges of that signal. In this mode, the timer
   behavior could be more accurately described as being a “counter”,
   since it is counting the external signal's edges. The external signal
   has to be fed to pin Tn (for timer _n_). Only the pins T0 (38) and T5
   (47) are routed out on the Arduino Mega2560.

2. You can use a timer to timestamp the edges of an external signal.
   This is called “input capture”. When an edge is detected, the current
   value of the counter register is immediately copied to the input
   capture register ICRn, and an interrupt can be delivered. The
   external signal has to be fed to pin ICPn (ICP4 = 49, ICP5 = 48).

If you want to use input capture, you most likely want to clock the
timer from the system clock, maybe through a prescaler. And you want to
read the ICRn register within the ISR. The edge that triggers the
capture is selected via the bit ICESn (Input Capture Edge Select) of the
control register TCCRnB.


body:
Slober has a menu option: *Arduino -> Add a library to the selected project*

HOWEVER, the "Import Arduino libraries" dialog that comes up only shows 18 libraries, and has no obvious way to add more.

I selected *Arduino -> How To*, and selected "Add a library to a sketch", but it told me nothing new. It assumes the library I want to add is in the list, and says nothing about how that list itself is managed, where the libraries in it came from, how to add others, etc.

I theorized that Sloeber's list might be somehow generated from the one maintained by the Arduino IDE... but no, the list of libraries shown in Sketch -> Include library is ENORMOUSLY longer than Sloeber's list.

So... where, exactly, does Sloeber's library list come from, and how does one go about adding a library to it that's NOT in the list? Say...

* From whatever repository the Arduino IDE itself gets libraries from when you go to Library Manager (confession: I don't use Arduino often enough to *know* where those libraries are actually hosted, or who decides what qualifies to be listed. I assume it's something like MavenCentral and hosted by the Arduino organization... but I might be completely wrong)

* From a "zipfile" (containing whatever files, with whatever additional metadata, is required for Arduino's IDE to regard it as a valid library zipfile)

* From a random Github repo, like https://github.com/mrkaleArduinoLib/gbj_htu21 (with library.json, library.properties, and subdirectories for src/ and examples/)

title: How to add library to Sloeber

Answers: 1

body:
In `Arduino` or in `Window` menu in `Preferences`

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

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


body:
I want to merge two projects: a ["Don't touch your face" hat for Nano](https://www.hackster.io/elegoo-official/don-t-touch-your-face-hat-337f4e) and a [7-segment 4-digit display for Uno](
https://create.arduino.cc/projecthub/aboda243/how-to-use-4-digit-7-segment-without-library-b8e014). I tested both independently and they work. I added an RGB LED to the first, so I use 6 digital pins: 2 for the ultrasonic sensor, 1 for the buzzer, and 3 the RGB LED.

The Nano project takes 6 digital pins and no analog pins, leaving 4 digital pins and 8 analog pins. The Arduino Uno takes 12 digital pins. So I suppose that it's possible to replace the digital pins of the Uno with analog ones at the right voltage.

Even without the Nano project claiming 6 digital pins, the Nano only has 11 digital pins (D2-D12), not enough for a 7-segment 4-digit display. But I couldn't find a tutorial online on how to do so.

Is it possible to use a 7-segment 4-digit display on Arduino Nano?

title: Using 4-digit 7-segment display on Arduino Nano

Answers: 1

body:
There are chips such as the MAX7219 designed to control 7 segment displays from devices such as an Arduino, there are also some well-established libraries such as LEDCONTROL to drive them. In fact the MAX7219 doesn't have to drive 7 seg displays, you can use it to drive any collection of up to 64 LEDs, I use one for a simple illuminated Christmas tree. You'll need some basic soldering skills to connect the chip to an Arduino but it's very simple.

E.g. see: https://www.maximintegrated.com/en/products/power/display-power-control/MAX7219.html


body:
```
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1B =  0xFF00;
  TCCR1A = (1<<WGM10) ;
  TCCR1B = (1<<CS12) | (1<<CS10);; //set the pre-scalar as 1024
  TIMSK1 = (1 << OCIE1A);
```

This doesn't produce a 1 second timer, it seems to produce a 0.5 second timer? I've calculated it based on the fact that I'm using the internal 8MHz internal clock on the chip.

Where am I going wrong?

EDIT: OK, I truly don't understand anything about timers, this is the first time I've ever tried one. I tried to figure it out using this tutorial: <https://exploreembedded.com/wiki/AVR_Timer_programming>
All the examples are related to 16MHz, and the calculations are confusing to me because of the switch between formats which I don't know. After a lot of googling I figure out what I should be pushing into the calculator is ((8000000/1024)*1)-1) = 7811.5 (Although what I do with this number is a mystery) I think I'm supposed to subtract this from 65536 or perhaps some other randomly generated number. You then take the result of this and turn it into the hexadecimal equivalent of a boy band name, like E17 use lots of arrows to point away from things that look like the names of radio stations, WGM10 (bringing you all the hits of the 80's and 90's)

I apologize for the sarcasm, I couldn't help myself. What I really need to know is:
1. How do you actually calculate a 1-second delay one timer 1 when you are using the 8MHz internal clock of the ATMega168PA ? What are the numbers to type into a calculator?
2. Which switches should I be setting? I thought these were the correct ones.
3. What does OCIE1A stand for, can't find it in the documentation or the tutorial, only in the example code?

I should probably also add all I am doing is incrementing a count and displaying the count in my loop.

```
ISR (TIMER1_COMPA_vect)
{
  count++;
}
```

title: Can't get 1 second on a ATMega168 timer

Answers: 1

body:
In normal mode, the timer counts from 0 to 65535 (0xffff), and then
rolls over back to zero. With a prescaler set to 1024, the period is
then 1024 × 65536 = 67108864 CPU cycles.

If you want to control the timer's period, you should not use normal
mode, but rather CTC mode (for “clear timer on compare match”). In this
mode, it counts from 0 to the value stored in OCR1A, and then starts
back at zero. With the same prescaler, the period is then
1024 × (OCR1A + 1) CPU cycles.


body:
I have a datafile, datalog.txt I can open, read and write cool. What is the best way to delete all the file contents?
Should I try rewriting the SD card file with NULL data?
I have been reading the "SD.h" header file. I see a flush() and truncate() function should I use one of these?

or maybe I should just close  and reopen the file, and overwrite the data. But I'm concerned that this might lead to some miss representations if the old data is not completely removed.

I am using a teensy 4.1 with built_in SD card.

title: how can I delete contents of an SD card in arduino?

Answers: 1

body:
To remove a file use `SD.remove("datalog.txt");`

SD library's `FILE_WRITE` is `O_READ | O_WRITE | O_CREAT | O_APPEND` so it would append at the end of the existing file.

<del>to start with an empty file: File file = FS.open("datalog.txt", O_READ | O_WRITE | O_CREAT);</del>

EDIT: opening the file with O_READ | O_WRITE | O_CREAT doesn't clear the content of the file, only starts to overwrite it from the beginning.


body:
In this question:
 https://arduino.stackexchange.com/q/86601/4255, @EdgarBonet gave a very nice method of generating timings that don't divide the system clock evenly. He also said that it would require tuning of the exact value by measuring the resulting frequency. I'd like to see if that tuning could be made automatic.

Suppose I had a precise external reference that could interrupt at a a sub-multiple of my frequency, say 60Hz. Is there a way to use that precision to, over time, bring my generated frequency into rough agreement with it?

In other words, for a frequency of 2400 Hz, and a reference of 60 Hz, I would adjust the period of the generator so that there are exactly 80 cycles of the 2400 Hz signal in each 60Hz period, even though there might be variations within the periods of those 80 cycles.

In effect this is a crude phase-locked loop multiplier. I know it can't be highly precise, but even close would be very valuable.

title: Synchronizing an internal frequency to an external one

Answers: 1

body:
You could use the input capture feature of Timer 1 to timestamp the
edges of the reference input signal. This way you can compute the period
of the input relative to the CPU clock, compare to the expected nominal
period, and use this to adjust the interrupt period.

Combining this idea with the answer to the previous question gives:

```c++
const float input_frequency = 60;
const float interrupt_frequency = 2400;
const uint32_t nominal_input_period = round(F_CPU / input_frequency);
const uint32_t nominal_interrupt_period =
    round(F_CPU / interrupt_frequency) * 65536;

volatile uint32_t interrupt_period = nominal_interrupt_period;

uint16_t last_input_timestamp;

ISR(TIMER1_COMPA_vect) {
    // Update the timer for the next interrupt.
    static uint32_t accumulator;
    accumulator += interrupt_period;
    OCR1A = accumulator >> 16;

    // The periodic task goes here...
}

void setup() {
    // Configure Timer 1.
    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS10);    // clock @ F_CPU
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

    // Capture the first input edge.
    TIFR1 |= _BV(ICF1);  // clear interrupt flag
    loop_until_bit_is_set(TIFR1, ICF1);
    TIFR1 |= _BV(ICF1);  // clear interrupt flag again
    last_input_timestamp = ICR1;
}

void loop() {
    // Detect edges of the input signal.
    if (bit_is_set(TIFR1, ICF1)) {
        TIFR1 |= _BV(ICF1);  // clear interrupt flag

        // Update the interrupt period.
        uint16_t input_timestamp = ICR1;
        uint32_t input_period =
            (int16_t) (input_timestamp - last_input_timestamp
                - (uint16_t) nominal_input_period)
            + nominal_input_period;
        last_input_timestamp = input_timestamp;
        uint32_t new_interrupt_period = round(nominal_interrupt_period
                * ((float) input_period / nominal_input_period));
        noInterrupts();
        interrupt_period = new_interrupt_period;
        interrupts();
    }
}
```

Note that rounding the input period to an integer number of cycles comes
with a rounding error of 1.25 ppm, well within your 10 ppm
requirement. You can do better if needed, by using fixed point or
floating point computations. Note also that the Timer rolls over
multiple times per cycle of the input signal, which is dealt with by
some arithmetic tricks, hence the casts to `uint16_t` and `int16_t` in
the expression of `input_period`.

Strictly speaking, this is not a phase lock loop. It is more like a
frequency lock loop. A real PLL would probably be a bit more involved.
However, if you can tolerate your resulting frequency to be 10 ppm
off, this approach is likely to be good enough.


body:
I'm trying to build arduino nonce generator, but the only thing I found is [this question on arduino forum][1] but I can't find out how to make it work for me. I checked and Serial.available() is always 0 for me and if I delete the If I still get nothing

**My code:**
```
void setup() {
    Serial.begin(9600);
    randomSeed(analogRead(0));
}

void loop() {
    byte randomValue;
    char temp[5];
    char letter;
    char msg[50];     // Keep in mind SRAM limits
    int numBytes = 0;
    int i;
    int charsRead;

    if(Serial.available() == 0)
    {
        charsRead = Serial.readBytesUntil('\n', temp, sizeof(temp) - 1); // Look for newline or max of 4 chars
        temp[charsRead] = '\0';   // Now it's a string
        numBytes = atoi(temp);
        if(numBytes > 0)
        {
            memset(msg, 0, sizeof(msg));
            for(i = 0; i < numBytes; i++) {
            randomValue = random(0, 36);
            msg[i] = randomValue + 'a';
            if(randomValue > 26) {
                msg[i] = (randomValue - 26) + '0';
            }
            }
            Serial.println("Here is your random string: ");
            Serial.println(msg);
            Serial.print("I received: ");
            Serial.println(numBytes);
            delay(1000);
        }
    }
}
```

How do I make it work?

Do you have some working random alphanumeric string generator that you are using?

  [1]: https://forum.arduino.cc/t/random-alphanumeric-generator/330466

title: Optimised random alphanumeric string generator

Answers: 1

body:
Your problem seems to be related to how you get the actual length you want to generate. There are other ways you could do that. Since your max seems to be 4 characters, you could possibly enter "9999" which would overflow the 50 bytes `temp` variable.

You could simply read until `\n` and then `atoi`. Then cap at 50.

As a side note, here's a function I've used in the past to generate (pseudo)random strings for network requests (e.g. `state` or `nonce` parameters)

```c
#define MAX_UID 8 /* Change to whatever length you need */

const char * generateUID(){
  /* Change to allowable characters */
  const char possible[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  static char uid[MAX_UID + 1];
  for(int p = 0, i = 0; i < MAX_UID; i++){
    int r = random(0, strlen(possible));
    uid[p++] = possible[r];
  }
  uid[MAX_UID] = '\0';
  return uid;
}
```


body:
The Adafruit Feather SAMD21 takes about two seconds from power being supplied to when setup() starts running.  How can I shorten that time so that setup() will run sooner?  I measure this time using a power supply and others appear to measure similar times with their eyeballs.

I understand that 328 microcontrollers can be made to boot quicker (almost instantly from a human perspective) using different bootloaders for example, but I haven't found one for the M0 SAMD21 nor another method.

The code isn't relevant because the blink example shows the same timeframe, but here's another example:

    //no libraries, global variables, nothing.
    setup(){
    digitalWrite(LED_BUILTIN, HIGH);
    }

    loop(){
    }

title: How can I get a Faster boot with the Adafruit Feather SAMD21?

Answers: 1

body:
After consulting the datasheet for the SAMD21, I verified that the processor starts immediately once the internal clocks are stable. This happens quickly. The reset vector directs execution to the Arduino bootloader, which certainly spins while waiting for the Arduino programmer to connect. If that does not happen during that delay, the bootloader jumps to the resident application. The delay with no activity is how the bootloader determines that you want to start the application. You can eliminate that by programming the processor using a hardware programmer/debugger, and getting rid of the Arduino bootloader.<p>
The hardware programmers also allow source level breakpoint debugging. You just have to learn to use a decent IDE programming environment. A good prgrammer will cost you around $160.


body:
I'm running IDE version 1.8.16 under Windows 10.
Frequently I get the error message. The situation is solved only when exiting the IDE. Afterwards the compilation  may be finished with or without sketch errors.
Is there anything to do?

```
Exception in thread "AWT-EventQueue-0" Exception in thread
"Thread-18" java.lang.IndexOutOfBoundsException: len=-12
 at sun.font.FontDesignMetrics.charsWidth(FontDesignMetrics.java:501)
 at org.fife.ui.rsyntaxtextarea.TokenImpl.getWidthUpTo(TokenImpl.java:601)
 at org.fife.ui.rsyntaxtextarea.TokenImpl.getWidth(TokenImpl.java:570)
 at org.fife.ui.rsyntaxtextarea.RSyntaxUtilities.getTokenListWidth(RSyntaxUtilities.java:1180)
 at org.fife.ui.rsyntaxtextarea.RSyntaxUtilities.getTokenListWidth(RSyntaxUtilities.java:1159)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.getLineWidth(SyntaxView.java:307)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.calculateLongestLine(SyntaxView.java:110)
 at org.fife.ui.rsyntaxtextarea.RSyntaxTextArea.refreshFontMetrics(RSyntaxTextArea.java:2106)
 at org.fife.ui.rsyntaxtextarea.RSyntaxTextArea.setFont(RSyntaxTextArea.java:2545)
 at processing.app.EditorTab.applyPreferences(EditorTab.java:333)
 at processing.app.Editor.lambda$selectTab$52(Editor.java:1457)
 at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
 at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
 at java.awt.EventQueue.access$500(EventQueue.java:97)
 at java.awt.EventQueue$3.run(EventQueue.java:709)
 at java.awt.EventQueue$3.run(EventQueue.java:703)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
 at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
 at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
 at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
 at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
 at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
java.lang.IndexOutOfBoundsException: len=-12
 at sun.font.FontDesignMetrics.charsWidth(FontDesignMetrics.java:501)
 at org.fife.ui.rsyntaxtextarea.TokenImpl.getWidthUpTo(TokenImpl.java:601)
 at org.fife.ui.rsyntaxtextarea.TokenImpl.getWidth(TokenImpl.java:570)
 at org.fife.ui.rsyntaxtextarea.RSyntaxUtilities.getTokenListWidth(RSyntaxUtilities.java:1180)
 at org.fife.ui.rsyntaxtextarea.RSyntaxUtilities.getTokenListWidth(RSyntaxUtilities.java:1159)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.getLineWidth(SyntaxView.java:307)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.calculateLongestLine(SyntaxView.java:110)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.updateMetrics(SyntaxView.java:903)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.yForLine(SyntaxView.java:988)
 at org.fife.ui.rsyntaxtextarea.SyntaxView.yForLineContaining(SyntaxView.java:1013)
 at org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaUI.yForLineContaining(RSyntaxTextAreaUI.java:263)
 at org.fife.ui.rtextarea.RTextAreaBase.yForLineContaining(RTextAreaBase.java:1218)
 at org.fife.ui.rtextarea.LineHighlightManager.repaintLine(LineHighlightManager.java:174)
 at org.fife.ui.rtextarea.LineHighlightManager.addLineHighlight(LineHighlightManager.java:69)
 at org.fife.ui.rtextarea.RTextArea.addLineHighlight(RTextArea.java:296)
 at processing.app.Editor.addLineHighlight(Editor.java:1670)
 at processing.app.Editor.statusError(Editor.java:2552)
 at processing.app.Editor$BuildHandler.run(Editor.java:1646)
 at java.lang.Thread.run(Thread.java:748)
```

title: Arduino IDE Java error

Answers: 0


body:
The first time, pow() works.  But inside of a 'for loop', or again afterwards, it doesn't behave !?  (I'm using a Chinese Pro Mini with Arduino 1.8.16)

**EDIT**
To clarify what I am asking, my question is: "Why does pow() only give the correct answer the first time?"

    uint8_t places;
    uint8_t temp8;
    uint32_t n;

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

    void loop() {
      places  = 5U;

      n = pow( 10, places);
      Serial.println(n);

      Serial.println("\nHERE'S THE SAME CODE INSIDE OF A 'FOR LOOP'\n");

      for (temp8 = 0; temp8 < places; temp8++)  {
        n = pow( 10, places);
        Serial.println(n);
      }

      Serial.println("\nNOW THE EXACT SAME CODE AS BEFORE GIVES A DIFFERENT RESULT\n");

      n = pow( 10, places);
      Serial.println(n);

      while(1){}
    }

Here's what the serial monitor shows:

> 100000
>
> HERE'S THE SAME CODE INSIDE OF A 'FOR LOOP'
>
> 99999
>
> 99999
>
> 99999
>
> 99999
>
> 99999
>
> NOW THE EXACT SAME CODE AS BEFORE GIVES A DIFFERENT RESULT
>
> 99999

title: 'for loop' seems to change the execution of pow()

Answers: 1

body:
This seems like a case of a confused compiler. More specifically, a
confused optimizer.

On the first occurrence of `pow(10, places)`, the compiler noticed that
`places` must be equal to 5, and so replaced the expression with its
value. If you disassemble the compiled code, you will notice it calls

```c++
Serial.println(100000);
```

On the following occurrences, the compiler did not notice that `places`
can not be anything other than 5, so it did not optimize-out the call to
`pow()`, and got the result 99999.9765625. This is 3 ULPs less than
the exact result, and is consistent with the accuracy you can expect
from `pow()`. Converting to an integer implicitly rounds towards zero,
hence the printed result: 99999.


body:
I am a beginner with Arduino. I have a program that is intentionally simple.

The code refuses to compile, spitting out the error `Compilation error: Error: 13 INTERNAL: exit status 1`. I have gotten this type of error multiple times, and I have no idea what causes it, nor how to fix it.

My code is below, by the way.

```lang-c++
void setup() {
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);

  analogWrite(10, 10);
}

void loop() {
  digitalWrite(9, HIGH);
  digitalWrite(11, LOW);
  delay(250)
  digitalWrite(9, LOW);
  digitalWrite(11, HIGH);
}
```

title: Random "Compilation error: Error: 13 INTERNAL: exit status 1". No clue how to resolve or even what causes this error

Answers: 1

body:
The problem with that error message is that you are only reading the very last line. That line says "Oops, it didn't compile". The *actual* error message occurs *before* that. You need to read the entire message to know what is going on.

With your code, for example, you get the following output:

```
blah.ino: In function 'void loop()':
blah.ino:13:3: error: expected ';' before 'digitalWrite'
   digitalWrite(9, LOW);
```

That is your *actual* error. It's telling you that there's a semi-colon missing before the `digitalWrite` on line 13.  There's nothing before the `digitalWrite` on line 13, but, if you look closely, you can see that line 12 has the semi-colon missing from the *end* of it.:

```c++
  delay(250)    <---- missing ;
  digitalWrite(9, LOW);
```

Thus it proves that it is always important to both read and (if you don't understand it) post **the entire error message not just the last line.**


body:
As the title implies, I have two Arduino devices (Uno and Mega) connected to each other over UART (the Mega is hardware UART, the Uno is software UART); I need the Mega to send a command to the Uno, the Uno to perform the command, then the Uno to report back to the Mega when it has finished the task. In this way, I want to implement asynchronous programming to control various light patterns as well as several motors (code not shown, it is unnecessary as the light control is in an isolated segment) without needing any firmware hacking. Sending commands from the Mega to the Uno works, but the reverse is not true, and even polling waitloops do not work. Note that if I send the "affirm" command repeatedly for infinity, but then I hang the code in the Uno and the Mega has no way to stop the barrage; it starts receiving likely random bytes.
My code for the Mega is bulky and multi-file so I can't send the entire thing, but here is the control code:
```c++
lights::showRow(Serial1, 0, 0, 1, 1, 2, 2);
lights::waitUntilFinished(Serial1);
delay(500);
lights::clear(Serial1);
lights::waitUntilFinished(Serial1);
lights::chantO(Serial1);
lights::waitUntilFinished(Serial1);
lights::showRow(Serial1, 1, 0, 1, 1, 1, 2);
lights::waitUntilFinished(Serial1);
delay(500);
lights::clear(Serial1);
lights::waitUntilFinished(Serial1);
lights::chantX(Serial1);
lights::waitUntilFinished(Serial1);
```
These commands are implemented by:
```c++
namespace lights{
  boll ready = false;
  boll helloSent = false;
  void chantO(HardwareSerial coms){
    coms.write(1);
  }
  void chantX(HardwareSerial coms){
    coms.write(2);
  }
  void showRow(HardwareSerial coms, uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, uint8_t x3, uint8_t y3){
    coms.write(3);
    coms.write(x1);
    coms.write(y1);
    coms.write(x2);
    coms.write(y2);
    coms.write(x3);
    coms.write(y3);
  }
  void clear(HardwareSerial coms){
    coms.write(4);
  }
  void waitUntilFinished(HardwareSerial coms){
    while (coms.available() == 0){};
    Serial.println("Done.");
    // It can't say anything but "affirmed", so we can save some code by not checking.
  }
}
```
The light code:
```c++
/* To make life easy, I will include a wiring map. Change as needed.
 *  Note that each ring is 24 pixels, and is labeled with the first-position to access it. The next one is obviously going to be the final point.
 ____     ____     ____
/48  \___/72  \   /192 \
\____/   \____/   \____/
 |___     |___     |___
/24  \   /96  \   /168 \
\____/   \____/   \____/
 |___     |___     |___
/0   \   /120 \___/144 \_____[END]
\____/   \____/   \____/
 |
 |
[CONTROLLER]

*/

#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN       6
#define NUMPIXELS 216
#define DELAYVAL 500

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
SoftwareSerial coms(9, 8);
int white = pixels.Color(255, 255, 255);
int red = pixels.Color(255, 0, 0);

int getPixel(uint8_t x, uint8_t y, uint8_t num){
  if (x == 0){
    return 48 - (y * 24) + num;
  }
  else if (x == 1){
    return 72 + (y * 24) + num;
  }
  else if (x == 2){
    return 192 - (y * 24) + num;
  }
}

void setRing(uint8_t x, uint8_t y, int color){
  for (int i = 0; i < 24; i ++){
    pixels.setPixelColor(getPixel(x, y, i), color);
  }
}

void setup(){
  pinMode(9, INPUT);
  pinMode(8, OUTPUT);
  coms.begin(9600);
  Serial.begin(9600);
  pixels.begin();
  pixels.setBrightness(205); // 0.8 * 256 = 204.8; thus this is 80% power. Only 6 can be lit up before you have issues.
}

void loop(){
  if (coms.available() > 0){
    uint8_t d = coms.read();
    Serial.println("He talkin' me");
    Serial.print("He say ");
    Serial.println(d);
    switch (d){
      case 1:
        for (uint8_t x = 0; x < 2; x ++){
          setRing(0, 1, white);
          setRing(1, 0, white);
          setRing(2, 1, white);
          setRing(1, 2, white);
          pixels.show();
          delay(500);
          pixels.clear();
          pixels.show();
          delay(500);
        }
        break;
      case 2:
        for (uint8_t x = 0; x < 2; x ++){
          setRing(0, 0, white);
          setRing(2, 2, white);
          setRing(2, 0, white);
          setRing(0, 2, white);
          setRing(1, 1, white);
          pixels.show();
          delay(500);
          pixels.clear();
          delay(500);
        }
        break;
      case 3:
        Serial.println("Hello, World");
        setRing(coms.read(), coms.read(), red);
        setRing(coms.read(), coms.read(), red);
        setRing(coms.read(), coms.read(), red);
        pixels.show();
        break;
      case 4:
        pixels.clear();
        pixels.show();
        break;
    }
    coms.write(1);
  }
}
```

title: UART connected device communication only works one way

Answers: 1

body:
You are passing your `HardwareSerial` (`Serial1`) objects by value. That means that the object is copied, which is not good - it breaks the connection between the incoming data buffer and the interrupt that loads the RX ringbuffer.

Instead you must either pass *by reference* or *by pointer*.  Personally I prefer pointers because it's what I am used to using, but you can use either.

For example:

```c++
  void waitUntilFinished(HardwareSerial &coms){ // <--- note the &
    while (coms.available() == 0){};
    Serial.println("Done.");
    // It can't say anything but "affirmed", so we can save some code by not checking.
  }
```

I would also consider changing this from a namespace to a class and passing the serial object you wish to use as a parameter to the constructor and storing the pointer to it in the class - then you only need ever pass it once and then use that pointer from then on. It would just simplify your code and clean things up somewhat.


body:
I am using a fingerprint sensor and GSM module on Arduino MEGA 2560. I want a fingerprint to be scanned every minute, if a minute elapses with no finger scanned, then the next code for the GSM to send an SMS must be executed
[![enter image description here][1]][1]

```
const unsigned long timeLimit = 60000;
unsigned long prevTime;
unsigned long currTime;

void setup() {
  prevTime = millis();
}

void loop() {
  unsigned long currTime = millis();
  getFingerprintID(); //fingerprint func
  if (currTime - prevTime <= timeLimit) {
    if (finger.fingerSearch() == FINGERPRINT_OK) { //if the fingerprint matches
      prevTime = currTime;
    }
  } else {
    Serial.print("MAXIMUM TIME OF ");
    Serial.print(currTime / 1000);
    Serial.print(" SECONDS HAS LAPSED\n");
  }
}
```

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

title: fingerprint scanner and GSM module- how do i put a timer condition using if statements?

Answers: 1

body:
i cleaned up your version. make sure to update the `prevTime` variable.

```cpp
const unsigned long timeLimit = 60000;
unsigned long prevTime ;
unsigned long currTime;
unsigned long elapsedTime;
int id;
void setup() {
prevTime=millis();
}

void loop() {
  if (fingerprint()){
    currTime = millis();
    elapsedTime = currTime- prevTime;
    if (elapsedTime < 60*1000) {
      prevTime = currTime;
    } else {
       sendSms();
    }
  }
}

void sendSms() {
Serial.print("MAXIMUM TIME OF ");
Serial.print(currTime/1000);
Serial.print(" SECONDS HAS LAPSED\n");
}

bool fingerprint(){
  bool fingerPrintAccepted = false;
  if (finger.fingerSearch()==FINGERPRINT_OK){
    fingerPrintAccepted = true;
  }
  return fingerPrintAccepted;
}
 ```


body:
I think this is a broad question. I'm currently implementing visible light communication with Arduino. I'm using a laser as my transmitter and LDR as my receiver. I'm able to transmit a text from one side to another. But I would like to go further on this project. I want to modify the system to transfer an audio file and live stream(play) on the receiver's side.

In order to play the stream in real time, data communication must happen much faster than simple text transfer.

(Like audio with 8KHz sampling rate with 16 bit per sample).
Need transmission speed of 8*16/8= 16,000 Bytes/s

I have identified a few barriers to achieve such as

 1. Arduino has a 64-byte buffer.(can lead to buffer overflow)
 2. LDR response time(min delay for the pulse is 10ms for text transmission project)

I wonder If this is a possible project to do with Arduino. If it's possible, I would like to know about changes to reach that kind of transmission speed. I'm sorry for my poor writing skills.

Thank You!

title: Arduino Visible Light Communication(Audio transmission)

Answers: 0


body:
My issue arose when attempting to flash several of my ESP8266 ESP-01 module (https://www.aliexpress.com/item/33010444450.html?spm=a2g0s.9042311.0.0.27424c4dNkKYQZ). In the past and with the first chip I got it working just fine with the loader from the Espressif website, but the second and third proved to be stubborn.

**The problem:**

The issue I am struggling with is that during flashing the software does not recognize/synchronize with the chip. When attempting to do this, the indicator blue-led on the chip is constantly on. When checking the communication with the chip in normal mode (at Baud 15200) the chip responds normally to AT commands and presents version number etc. When in flash mode, however, the chip responds at Baud 74880 by flooding TX with

    Fatal exception (0):
    epc1=0x400fffa8, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

From research, I gathered that this could be a faulty flash in the past causing a wrong configuration in flash mode but I still haven't found a solution to this problem as the chip does not respond when attempting to re-flash.

**The setup**

As a setup, I have both an Arduino Uno with the chip removed(https://www.instructables.com/Flash-or-Upgrade-Firmware-on-ESP8266-ESP-01-Module/) as well as an ESP-dongle(https://www.aliexpress.com/item/32693314450.html?spm=a2g0s.9042311.0.0.506e4c4ddAqtwB) with a switch soldered on between GND and GPIO0. Furthermore:

 - Vin -> 3.3V
 - CH_EN -> 3.3V
 - Tx -> Tx
 - Rx -> Rx
 - GPIO_0 -> GND
 - GND -> GND

As software, I tried that from the Espressif website (latest version and that of Jan 2021) as well as NodeMCU Firmware Programmer. Again, the first chip responded after a while (also not ideal), but the second and others fail to do so.

**The question**

My question is thus what could be causing this problem, what I can do to rectify the issue, and finally what the most secure way to flash such chips is as my previous one clearly did not work.

Thanks for any tips in advance,

Cheers

title: Fatal exception preventing flashing ESP8266 ESP-01

Answers: 0


body:
I am working on a led strip project and was looking for ways to smooth transition from color to another. Problem is my current method is not so good.

    #include <Adafruit_NeoPixel.h>

    #define LED_PIN     25
    #define LED_COUNT  60
    #define BRIGHTNESS 50

    Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800);

    bool isFading = false;
    unsigned long startTime;
    uint32_t fadeDuration = 1000;          //fade for 3seconds
    uint32_t startingColor = 0x00ffff00;      // W = 0x00 R=0xFF G=0xFF B=0x00  yellow
    uint32_t targetColor = 0x008f00ff;        // W = 0x00 R=0x8F G=0x00 B=0xff  violet

    void setup() {

      pinMode(25, OUTPUT);
      digitalWrite(25, LOW);

        Serial.begin(9600);
      while (!Serial);
      Serial.println("Starting");

      strip.begin();
      strip.show();
      strip.setBrightness(BRIGHTNESS);

      for (int i = 0; i < strip.numPixels(); i++)
        strip.setPixelColor(i, startingColor);
      strip.show();

      delay(5000); // wait 5 seconds before fading

      isFading = true;
      startTime = millis();
    }

    void loop() {

      if (isFading) { //Fade from yellow to violet in 3 seconds
        for (int i = 0; i < strip.numPixels(); i++)
          strip.setPixelColor(i, getFadeColor(startingColor, targetColor, startTime, startTime + fadeDuration));
        strip.show();
      }

      if ( millis() >= startTime + fadeDuration){; // i intentionally did not include an overflow check to keep it simple
      Serial.println("Fade ended");
      isFading = false;
      }
    }

    uint32_t getFadeColor(uint32_t startColor, uint32_t endColor, unsigned long timeStart, unsigned long timeEnd) {

      uint8_t startWhite  = (startColor >> 24) & 0xff;
      uint8_t startRed    = (startColor >> 16) & 0xff;
      uint8_t startGreen  = (startColor >> 8 ) & 0xff;
      uint8_t startBlue    =  startColor & 0xff;

      uint8_t endWhite    = (endColor >> 24) & 0xff;
      uint8_t endRed      = (endColor >> 16) & 0xff;
      uint8_t endGreen    = (endColor >> 8) & 0xff;
      uint8_t endBlue      = endColor & 0xff;

      unsigned long timeNow = millis();

      uint8_t mapTime = map(timeNow, timeStart, timeEnd, 0, 255);
      uint8_t white   = map(mapTime, 0, 255, startWhite, endWhite);
      uint8_t red     = map(mapTime, 0, 255, startRed, endRed);
      uint8_t green   = map(mapTime, 0, 255, startGreen, endGreen);
      uint8_t blue    = map(mapTime, 0, 255, startBlue, endBlue);

      Serial.print("Time: \t");
      Serial.print(mapTime);
      Serial.print('\t');
      Serial.print("Color now: \t");
      Serial.println(strip.Color(  red,   green,   blue, white),HEX);

      return strip.Color(  red,   green,   blue, white);

    }

The problem im having with this code is visually it would seem that it goes from

Yellow -> White -> violet

and it does not look like a proper transition. I have tried with other colors, and it always seems to pass throught the white color

Are there color theories i can apply for the transition? if you can show me an example sketches on how to do the transition that would also be great.

title: How to smooth transition to another color NEOPIXELS

Answers: 1

body:
>  something that will go through the color wheel until the destination color

For that the `FastLED` library has the function `ColorHSV()`, which can be used to define colors using the HSV color space. It stands for **H**ue, **S**aturation and **V**alue (or brightness). Hue is the value representing the position in the color wheel, so that is what you want to change.

Instead of

    strip.Color(  red,   green,   blue, white);

use

    strip.ColorHSV( hue, saturation, brightness );

and change `hue` over time with the algorithm, that you already programmed. When `saturation` and `brightness` stay the same the LEDs will cycle through the color wheel.

Note: The library provides the way from HSV to RGB color (with the above function), but it does not provide a way back. For getting back HSV from an RGB color you would need to write your own conversion function and I don't know how to do that. Though at the current state you don't need it.


body:
Good day to ya all. I have a general question and a potential problem to solve.

My plan is to make a device which will work on 2 li-ion batteries. The purpose of this board is to take data from 3/4 sensors and send them via gprs to a server.( it would be ideal if it had gps on board also )

It must be small and it must at least hold half a year on those 2 ( at max 4 batteries ).

My question to you all is do you know a good low power microcontroller board with gsm/gprs chip on it (and maybe gps) ?

One solution would be to use a Arduino pro nano and a separate sim800 module and a separate gps module but this solution is just complicating. I need something with similar functionality of an Arduino and not so power hungry.

Hope to hear from you.

title: Low power microcontroller with gprs/gsm and maybe gps on board

Answers: 0


body:
sorry to ask this but I am very very new to Arduino.
My project aims to collect the skin temperature by 18B20 and the heart rate & SPO2 level by MAX30100.
I have tested the codes for the respective sensors and they work fine, but when i am trying to merge these two codes together, only 18B20 works and 30100 isn't delivering any information (Heart rate:0.00bpm / SpO2:0%). Is there a way to combine these two codes? Thank you very much!

Code of 18B20
````
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire device
OneWire oneWire(ONE_WIRE_BUS);

// Pass oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);

void setup(void)
{
  sensors.begin();  // Start up the library
  Serial.begin(9600);
}

void loop(void)
{
  // Send the command to get temperatures
  sensors.requestTemperatures();

  //print the temperature in Celsius
  Serial.print("Temperature: ");
  Serial.print(sensors.getTempCByIndex(0));
  Serial.print((char)176);//shows degrees character
  Serial.print("C  |  ");

  delay(500);
}
````
Code of 30100
````
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#define REPORTING_PERIOD_MS     1000

PulseOximeter pox;
uint32_t tsLastReport = 0;

void onBeatDetected()
{
    Serial.println("Beat!");
}

void setup()
{
    Serial.begin(115200);
    Serial.print("Initializing pulse oximeter..");

    // Initialize the PulseOximeter instance
    // Failures are generally due to an improper I2C wiring, missing power supply
    // or wrong target chip
    if (!pox.begin()) {
        Serial.println("FAILED");
        for(;;);
    } else {
        Serial.println("SUCCESS");
    }
     pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);

    // Register a callback for the beat detection
    pox.setOnBeatDetectedCallback(onBeatDetected);
}

void loop()
{
    // Make sure to call update as fast as possible
    pox.update();
    if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
        Serial.print("Heart rate:");
        Serial.print(pox.getHeartRate());
        Serial.print("bpm / SpO2:");
        Serial.print(pox.getSpO2());
        Serial.println("%");

        tsLastReport = millis();
    }
}
````

title: Combining the code of MAX30100 and DS-18B20

Answers: 0


body:
I have a rp2040 board using Earl E. Philhower core. I would like to use the rtc functions just like the one mentioned in the [sdk][1]. Especially the alarm function which is critical in my project.

Supposedly from what i know you have access to all the functions in the sdk on the arduino IDE but when i tried out the example in the sdk it would not compile saying that rtc functions are not declared

    char datetime_buf[256];
    char *datetime_str = &datetime_buf[0];

        datetime_t t = {
                .year  = 2020,
                .month = 06,
                .day   = 05,
                .dotw  = 5, // 0 is Sunday, so 5 is Friday
                .hour  = 15,
                .min   = 45,
                .sec   = 00
        };

    void setup() {
        Serial.begin(9600);
        Serial.println("Hello RTC!");

        rtc_init();
        rtc_set_datetime(&t);
    }

    // the loop function runs over and over again forever
    void loop() {
            rtc_get_datetime(&t);

            Serial.println(datetime_str);
            sleep_ms(100);             // wait for a second
    }

Earl E. Philhower comes with a Time sketch example but problem is i could not find a documentation if a alarm like function exist

    /* Simple demonstration of setting and printing the current time */
    /* The initial time will need to come from an RTC, NTP, or user */

    /* Released to the public domain by Earle F. Philhower, III <earlephilhower@yahoo.com> */

    #include <time.h>
    #include <sys/time.h>

    void setup() {
      Serial.begin(115200);
      delay(5000);
      struct timeval tv;

      tv.tv_sec = 1611198855; // Jan 21, 2021  3:14:15AM ...RPi Pico Release;
      tv.tv_usec = 0;
      settimeofday(&tv, nullptr);
    }

    void loop() {
      time_t now;
      char buff[80];

      time(&now);
      strftime(buff, sizeof(buff), "%c", localtime(&now));
      Serial.println(buff);
      delay(1000);
    }

  [1]: https://raspberrypi.github.io/pico-sdk-doxygen/group__hardware__rtc.html

title: RP2040 RTC alarm or similar function

Answers: 1

body:
You can try to use my [RP2040_RTC Library](https://github.com/khoih-prog/RP2040_RTC), especially this [RP2040_RTC_Alarm example](https://github.com/khoih-prog/RP2040_RTC/tree/main/examples/Alarm/RP2040_RTC_Alarm).

Both [**ArduinoCore-mbed**](https://github.com/arduino/ArduinoCore-mbed) and [Earle Philhower **arduino-pico**](https://github.com/earlephilhower/arduino-pico) cores are supported.


body:
I'm using an **Arduino Uno** and a **PCA9685** board to run 4 servos (of type MG996R).
For that, I set up the following connections:

- SCL -> SCL
- SDA -> SDA
- Ground -> GT
- VCC -> 3.3V

As the servos require high current under draw, I've used an external power supply that is also connected to the PCA9685 at the intended place. The power supply is at **6V** (DC) - and **max 3 ampere**.

Everything **just worked fine** for about 1 month. Then, suddenly the servos did not move anymore.
What I checked:
- the power supply **still gives** the desired 5-6V at the PCA9685 board
- I bought a **new** PCA9685 board
- I used **another** power supply at 5.2V and max 2 ampere (only 1 servo connected)

The strange thing is that even with the new PCA9685  board and power supply, the **servos don't move**. However, they **move** if a remove the external power supply and connect the **v+** pin of the PCA9685  to the arduino's 5V output pin.

You have any idea whats going on or what might be broken?

title: Arduino and PCA9685 - Suddenly stopped working

Answers: 0


body:
I'm working on a project with reed switches, which are connected between a GPIO pin (in pullup mode) and ground. With some of my NodeMCU ESP-12E boards (HiLetGo brand) that I ordered, whenever the reed switch on GPIO9/SD2 is closed, the board is rebooting. However, some of these same boards do not exhibit this same behavior - the reed switch on this pin works correctly.

The reset reason is `Fatal exception:4 flag:1 (WDT)`

Is there any reason that some boards would work while others don't? Is this pin generally safe to use as an IO pin? I need at least 8 GPIO pins to work per board, and I'm having a hard time finding enough of them.

Here's my code, for reference
```
int REED_PIN = 9;
void setup() {
  Serial.begin(9600);
  Serial.println("Setup");

  pinMode(REED_PIN, INPUT_PULLUP);
  Serial.println(ESP.getResetInfo());
}

// the loop function runs over and over again forever
void loop() {
  int proximity = digitalRead(REED_PIN);
  if (proximity == LOW) {
    Serial.println("Magnet detected");
  }
}
```

title: ESP8266 ESP-12E: SD2 (GPIO 9) causing reboot when pulled low

Answers: 0


body:
Im very new to Arduino. Using an ESP32, Im trying to login to a network device to read its log file. To login to the device I need to simulate a web browser with cookies.

The ESP32 is connecting to WiFI correctly, and Im including the HTTPClient.h file

Using http.begin I am able to browse to the device login page, but I dont know how to store the successful login in a cookie.
From doing some research I think that cookies are just HTTP headers, but I'm not really sure how to read/parse/resend the cookie header in another HTTP request.

I can successfully do it in PEARL using CURL (my code is below). Can someone help me port this to ESP32

    use strict qw/refs/;
    use HTTP::Cookies;
    use LWP::UserAgent;
    use HTTP::Request::Common qw/POST GET/;

    my $Browser = LWP::UserAgent->new(
    cookie_jar => HTTP::Cookies->new,
    requests_redirectable => ,
    timeout => 10,
    pragma => "no-cache",
    max-age => 0,
    agent => "Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0"
    );

    my $Page = $Browser->request(GET $Authenticate);

title: Need Help with HTTPClient.h and storing cookies

Answers: 0


body:
I would like to use queuing because i think its best for my application. I have very limited experience in dual core programming all i want is to hopefully pass 32 bit numbers to the second core properly. queuing seems to be good because it makes sure that the second core who is receiving the data wont miss anything in the sequence if data comes in very fast and core 2 is not ready to process it.

But Im having trouble finding examples. I did [find one][1] but its for a runner queue, which i think is a bit different to what i want

Can anyone show me an example sketch? what i would really like to see is core 1 adding to the queue and core 2 retrieving and removing data from the queue

  [1]: https://github.com/raspberrypi/pico-examples/blob/master/multicore/multicore_runner_queue/multicore_runner_queue.c

title: RP2040 example sketch for dual core queuing

Answers: 2

body:
This requires a thread-safe queue, where one thread writes to the queue, and another thread reads from the queue.

But I find that with a little care, you can just use a circular buffer where the consumer will increase the head, and the producer will increase the tail.

Something like this:

```
#define MAXSZ 80
static int buff[MAXSZ];
static int head=0;
static int tail=0;

bool full(void)  { return (tail+1)%MAXSZ == head; }
bool empty(void) { return head==tail; }
int  usage(void) { int num = tail-head; return num<0 ? num+MAXSZ : num; }

int produce(int val)
{
   if ( full() ) return -1;
   buff[tail] = val;
   tail = (tail+1)%MAXSZ;
   return 0; // signal success.
}

int consume(void)
{
   if ( empty() ) return -1;
   int val = buff[head];
   head = (head+1)%MAXSZ;
}

```

This will work as long as your compiler doesn't do crazy re-ordering of the operations, and as long as you only touch the head with the consumer, and only touch the tail with the producer. Also, the assignments of head/tail need to be atomic, not split up as: `tail++ ; tail = tail%MAXSZ;`

Come to think of it: if a small capacity suffices, like the 80 from the example code, I would use `int8_t` for head/tail, just in case writing an int to memory gets context-switched between writing the LSB and MSB parts. (I don't know RP2040 well enough to know if writing an int is atomic.)

body:
After digging around i was able to use the queue_t from the sdk. and here it is

    queue_t queue;

    typedef struct queueItem {
      uint32_t value;
    } item;

    const int QUEUE_LENGTH = 128;

    void setup() { //CORE 1 setup

      Serial.begin(9600);
      while (!Serial);
      queue_init(&queue, sizeof(item), QUEUE_LENGTH); //initialize the queue

    }

    void loop() { //CORE 1 TIGHTLOOP

      queueItem temp;
      temp.value = random (1000);
      if (queue_try_add(&queue, &temp)) { //adding items to the queue
        Serial.print("ADDING:\t");
        Serial.println(temp.value);
      }

      else
        Serial.println("FIFO was full\n");
      delay(500);
    }

    void setup1() { // CORE2
    }

    void loop1() {  //CORE 2 TIGHTLOOP

      queueItem temp;
      while (queue_try_remove(&queue, &temp)) { //retrieving item from the queue and deleting it from the queue
        Serial.print("ITEM RETRIEVED:\t");
        Serial.println(temp.value);
      }

      delay(500);

    }


body:
I'm working on my first Arduino project using LoraWAN8688 ASR6501 M5 module. I would like one nano to send message, and another nano to receive and read it.

I believe they are not sending or receiving data. I can see Transmission led flashing on one of them, but not Receive led on another.

I think, that my Lora module must be configured before it will be used to send and receive data from Arduino.

How can I send AT+ commands to the LORA module to configure it? Do I need any additional cables or connectors, or can I use Arduino to set it up?

Can I use Serial.println("AT+ADDRESS=1"); to set address via andruino?

[![my setup for tests][1]][1]

RECEIVER CODE:
```
String incomingString;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("AT+ADDRESS=3");
}

void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()){
incomingString = Serial.readString();
if (incomingString.indexOf("TeamA") >0){
delay(500);
}
}
}
```

TRANSMITTER CODE:
```
unsigned long lastTransmission;
const int interval = 1000;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("AT+ADDRESS=2");
}

void loop()
{
if (millis() > lastTransmission + interval) {
Serial.println("AT+SEND=1,6,TeamA");
delay(2000);
lastTransmission = millis();
}
}
```

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

title: M5 Lora module and Nano - does not receive / transmit

Answers: 0


body:
I am trying to communicate through the native USB port of the Arduino Due with a PC.

The native port itself works, I have tested this. The problem is, that every time I upload my Simulink model via the programming port onto the Arduino, Windows loses the connection to the native (Bossa) port.

It does not recocnize the port anymore after programming the Arduino with Simulink (Arduino Support Package). The only way to get Windows to recognise the port again is holding reset+erase on the Arduino, which obviously deletes my application.

Do you know any solution? Is this possible to get the native port working for communication after using Simulink to deploy my application?

title: Arduino native USB port and Simulink

Answers: 1

body: Got it working myself by simply writing the communication part in C for the Due, not using the Simulink blocks.


body:
(Im new to the arduino side of stackexchange). Im working on a worksheet for to begin with arduino. I have prior experiences working with arduinos, but problem is new for my field of expertise. Any help will be well appreciated (need help pls uwu)

Problem statement:

[![Problem statement][1]][1]

I tried different methods to obtain those values, but all are to vain.

Methods that I tried so far:
 - using limits.h, floats.h and inbuild variables of those library -- Problem: Im getting wrong minimum and maximum values for float and double: [![Wrong output][2]][2]
Code:
```
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <math.h>

char fltmax[250];
char fltmin[250];
char dblmax[250];
char dblmin[250];

void sint() {
  Serial.print("Range of signed int: ");
  Serial.print(INT_MIN);
  Serial.print(" to ");
  Serial.print(INT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(int));
  Serial.println(" bytes");
}
void usint() {
  Serial.print("Range of unsigned int: 0 to ");
  Serial.print(UINT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned int));
  Serial.println(" bytes");
}
void schar() {
  Serial.print("Range of signed char: ");
  Serial.print(SCHAR_MIN);
  Serial.print(" to ");
  Serial.print(SCHAR_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed char));
  Serial.println(" bytes");
}
void uschar() {
  Serial.print("Range of unsigned char: 0 to ");
  Serial.print(UCHAR_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned char));
  Serial.println(" bytes");
}
void slong() {
  Serial.print("Range of signed long: ");
  Serial.print(LONG_MIN);
  Serial.print(" to ");
  Serial.print(LONG_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed long));
  Serial.println(" bytes");
}
void uslong() {
  Serial.print("Range of unsigned long: 0 to ");
  Serial.print(ULONG_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned long));
  Serial.println(" bytes");
}
void sshort() {
  Serial.print("Range of signed short: ");
  Serial.print(SHRT_MIN);
  Serial.print(" to ");
  Serial.print(SHRT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(signed short));
  Serial.println(" bytes");
}
void usshort() {
  Serial.print("Range of unsigned long: 0 to ");
  Serial.print(USHRT_MAX);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(unsigned short));
  Serial.println(" bytes");
}
void flt() {
  Serial.print("Range of float: ");
  dtostrf(FLT_MIN, -1, 50, fltmin);
  Serial.print(fltmin);
  Serial.print(" to ");
  sprintf(fltmax,"%e", FLT_MAX);
  puts(fltmax);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(float));
  Serial.println(" bytes");
}
void dbl() {
  Serial.print("Range of double: ");
  dtostrf(DBL_MIN, -1, 50, dblmin);
  Serial.print(dblmin);
  Serial.print(" to ");
  dtostrf(DBL_MAX, -1, 0, dblmax);
  Serial.print(dblmax);
  Serial.print(", which has a storage size of ");
  Serial.print(sizeof(double));
  Serial.println(" bytes");
}

void setup() {
  Serial.begin(115200);
  sint();
  usint();
  schar();
  uschar();
  slong();
  uslong();
  sshort();
  usshort();
  flt();
  dbl();
}

void loop() {
}
```
- Other than using dtostrf(), I found better alternatives at exchange here too such as: https://arduino.stackexchange.com/questions/65813/print-unsigned-long-long-in-esp8266 and https://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm

I tried combining both where the test code that I used before actual implementation:

```
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <limits.h>

void setup () {
  char str[30];
  Serial.begin(115200);
  snprintf(str, 30, "Value of float max = %e", FLT_MAX);
  /*puts(str);*/
  Serial.print(str);
  return(0);
}
void loop(){

}
```

But ```puts(str)``` is not getting printed in the serial monitor.  Then It clicked, that I have to use Serial.(code) for it to get printed in serial monitor, but it ended up in ```Serial.puts(str)``` code not found. Then I tried just ```Serial.print(str)```, but it just outputs ```Value of float max = ?``` (Initially, before I wrote this problem here, it output ```Va``` only, which i have no idea how it changed, but its still wrong). What do I do now? also, Why cant I use puts to print in serial monitor?

The board im using for this is Arduino UNO (ATmega328P)

  [1]: https://i.stack.imgur.com/OihAW.png
  [2]: https://i.stack.imgur.com/3gDVU.png

title: Arduino data-types

Answers: 1

body:
There are two issues here.

One is that the Arduino core uses `Serial` to handle serial I/O, rather
than the traditional libc interface (`printf()`, `puts()` and co.). The
avr-libc does provide the traditional stdio functions, but these will
not work unless you tell them where `stdout` is, which is a bit complex.

The take away is to just use the methods of `Serial` for accessing the
serial port.

Then there is the question: why did it print “Value of float max = ?”.
The reason is that the avr-libc does not provide by default support for
formatting floating point numbers with `sprintf()`. That support is
quite expensive in flash space, and it is omitted unless you link with a
specific version of the avr-libc. The simple workarounds are:

 - Use `Serial.print()` to both format and print floating point numbers,
   which is inconvenient for very small or very large numbers.
 - Use [`dtostre()` or `dtostrf()`][dtostr] to format them.

In your case, `dtostre()` is a better fit:

```c++
void setup() {
    char val[40];
    Serial.begin(9600);
    Serial.print("Range of float: ");
    dtostre(FLT_MIN, val, 5, 0);
    Serial.print(val);
    Serial.print(" to ");
    dtostre(FLT_MAX, val, 5, 0);
    Serial.print(val);
    Serial.println();
}

void loop(){}
```

prints:

```text
Range of float: 1.17549e-38 to 3.40282e+38
```

[dtostr]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#amgrp67796e0946dab291b611cb32584a051f


body:
I try to run an atmega328p as a i2c slave. even with the bare minimum the slave acts as its not wired at all: NACK is transmitted after request (see logic analyzer).

The master should read a constant value in this example. iam using the wire.h lib. pullup resistors on SDA, SCL 4.7kOhm.

**master.ino: esp8266** (working, sends requests)
```cpp
#include <Wire.h>
#define DEFAULT_SLAVE_ADDRESS 0x0A
void setup()
{
  Wire.begin(); // join i2c bus as master
  Serial.begin(9600);
  Serial.println("\n Hello");
  delay(2000);
}
void loop()
{
  //Wire.beginTransmission(DEFAULT_SLAVE_ADDRESS);
  //Wire.write(0);
  //Wire.endTransmission();
  //delay(10);
  Wire.requestFrom(DEFAULT_SLAVE_ADDRESS, 1);
  Serial.println(Wire.read());
  delay(1000);
}
 ```

**slave.ino: atmega328p**
```cpp
#include <Wire.h>
#define F_CPU 8000000UL
volatile uint8_t nr;
void setup()
{
  Wire.begin(0x0A);                // join i2c bus with address #4
  //Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent);
}
void loop()
{
}
//void receiveEvent(int howMany)
//{
//  while(0 < Wire.available()) // loop through all but the last
//  {
//  int x = Wire.read();    // receive byte as an integer
//  }
//}
void requestEvent()
{
  nr = 99;
  Wire.write(nr);
}
 ```
Serial output from master: (got no val)
```
-1
-1
...
 ```
Logic analizer output:
[![nack][1]][1]

Wiring on atmega:
VALUE-PIN
- VCC 7
- GND 8
- SCL 28
- SDA 27

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

  [1]: https://i.stack.imgur.com/PX1Y2.png
  [2]: https://i.stack.imgur.com/aOytI.png

anyone got an idea whats missing?

**Edit: removed `receiveEvent()`, added CPU speed** and it worked

title: I2C / TWI: set up atmega328p as slave

Answers: 0


body:
I am logging binary data to my SD. I log a datetime object of type 'tm', which is 36 bytes on ESP32.
When I create a datetime of type 'tm' on linux it is 56 bytes.

ESP32 write tm to SD:
[tm datetime = 36 bytes]

    time_t t = std::time(nullptr);
    tm datetime = *std::localtime(&t);
    uint16_t t = file.write((const uint8_t *)&datetime, sizeof(datetime)); // ==36 bytes.

PC
[tm datetime = 56 bytes] (compiled using g++ on linux 64)

    tm datetime;
    std::ifstream fileStream(filename, std::ios::binary);
    fileStream.read((char *)&datetime, sizeof(datetime));

tm is defined in time.h:

    struct tm
    {
      int tm_sec;
      int tm_min;
      int tm_hour;
      int tm_mday;
      int tm_mon;
      int tm_year;
      int tm_wday;
      int tm_yday;
      int tm_isdst;
    #ifdef __TM_GMTOFF
      long __TM_GMTOFF;
    #endif
    #ifdef __TM_ZONE
      const char *__TM_ZONE;
    #endif
    };

My tm struct doesn't have the ['tm_gmtoff' or 'tm_zone'][1], even if it had it wont add up to 56 bytes.

How can my tm be 56 bytes on my PC?
If someone has a better way to log a datetime object, without this issue, let me know.

  [1]: https://stackoverflow.com/questions/13969210/size-of-struct-tm

title: sizeof tm struct (datetime) different on ESP32 vs linux64x

Answers: 1

body:
You can not trust system-level structs for data storage or transfer between different systems. The main reasons are:

1. Different data type sizes (16 / 32 / 64 bit ints, floats vs doubles, etc)
2. Struct element alignment differences owing to underlying architecture optimizations and limitations

Unless you are working with a system struct that is specifically designed for cross-system communication you must define your own and pay special attention to the layout.

1. Always use explicitly sized variable types (uint8_t, int32_t, etc for example) to ensure both ends always agree on data storage sizes
2. Always "pack" your struct (`__attribute__((packed))`) to collapse any specially aligned variables into just the room needed to store those variables

Point 2 requires special attention if you're doing much more than filling the struct and saving / transmitting it. It's advisable to never do more than create the struct instance, fill it, save it, then throw it away. If you start doing advanced operations with pointers to the struct you risk corrupting the packing code if the alignment changes. Also packed structs are often slightly slower to access owing to more complex code usually needed to be used to read / write the individual fields within them (especially if there are no byte-wise operations in the underlying architecture).


body:
Hello I have a question on why my port is grayed out when I go to upload?

I’ve watched so many YouTube videos on what’s the problem and have been trying to do everything but just nothing seems to work! Also, in device manager under ports (COM & LPT) the ports have an error sign over it. If someone can help me through this that would be fantastic!

The error when uploading:

problem uploading to board.
Sketch uses 2838 bites (8%) of program storage space. Maximum is 32256 bytes . Global variables use 9bites (0%) Of dynamic memory, leaving 2039 bites for local variables. Maximum is 2048 bytes.avrdude: ser_open(): can’t open the voice “\\.\COM”: The system cannot find the file specified.

title: My port is grayed out?

Answers: 0