body:
I have analog accelerometer that transfer acceleration on 3 axis with frequency 5 kHz. I want to store that data in SD card for in txt file. My sketch is the following:

```
void loop()
{

  // Get raw accelerometer data for each axis
  int rawX = analogRead(A0);
  int rawY = analogRead(A1);
  int rawZ = analogRead(A2);

  // Scale accelerometer ADC readings into common units
  // Scale map depends on if using a 5V or 3.3V microcontroller
  float scaledX, scaledY, scaledZ; // Scaled values for each axis
  if (micro_is_5V) // Microcontroller runs off 5V
  {

    scaledX = mapf(rawX, 0, 1023, -scale, scale); // 3.3/5 * 1023 =~ 675
    scaledY = mapf(rawY, 0, 1023, -scale, scale);
    scaledZ = mapf(rawZ, 0, 1023, -scale, scale);

  }
  else // Microcontroller runs off 3.3V
  {
    scaledX = mapf(rawX, 0, 675, -scale, scale);
    scaledY = mapf(rawY, 0, 675, -scale, scale);
    scaledZ = mapf(rawZ, 0, 675, -scale, scale);
  }

   String dataString = "";
   // Concatenate string
   dataString += String(scaledX);
   dataString += "\t\t";
   dataString += String(scaledY);
   dataString += "\t\t";
   dataString += String(scaledZ);
   dataString += "\t\t";
   saveSD();
}

// Same functionality as Arduino's standard map function, except using floats
float mapf(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void saveSD()
{
  // create file for writing
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  // if file is available
  if (dataFile) {
    // save the data
    dataFile.println(dataString);
    // close file
    dataFile.close();
  } else {
    // if file is unavailable
    Serial.println("Error opening datalog.txt");
  }
}
```
So in loop I open file, write to it and after that close it. When my file will be big enough there will be bottle neck.It will take a lot of time to read and write file.
How to deal with saving data to files on SD card?

**UPD:**
I measured the time of executing code like that:
```
  ...
  start_open_t=micros(); // time in milli seconds
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  delta_open_t=micros() - start_open_t ;
  // if file is available for writing
  if (dataFile) {
    // save the data
    start_write_t=micros(); // time in milli seconds
    dataFile.println(dataString);
    delta_write_t=micros() - start_write_t ;
    // close the file
    start_close_t=micros(); // time in milli seconds
    dataFile.close();
    delta_close_t=micros() - start_close_t ;
    ...

```
And there is the result:
```
Open time:
7656
Write time:
2176
Close time:
8076
```
The open time is increasing there is no surprise (with increasing the file size).
Write to file and close time is almost constant.
I thought to open file in setup() and initialize timer. Write to file in loop() and after some time interval to close the file, after that open new file and so on. But as can be seen the print operation ```dataFile.println(dataString);``` takes approximately 2 ms that is 500 Hz, and it is too slow. I need to register with 5 kHz.
If I print in serial the data is printed much faster but I can not  connect to usb because arduino is located to far (approx 30 meters).
May be there is the way to connect to serial with wifi or bluetooth or may be there are another methods to store the data fast?

title: Efficient way to save accelerometer data on sd card

Answers: 1

body:
I can see it is safe to open/close the file every time, especially closing, as if the Arduino loses power, the entire file can be corrupted possibly.

However, I can find of some 'solutions':

 1. Backup battery

Open the file in `setup()`, and only close the file when the backup battery becomes active (instead of closing the file after every write). This will however need an external battery, and some implementation to check if it is active. Also, during the external battery is active, no data should be written.

 2. Using multiple files

More easier is to use multiple files, and write each time period (less than the  size of the file that cause problems) in a separate file. You can either close the file after each write, or when starting a new period, meaning when the Arduino loses power, you only lose the last time period.

  3. Using binary format

This can be used in combination with solution 1 and 2, and is to not write the files as text files but in binary format, reducing the size considerably.


body:
I want to try out this library:
https://github.com/connornishijima/arduino-volume3

I downloaded the zip file from github, renamed it, and included it as a library in the IDE.

So run one of the examples, `A4_440HZ`
This is its code:

    #include "Volume3.h"
    #define speakerPin 9

    uint16_t frequency = 440;

    void setup() {
      // Nothing neeeded here!
    }

    void loop() {
      for(uint16_t volume = 0; volume < 1023; volume++){
        vol.tone(speakerPin,frequency,volume);
        delay(1);
      }
      for(uint16_t volume = 1023; volume > 0; volume--){
        vol.tone(speakerPin,frequency,volume);
        delay(1);
      }
    }

And i get this error:

    Error Compiling
    A4_440Hz.cpp.o: In function `loop':
    /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
    /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol'
    collect2: error: ld returned 1 exit status

I have no idea what is to blame, or how to mitigate it.

This is the first time that an included example from a library does not play out of the box.

title: Library fails to compile

Answers: 1

body:
This is kind of a weird situation. The library declares the object
`vol`, but fails to define it. On the ancient version of the Arduino IDE
you are using, compilation fails, understandably, because `vol` has
never been defined. What is weird is that, on a more recent version
(1.8.15 on Ubuntu here), compilation succeeds.

It is worth noting that `vol` belongs to the class `Volume`, which is an
empty class. As such, it only plays the role of a namespace for the
functions `vol.tone()` and `vol.noTone()`. Strictly speaking, as `vol`
has no data (its size is zero), the compiler should never need to access
it. My guess is that the newer Arduino manages to compile this only
because it uses different optimization settings than the ancient 1.0.5.

Anyhow, you have two options:

- upgrade your installation of the Arduino IDE

- declare `Volume vol;` near the top of the sketch.

**Edit**: I did some tests and it appears that, as I suspected, this is
related to [link-time optimization][lto] (LTO). Since version 1.5.7, the
Arduino IDE enables LTO, and when this is the case, the linker doesn't
complain about missing empty objects.

The library could be fixed by defining `vol` in Volume3.cpp, although
this would create a weird empty object in the BSS. Another option would
be to declare both methods as `static` within Volume3.h. This would make
the compiler know it doesn't actually need to reference the `vol` object
when one of its methods is called.

Would you submit a pull request with one of those fixes?

[lto]: https://en.wikipedia.org/wiki/Interprocedural_optimization


body:
I'm trying to make a mildly accurate oscilloscope using Arduino Uno R3 and I've done some research on the best method to do so. First of all I need to measure the voltage with a rather high sampling rate and then I'm going to transfer my data through the serial port and plot the data using Python or Matlab.

According to what I have read the `analogread()` function will cause some delay and therefore some inaccuracies and thus it is not suitable for my purpose.

I found on [**this**][1] website some good info about how I should write my code, but I have some questions:

1. I want my reference voltage to be 1.1 V so that by dividing it to 1023 parts I will have an accuracy of about 1 mV. How should I edit the mentioned code in order to do so?

2. The code in the `void loop()` setup is of no use to me (I prefer not to save the measured data on the Arduino and then send to my PC because of memory limitations). After deleting it will the data still be sent to the serial port?

3. Will sending the data through the serial port affect my sample rate/accuracy? I mean how does it effect my accuracy?

P.S: by mildly accurate this is what I mean: I want to measure voltage accurately with 1 mV precision for frequencies of max. 500 kHz (a bit less or more won't hurt).

  [1]: http://yaab-arduino.blogspot.com/2015/02/fast-sampling-from-analog-input.html

title: Mildly accurate oscilloscope using Arduino Uno R3

Answers: 1

body:
> I want my reference voltatge to be 1.1v so that by dividing it to
> 1023 parts I will have the accuracy of about 1mv.

You will have a _resolution_ of about 1 mV. The accuracy will be
significantly worse than that due to the imperfections of the ADC
(offset error, gain error, non-linearity) and noise.

> how should I edit the mentioned code in order to do so?

The reference is configured by the bits `REFS0` and `REFS1` of the
`ADMUX` register. The internal 1.1 V reference is selected by
setting both bits, as shown in table 24-3 of [the
datasheet][datasheet]. You can then patch the original code like this:

```diff
@@ -8,7 +8,7 @@
   ADCSRA = 0;             // clear ADCSRA register
   ADCSRB = 0;             // clear ADCSRB register
   ADMUX |= (0 & 0x07);    // set A0 analog input pin
-  ADMUX |= (1 << REFS0);  // set reference voltage
+  ADMUX |= (1 << REFS0) | (1 << REFS1);  // set reference voltage
   ADMUX |= (1 << ADLAR);  // left align ADC value to 8 bits from ADCH register

   // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
```

> the code in the `void loop()` setup is of no use for me (I prefer not
> to save the measured data on the arduino and then send to my pc
> because of memory limitations). after deleting it will the data still
> be sent to the serial port?

In the linked code, `loop()` is the only function sending anything to
the serial port. If you remove it, nothing will be sent. You could
`Serial.write()` in the ISR though, in which case an empty `loop()`
would be fine.

Note that writing to `Serial` from within an ISR is generally
discouraged. Your situation though (an oscilloscope code) is one of the
very few cases where it does make sense to do so.

> will sending the data through the serial port affect my sample
> rate/accuracy?

It can certainly affect your sampling rate. `Serial.write()` is usually
non-blocking, as all it does is write the data to the RAM-based transmit
buffer. If the buffer fills up, however, `Serial.write()` will block
waiting for the serial port to actually send the data, and make enough
room in the buffer.

This means that, in order for the oscilloscope to not miss samples, you
have to make sure that the serial port can send the data at least as
fast as the ADC is acquiring it.

**Example calculation**: If you clock the ADC at 1 MHz, you get one
sample every 13 µs. You can follow the example given in the code
you linked to, and discard the last two bits in order to transmit only
8 bits of the sample. Transmitting those in plain binary will take
10 “bits” worth of the serial port bandwidth (one start bit,
8 data bits and one stop bit). Each bit should then take less than
1.3 µs, which translates to a baud rate of 769,231 bits per
second. You will probably have no other choice than configuring the
serial port for 1 Mb/s.

If you want to transmit the whole 10 bits of the ADC readings, you
will have to lower the sampling rate by a factor two.

At this point you may notice that the serial port, rather than the ADC,
is the bottleneck for the performance of your oscilloscope. If this is
too limiting, you may consider building a scope that works by bursts: it
stores a burst of samples in memory, then sends it at a leisurely rate
through the serial port.

[datasheet]: https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738867


body:
Hello I would like to create an Arduino protoype with Led WS2182B.
I currently have
Arduino NANO (not UNO, like in this schema)
65 Led WS2182B = Which gives me 3.9 Amp of suply for full brighness (65*60mAmp)
Power supply of a movil charge wich have 5V 2.1 A

I am currently working with this schema from this [website][1]

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

I have a few questions
1) Does this battery will work for this schema replacing the usb conector?
2) Can I use the 68 leds at a medium energy, to make it suitable wih the power supply? Can this damage any device (Because in theory I believe it needs more than 2.1 Amps)
3)If this battery will not be appropiate to this schema. What could I do?

Thank you very much!

  [1]: https://core-electronics.com.au/guides/ws2812-addressable-leds-arduino-quickstart-guide/
  [2]: https://i.stack.imgur.com/rsZ5o.png

title: Does an 5V 2.1 A will fit for this Led Schema?

Answers: 1

body:
You are using a standard USB power bank. It should be possible to power your project as long as you stay below the current limit (2.1A). Probably you should keep the intensity small enough to not exceed 1.9A in normal operation. That should be enough for about half intensity. You really don't want to exceed the current limit. And you should measure the actual current draw and then approach your own current limit (like 1.9A) from below. Calculations are good, but when operating like this you should look at the real values.

If you exceed the current limit of the power bank it depends on the implementation of the power bank what will happen. Most likely the power bank will cut the power but still work. Though it is also possible, that you fry some electronics inside the power bank and kill it this way.

Note:
- While you experiment with your code you can use fewer LEDs, so that they would be able to light up at full intensity. That makes sure, that you don't damage anything from a small programming error. If you write your code in the correct way (for example defining the number of LEDs at exactly one code line and reusing that name everywhere), then it will be easy to increase the number of LEDs to the target and also be sure, that you are staying within your limits.
- You already have it in your wiring diagram, but nonetheless I want to emphasize, that you must not power the LEDs through the Arduino. You need to connect them directly to the USB cable to the power bank. The Arduino cannot withstand such currents.
- USB power banks often cut power, when not enough current is being drawn from them (and for mine the current of an Arduino Nano wasn't enough to hold it active). If in your project the LEDs get turned of at some time, while the Arduino should keep running, the power bank might cut the power, thus turning off the Arduino. In my experience the bigger, more expensive power banks will do that, while small, cheap ones will just keep outputting the power. If this scenario is relevant for you, you need to test this yourself with your specific power bank.

> If this battery will not be appropiate to this schema. What could I do?

You could use multiple of these power banks, each of them powering its own part of the LED strip. One of them can also power the Arduino. Just make sure to connect all grounds together.


body: I want to create a joystick for my flight simulator and I need to make an Arduino Uno Rev3 pretend to be a joystick when I plug it to my computer.

title: Can I make an Arduino Uno Rev3 pretend to be a joystick?

Answers: 1

body:
The Uno doesn't have native USB capabilities. It uses an additional microcontroller (the Atmega16u2) as an USB to Serial adapter. In the default configuration this microcontroller is only programmed for providing a serial interface over USB, not a joystick interface. You can hack your Uno and reprogram the Atmega16u2 for providing a joystick interface (and there are tutorials for how to reprogram the Atmega16u2 online). (Note, that you need a genuine Arduino for this to work, since the cheap clones often only have CH430 chips as USB to Serial adapter)

But I would suggest going the easier way and buying an Arduino board, which itself has USB capabilities without the need of hacking the board, like the Arduino Micro. Then you can simply use one of the joystick libraries on it. This way will be a lot easier for a beginner than doing it with an Uno.


body:
I want to strobe 3 LEDs (at independent frequencies and duty cycles) via mosfets with a duty cycle of 0.05%-1% at a frequency range of 24-100 hz. I would like to hold 1% or better accuracy for both duty cycle and frequency.

The Teensy 4.x seems perfect with its amazing PWM frequency and resolution controls, and generous number of independent PWM timers.

 1. For the purposes of my application, should I use pins with FlexPWM or QuadTimer? Does it matter?
 2. I see that the numbering convention is X.Y, is there any functional significance when X numbers are in common (IE FlexPWM 1.0 and FLexPWM 1.1)?

[See "Frequency" section of this page][1]

  [1]: https://www.pjrc.com/teensy/td_pulse.html

title: Teensy 4.1 / 4.0 When to use FlexPWM vs QuadTimer pins to strobe LEDs

Answers: 1

body:
I had cross-posted, and Paul Stoffregen answered [in the Teensy Forum][1].
Pasting Paul's great answer here for posterity:

> 1: Really doesn't matter for 0.05% accuracy.
>
> 2:See "PWM Frequency" on [this page.][2]
>
> The 3 pins identified as "FlexPWM1.0" (1, 44, 45) will always run at
> the same frequency. If you want different PWM frequency, you would
> need to choose pins from different groups.
>
> More detail on how the hardware actually works can be found in the
> reference manual. But usually that ends of being far too much
> information. The timers are packed with a mind boggling number of
> advanced features, which makes a steep learning curve if you want to
> dive into how the hardware really works.
>
> Most applications work fine by simply using analogWrite,
> analogWriteResolution and analogWriteFrequency. Everything you've said
> sounds like a pretty simple application that can be done easily with
> these 3 functions. You're only looking for 9 bit resolution from
> hardware than is natively 15 or 16 bits. Just use the easy functions
> do the low-level work for you.

  [1]: https://forum.pjrc.com/threads/70530-Teensy-4-1-4-0-When-to-use-FlexPWM-vs-QuadTimer-to-strobe-LEDs?p=308324#post308324
  [2]: https://www.pjrc.com/teensy/td_pulse.html


body:
I'm currently working on a project where you essentially will have multiple Arduinos (1 Uno, multiple Nanos) daisy-chained, only connected through 2 digital pins and one wire for Serial communication (RX Pin -> TX Pin). (The first one is connected via USB to the PC.)

I figured the serial communication between the first Arduino and PC would also be forwarded through the RX and TX pins, but that doesn't seem to be the case.

As it's fairly tedious to update one at a time, is there a way of updating all of them at once, using only the one-way serial communication wire?

EDIT: Yeh so like imma just add a USB Port to every single component to the chain to update separately, and update every single one of them separately.

title: Uploading sketch to multiple Arduinos connected in series

Answers: 2

body:
Try connecting only the RX and reset pins. Serial programming is done by the bootloader, but it needs to be switched into programming mode first, which is done by resetting the chip and then sending a special code to the RX pin within a certain time period. When you program through the serial port (as you are doing with the Uno) the FTDI chip drives this pin for you, but you'll need to cascade that reset signal through to the other chips as well. This still isn't guarenteed to work 100%, because it depends on a number of other factors as well, but at least you'll have a chance.

When I've done stuff like this commercially I've programmed via the ICSP connector instead and made programming rigs out of spring-loaded pin connectors that the target boards simply clip onto. If you're planning on doing this with any degree of frequency then I'd recommend investing a bit of time into doing this yourself.

UPDATE: ok, I can see now why this isn't working. The Nano's CH340 usb-to-serial chip is pulling RX low, preventing the data stream from being read. Would work fine with standalone chips, obviously doesn't on the Nano.

I think your best option is to use ICSP. It's an extra pin, but if you breadboard then it shouldn't make any difference. Plus there are a number of advantages to doing so, including faster programming, the ability to upload/replace the bootloader and the ability to change fuses (e.g. to protect your firmware or disable the bootloader altogether to give you app more Flash space etc).

If you don't already know how to do this then the layout is:

 - Connect Uno SCLK(D13)/MOSI(D11)/GND pins to all the corresponding Nano pins.
 - Connect Uno D10 to all the Nano's RESET pins.
 - Connect Uno MISO(D12) to only the first Nano's MISO pin.
 - Connect Uno VIN to all the Nano VINs (you don't want all the Nanos being driven from the Uno's regulator)

Should wind up looking something like this:

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

Prepare the Uno for programming:

   - Set your IDE board type to Uno
   - Set IDE programmer type to "AVR ISP"
   - Upload IDE ArduinoISP sketch to the Uno

And now you're ready to program the Nanos:

   - Set your IDE board type to Nano
   - Set IDE programmer type to "Arduino as ISP"
   - Upload your Nano sketch using "Upload Using Programmer"

Just tried it now with the two Nanos in the photo, worked fine.

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

body:
There is a two-way protocol used by the bootloader which I describe [here](https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader/15937#15937).

You could conceivably connect all the Rx wires together, and use the Tx wire from the first one (so it responds appropriately), and discard the responses from the other units. If they program at exactly the same rate, and reset at exactly the same moment, that might work.

You might be better off just uploading using a device designed to do that, as I describe [on my forum](http://gammon.com.au/forum/?id=11638). The Atmega328P programmed using that method can be reprogrammed in about one second (so the time to hook up the wires is the long part). Using the ICSP interface on the chips, and a suitable plug, could make that very quick, and easy.

There are also stand-alone devices, for example [the Crossroads standalone programmer](http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html) which uses the techniques described in my forum post. You can use that in the field because it doesn't require a monitor or PC. You just hook it up via the ICSP port, select what file you want to upload, and hit the "program" button.


body:
I got the following data as shown in the figure from imu razor which is connected to Arduino Mega 2560 in the serial monitoring and I want to get only the data that starts with "#A-R= "

Can any one provide me with code to do this?

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

This is my code:

    #define BUFF_SIZE 40
    char buffer[BUFF_SIZE];
    String header ;
    char Bufferheader[4] ;

    void setup(){
    Serial.begin(57600);
    Serial2.begin(57600);
    Serial2.write("#osct");
    }

    void loop() {

    int i = 0;
    while(Serial2.available()) {
    buffer[i++] = Serial2.read();
    if(i == BUFF_SIZE) break;
    }

    for(int j = 0; j < i; j++) {
    Serial.print(buffer[j]);

    }
    }

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

title: How to display only specific data in the serial monitoring?

Answers: 2

body:
Your code is doing literally nothing except reading from one serial port and passing it to another.

You need to throw away pretty much all that code and do some actual processing of the data.

You need to:

1. Read the incoming data a line at a time (that is, read everything up to the line ending into a buffer)
2. Examine the start of that buffer
3. Output whatever data from the buffer your examinations deem appropriate.

I can't go into detail here about how to do it, but there are tutorials covering all those topics available on the web. For the serial reading I have [a tutorial](https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27) that you may find helpful.

body:
The method outlined by Majenko is the general way of dealing with this
kind of requirement, and also probably the “cleanest” way. If, however,
you are confident that the incoming data always follows the pattern you
are showing, then you can “cheat” and cut some corners.

Consider this: in the sample you show, the character `'A'` only ever
appears as the second character in a line, and always as part of the
sequence `"#A-R="`. If you are confident that this is always the case,
then you can apply the following algorithm:

- the program processes one input character at a time, and decides
  whether to print it to its output or not
- it has two possible states: either it is printing every character it
  reads (because it believes the character belongs to a “#A-R” line), or
  it is not
- if it is printing and it reads an end of line, it prints that end of
  line, and then stops printing
- if it is not printing and it reads an `'A'`, it outputs `"#A"`, then
  starts printing all its input.

In code:

```c++
void loop() {
    static bool printing = false;  // are we printing what we read?
    if (Serial2.available()) {
        char c = Serial2.read();
        if (printing) {
            Serial.write(c);
            if (c == '\n')  // on end of line, stop printing
                printing = false;
        } else if (c == 'A') {  // on 'A', start printing
            Serial.print("#A");
            printing = true;
        }
    }
}
```

This code assumes your device uses ASCII LF (`'\n'`) as end-of-line
indicator. You will have to replace `'\n'` by `'\r'` if it uses ASCII CR
instead.


body:
I have a big-ish electrode (10cm x 10cm) that works fine for detecting touch over the whole electrode (as a boolean - simple touch vs. release) but I was wondering if there was a way to detect where on the electrode there was a touch, using filtered data or something? I saw [this][1] link where the person made a capacitive touch grid. All their copper tape rows/columns are touching. When I try to connect multiple clips to a single electrode though (more-or-less what they did) my MPR121 becomes unresponsive.

I'm using an Arduino Uno, a Sparkfun MPR121 capsense breakout, and [this][2] library for interacting with the MPR121.

Here's a basic program I have running at the moment just to check out an average of filtered data readings to see if there's a pattern. There isn't. The readings are anywhere between 250 and 580 no matter where the electrode is touched.

    #include <MPR121.h>
    #include "Wire.h"

    int readingSum = 0;

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      MPR121.begin(0x5A);
      MPR121.setInterruptPin(2);

      MPR121.setTouchThreshold(50);
      MPR121.setReleaseThreshold(40);

      delay(1000);
    }

    void loop() {
      if (MPR121.touchStatusChanged()) {
        MPR121.updateAll();
        if (MPR121.isNewTouch(0)) {
          for (uint8_t i = 0; i < 8; i++) {
              readingSum += MPR121.getFilteredData(0);
          }
          Serial.println(readingSum / 8);
        }
        readingSum = 0;
      }
    }

  [1]: https://create.arduino.cc/projecthub/gatoninja236/capacitive-touch-sensing-grid-f98144?ref=tag&ref_id=capacitive&offset=7
  [2]: https://github.com/BareConductive/mpr121

title: Detect where touch happened on a big capacitive electrode

Answers: 1

body:
As @jsotola mentioned in the comments, no I don’t think there is a way to take a single electrode and turn it into a [touchpad][1]. Touchpads rely on a grid of addressable capacitance points to resolve a location.

I didn’t spend a lot of time investigating the link you referenced. However I wonder if you allowed for the adhesive backing on the copper tape when you attempted to replicate the example. It looks to me to be rows and columns of copper conductor separated by a thin layer of adhesive. Not the same thing as one big conductor.

  [1]: https://en.wikipedia.org/wiki/Touchpad


body:
I'm attempting to connect 6 DS18B20 temperature sensors to an Arduino GPIO pin in a topology that looks something like this:

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

Conceptually, it's a star network with two star subnets.

The GPIO pin on the Arduino is connected to point "E" through a 4-inch wire, a JST connector, and another 4-inch wire.

The 3 wires (shown in green) connecting sensors "A", "B", and "C" to point "D" are approximately 3 feet long (and are, in fact, the original ~1-meter wires that came pre-attached to the sensors when I bought them). Segment ED is ~4 feet long.

The 3 wires (shown in blue) connecting sensors "G", "H", and "I" to point "F" are approximately 20-30 feet long (including the original 3-foot wires attached to the sensors when I bought them). Segment EF is ~8 feet long.

No parasitic power is involved. Every DS18b20 has 3 wires... +5v (probably closer to 4.5v by the time it gets to G/H/I), ground, and 1-wire data.

#### So... where would YOU recommend putting resistors (feel free to describe points besides the ones I labeled with letters), and what values would you use?

And... would it actually be any *better* to take advantage of the fourth (presently unused) wire in the cables I have connecting G, H, and I to F as a 'return wire' to turn it into a much longer daisy chain (E to F, F to G, G back to F, F to H, H back to F, F to I), or something even more radical (say, ED, DA, AD, DB, BD, DC, CD, DE, then continuing the daisy chain with EF as described previously)?

For what it's worth, I presently have a single 4.7k pullup resistor sitting at point "E", and it seems to work... but after reading Maxim's AppNote about ["Building reliable long 1-wire networks" (Appnote 148)][2], I'm feeling like it *shouldn't* work, and that I really *ought* to do something more sophisticated for the sake of long-term reliability.

  [1]: https://i.stack.imgur.com/o0JZE.png
  [2]: https://pdfserv.maximintegrated.com/en/an/AN148.pdf

title: Suggested pullup resistor values for 1-wire network

Answers: 1

body:
I have a linear network with three thermos at roughly 5', 20', and 40-50' from the micro (a 5v '328p), as well as being parasitically powered. The physical bus is a twisted pair from a Cat-5 cable. The pullup is 4.7KOhm on the processor board.

I've tested this network using a 3.3v '328p and it wasn't as reliable, but reducing the pullup to 2.2K (IIRC) fixed it.

I find Maxim's App Note 148, "[Guidelines for Reliable 1-Wire Networks][1]" to be very helpful and is my go-to for 1-wire network questions.

  [1]: https://pdfserv.maximintegrated.com/en/an/AN148.pdf


body:
When buying a barometer for my current project at work, I chose the MikroElektronika click 3 barometer. However, as it turns out, the library for it doesn't exist for Arduino.
I know it uses I2C communication, so I tried connecting the board to my Arduino UNO R3 as follows:

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

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

<!-- End schematic -->

However, I do not know how to use the output of the sensor. Is there a way to access the raw data measured by the sensor and post-process it myself, or is a library needed?

Thanks for your help

title: Using an I2C barometer

Answers: 1

body:
I have found MikroElektronika library for the barometer 3. You can get basic idea how to communicate with the sensor.
[MikroElektronika c libraray][1]

  [1]: https://github.com/MikroElektronika/mikrosdk_click_v2/tree/master/clicks/barometer3

You can develop your own library based on that one for Arduino or you can read the data sheet of the sensor for more details.


body:
Minimal working example:
```
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  noInterrupts();
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
```

When uploaded to my Arduino Nano 3.3v BLE from my M1 Mac, this causes the Nano to no longer appear in the ports menu. In order to get it to appear again, I have to double press the reset button on the Nano so that it resets to a default script. After doing this, the Nano is available in the ports menu again.

I also cannot see the Nano via `cat /dev/cu.<TAB>` when this script is uploaded to it.

Does anyone know why this happens? Or alternatively (if this is intended behaviour) why it is not documented in [`interrupts()`](https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts) or [`noInterrupts`](https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts)?

I've looked through some other posts, but I don't think they're duplicates of this one:
- [What functions are disabled with noInterrupts()?](https://arduino.stackexchange.com/questions/61567/what-functions-are-disabled-with-nointerrupts): doesn't highlight the behaviour I've seen in the MWE.
- [Trying to understand interaction of interrupts, noInterrupts and delays](https://arduino.stackexchange.com/questions/35358/trying-to-understand-interaction-of-interrupts-nointerrupts-and-delays): Gives interesting techniques for interrupts and embedded programming, but doesn't mention the behaviour I've seen

#### Edits in response to answers

So the MWE wasn't quite descriptive enough of my problem and some of the answers got caught up on that (which is my fault). I've included a more detailed description of what I'm doing below to describe what I'm actually doing, but I've also accepted the answer which I think answers the heart of the question "why do interrupts cause the Nano to not appear in port?".

What I'm actually doing is I've got two Arduino Nanos (call them primary and secondary) connected via I2C and `Wire.h`. Each Arduino nano is reading 15 analog inputs (via a multiplexer). The secondary Nano is then sending its 15 analog readings to the primary over I2C. But I'm getting a lot of noise in the analog readings of the primary Nano, but no noise in the secondary. This noise disappears when I disconnect I2C. So my theory was that digital SCL and SDA wires were causing noise in the analog sensor wires, but I observed the noise would only occur for ~2ms every ~10ms. I thought I'd disable interrupts (and therefor disable `Wire.h` from pulsing SCL/SDA) while I was reading the primary's analog sensors, and enable interrupts afterwards. This caused the Nano to not appear in the Ports tab, and the rest is the result of this post.

I now think I didn't include the 4.7Ohm pull-up resistor on SDA and SCL which seems to only be included on the official Arduino examples, and never on any random internet examples.

title: `noInterrupts()` causes the arduino to no longer appear in ports

Answers: 1

body:
I'm not really an expert on the Nano 3.3v BLE, however it appears that it is directly connected to the USB port and thus disabling interrupts will also disable its ability to respond to USB handshakes, thus it will appear to the host that it has been unplugged.

The original Nano had a separate chip (FT232RL) which handled the USB interface, and thus disabling interrupts on that Arduino would not drop the USB connection.

>  Or alternatively (if this is intended behaviour) why it is not documented in interrupts() or noInterrupts?

Probably the documentation has not kept up-to-date with later product releases. It is not uncommon for documentation to lag behind what the released products actually do.

As timemage points out in another answer, your attempts to blink LEDs with interrupts turned off will not succeed. In fact, turning interrupts off should only be done for milliseconds, not permanently. I assume that is a demonstration sketch, but still ... if you turn interrupts off only briefly the problem should go away.


body:
*Note: This is a reference question (but feel free to write answers of your own!)*

---

I want to use the AVR tools directly -- no arduino-builder or arduino-cli. I would also like compilation and uploading to be as fast as reasonably possible

title: How do I build and upload a C++ program without the Arduino Library or IDE?

Answers: 1

body:
1. Create a new file called `Makefile` in your project directory. Populate it with the following contents:

```Makefile
TEMPDIR := $(shell mktemp -d)

all:
 avr-g++ -DF_CPU=<CLK> -mmcu=<PARTNO> -fno-threadsafe-statics -O3 -flto -std=c++23 -isystem/usr/avr/include -lm -fuse-linker-plugin -Wl,--gc-sections *.cpp -o ${TEMPDIR}/a.elf

 avr-objcopy -O ihex -R .eeprom ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
 avrdude -V -p<PARTNO> -carduino -P/dev/tty<SERIAL_PORT> -b<BAUD> -D -Uflash:w:${TEMPDIR}/a.hex

 rm ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
 rm -d ${TEMPDIR}
```

2. In the Arduino IDE, press Ctrl+, and enable verbose output during compilation and uploading.
3. Start uploading with Ctrl+U. Replace the groups of angled brackets in Makefile (e.g. `<CLK>`) with the values in the Arduino IDE's build output.
4. Run `make`.

`-lm` links in the AVR math library. `*.cpp` refers to your c++ source files. `-V` prevents avrdude from reading back the flash contents and verifying it, which saves time, but you may want to disable it while diagnosing problems.


body:
*Note: This is a reference question (but feel free to write answers of your own!)*

---

I uploaded code that contains a bug that causes my Arduino to immediately reset itself when starting using [this](https://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_softreset) code from the AVR libc FAQ. The built-in LED keeps flashing. Because it's in this state of constantly resetting, I'm unable to upload my sketch to it.

I tried holding the reset button while uploading and burning a new bootloader, but neither of those worked.

How do I get my Arduino out of this boot loop so I can upload sketches again?

title: How do I escape a boot loop?

Answers: 1

body:
1. Start holding the reset button. This is to prevent the Arduino from entering the boot loop.
2. Unplug the Arduino and plug it back in.
3. Open a new sketch. Remove all of the code and replace it with `int main(){}`. This is to create a small program that will upload quickly.
4. Start uploading the sketch. Avrdude will attempt to upload the sketch ten times -- each time it tries, the RX LED on the Arduino will flash briefly.
5. Notice how often the LED flashes (0.2 Hz for me). Right before it flashes again, release the reset button. There's a small window of oppurtunity for avrdude to upload the sketch before the arduino starts up. If the TX and RX LEDs flash, success!


body:
I am trying to get the NRF24 Modules to work but all I get is short lived moments of when it works. I am using the transmitter to send signals to the receiver, which in turn sends a signal to the Motor Controller module to spin the motor.

Both the transmitter and receiver are connected on Nano Every's. Currently they both Arduinos are powered with 9v batteries with the NRF24 modules connected to the 3.3v pin. Both NRF24 modules have 10uf caps connected. I double checked for connections issues and shorts.

Sometimes the Rx and Tx connect and the motor spins correctly and everything is fine. This lasts only a few moments before it stops responding again. Usually it happen when I connect the USB to the transmitter to see what the Serial console is printing. Once I open up the Serial monitor it might, if I am lucky, connect and work for a bit.

I don't have any reason to believe that it is a connection issue since it sporadically works as intended. I can post a diagram if needed. If anyone has any clue I'd appreciate the help.

Here is my Tx code:

    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>

    const byte ledPin = 5;

    RF24 radio(7,8); //CE, CNS
    const byte address[6] = "00001";
    const int button = 3;
    int buttonPressed;

    int joystick;

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    radio.begin();
    radio.openWritingPipe(address);
    radio.setPALevel(RF24_PA_MAX);
    radio.setDataRate(RF24_250KBPS);
    radio.stopListening(); //transmitter

    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    delay(300);
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    radio.printDetails();

    }

    void loop() {

      // put your main code here, to run repeatedly:

      joystick = analogRead(A1);
      Serial.println(joystick);

      if(joystick > 530)
      {
        motorForward(joystick);
      }
      if(joystick < 480)
      {
        motorBackward(joystick);
      }
      if(joystick >= 480 && joystick <= 530)
      {
        motorStill();
      }

    }

    void motorBackward(int jsInput)
    {
     //digitalWrite(motorPin1, LOW);
     //digitalWrite(motorPin2, HIGH);
     int motorSpeed = map(jsInput, 480, 0, 0, 255);
     int message[] = {2, motorSpeed};
     radio.write(&message, sizeof(message));
     //analogWrite(motorPWM, motorSpeed);

     delay(20);

    }

    void motorForward(int jsInput)
    {

     int motorSpeed = map(jsInput, 530, 1023, 0, 255);
     int message[] = {1, motorSpeed};
     radio.write(&message, sizeof(message));

     delay(20);

    }

    void motorStill()
    {

        int message[] = {0};
        radio.write(&message, sizeof(message));
    }

Here is my Rx code:

    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #define motorPWM 6

    RF24 radio(7,8); //CE, CNS
    const byte address[6] = "00001";

    byte motorPin1 = 4;
    byte motorPin2 = 5;

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    radio.begin();
    radio.openReadingPipe(0,address);
    radio.setPALevel(RF24_PA_MAX);
    radio.setDataRate(RF24_250KBPS);
    radio.startListening();

     pinMode(motorPin1, OUTPUT);
     pinMode(motorPin2, OUTPUT);
     pinMode(motorPWM, OUTPUT);

     //test motor
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPWM, 600);
    Serial.print("Test motor started");
    delay(2000);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin1, LOW);
    Serial.print("Test motor complete");
    radio.printDetails();

    }

    void loop() {

      // put your main code here, to run repeatedly:

    if(radio.available())
    {
       //0 = still, 1 is forward and 2 is backward
      int message[2];
      Serial.println("radio detected");
      radio.read(&message, sizeof(message));
      Serial.println(message[0]);
      Serial.println(message[1]);

      if(message[0] == 1)
      {

        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, LOW);
        analogWrite(motorPWM, message[1]);
        delay(20);
        Serial.println("move forward");
      }

      if(message[0] == 2)
      {
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, HIGH);
        analogWrite(motorPWM, message[1]);
        delay(20);
      }

      if(message[0] == 0)
      {
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, LOW);
        delay(20);
      }

      Serial.println("radio available");

    }

    }

title: NRF24L01 modules fail to stay connected. Work intermittently

Answers: 0


body:
I am having issues using the following [USB to UART module][1]. I am using an Arduino 2560 clone.

I have two connections with the Arduino:
 1. COM7 which consists of the given module, connected to the main Rx0/Tx0 on the Arduino, with yellow to Tx0, orange to Rx0 and ground to the Arduino ground.
 2. COM4 which consists of a usual USB to USB module, connected to the Arduino's USB port.

I can read from the Arduino perfectly fine using either COM4 or COM7, but I cannot send data through the serial or upload a program to it through COM7, only through COM4.

I have tried the following for uploading data with COM7: PuTTY and Arduino Serial.

Once again: The Arduino can correctly receive a program file or read serial input data from COM4, it correctly outputs data to either COM4 or COM7, but I cannot upload data to it from COM7.

Code I am using to test the COM7's ability to send data:

    int incomingByte = 0; // for incoming serial data

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

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

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

  [1]: https://docs.rs-online.com/12f1/0900766b811b9e83.pdf

title: Can read Serial but cannot write - serial communication Arduino Mega 2560 clone

Answers: 0


body:
*Note: This is a reference question (but feel free to write answers of your own!)*

---

My Arduino takes too long to start up, I need to use the space taken up by the bootloader and I don't want a brown-out to be able to move the program counter to bootloader code, which could lead to my code being corrupted.

I considered buying an Arduino programmer, but since I already have an Uno lying around doing nothing, I would rather use that as a programmer.

I found a few guides on the internet, but most of them leave important details out and aren't specific enough.

So, how can I upload a sketch without a bootloader, using another Arduino as a programmer?

title: How do I upload a sketch without a bootloader, using another Arduino as a programmer?

Answers: 1

body:
There are a few guides on the internet that explain how to do this, but I've
found that most of them contain too much ambiguity or leave important details
out. This is my attempt at writing a short but complete guide that's easy to
follow.

## Prerequisites

- The board that will run your sketch
- A board that will act as a programmer (a.k.a. "ISP")
- 7 wires
- Any small capacitor

## Steps

### Programming the programmer

First, you'll need to upload the ArduinoISP sketch to the programmer. Here's
how:
1. In the Arduino IDE, press Alt+F and open Examples ->
   11.ArduinoISP -> ArduinoISP.
2. Plug in the programmer board (USB).
2. Press Alt+T and set "Board" to your *programmer*
   board's type and "Port" to your *programmer* board's serial port.
3. Press Ctrl+U to upload the sketch to your programmer.

### Connecting the boards

Then you need to connect the programmer to the board that will run your sketch.

1. Unplug the programmer board. This is to prevent accidental short-circuits.
2. Connect pins **GND, 10, MOSI, MISO, SCK and 5V** of the programmer to pins
   **GND, RESET, MOSI, MISO, SCK and 5V** of the board that will run your
   sketch, respectively. Pins MOSI, MISO and SCK correspond to pins 11, 12 and
   13, respectively, on the Uno and the Nano. Consult your board's datasheet if
   you're uncertain.
3. Connect the capacitor between pins 5V and RESET of the programmer board. This
   is to prevent it from auto-resetting while programming.
4. Plug in the programmer board. You will never need to plug in the board that
   will run your sketch.

### Uploading your sketch

The order of these steps is important due to a bug in the Arduino IDE.

1. Press Alt+T and set "Board" to *the board that will run
   your sketch*'s type, "Port" to your *programmer* board's serial port and
   "Programmer" to "Arduino as ISP".
2. Open the sketch you would like to upload.
3. Press Ctrl+**Shift**+U to upload the sketch using the programmer.

## Troubleshooting

If something went wrong, press Ctrl+, and enable verbose
"compilation" and "upload" and repeat the step that went wrong. Look out for
these error messages:

### `avrdude: stk500_recv(): programmer is not responding`

Followed by something similar to:

```plaintext
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
```

Remove the capacitor before uploading a sketch to your *programmer* board.

### `avrdude: Yikes!  Invalid device signature.`

Scroll up and copy the line that looks similar to the following:

```plaintext
...avrdude -C...avrdude.conf -v -V -p... -c... -P... -b... -Uflash:w:....hex:i
```

Paste it into a terminal and add ` -F` to the end. You can reuse this command
every time you upload the same sketch.

### The upload seems to succeed but my sketch is still running the same code!

If the board that runs your sketch's CPU clock is slower than 1MHz (e.g. your
sketch modifies the CPU prescaler), you need to change `(1000000/6)` in the
ArduinoISP sketch to something slower and re-upload the sketch to your
programmer.


body:
The power supply is external. I want to clear one strip say pin 7, and meanwhile i dont want other strip say pin 6 to switch off...I use
         FastLED.clear();
         FastLED.show();
But it clears all the led strips connected to pin6 and pin7. What is the code to switch off only one strip?

title: How can I clear two FastLEDs strip ws2812b separately? One strip is connected to pin 7 of UNO and other strip to pin 6 of UNO

Answers: 1

body:
You can use two `CLEDController` instances, which you can control separately, and by using the `clearLedData` you can clear either one or the other LED strip (depending on the `CLEDController` instance).

Below is the code I copied from
https://forum.arduino.cc/t/xrads-fastled-fastled-clear-question/693569/8
which contains more info:

    #include <FastLED.h>

    #define COLOR_ORDER GRB
    #define LED_TYPE WS2812B

    #define DATA_PIN 9
    #define NUM_LEDS 26
    CRGB leds[NUM_LEDS];

    #define HEADLIGHTS 10   //headlight led pin
    #define NUM_HEADLIGHTS 2
    CRGB leds2[NUM_HEADLIGHTS];

    CLEDController &ledController = FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
    CLEDController &headlightController =   FastLED.addLeds<LED_TYPE, HEADLIGHTS, COLOR_ORDER>(leds2, NUM_HEADLIGHTS);

    void setup() {
      ledController.setCorrection(TypicalLEDStrip);
      headlightController.setCorrection(TypicalLEDStrip);

      ledController.clearLedData();
      headlightController.clearLedData();
      FastLED.show();
    }

    void loop() {
    }


body:
I'm looking for a way to store data on flash as on ESP8266 or ESP32 using `FS.h`,  `LITTLEFS.h` but it fails.

Is is possible on Nano IOT33 ?

title: Arduino Nano IOT33 - Using flash

Answers: 1

body:
It seems this library can be used:

https://github.com/cmaglie/FlashStorage

Library: FlashStorage library for Arduino

About info: A convenient way to store data into Flash memory on the ATSAMD21 and ATSAMD51 processor family

Mentioned in external related article (thanks to Juraj): https://forum.arduino.cc/t/persistent-storage-for-arduino-nano-33-iot-no-eeprom/623137

**UPDATE**

(See remark of Juraj below: this is NOT for a Nano IOT33)

See Library: https://github.com/khoih-prog/FS_Nano33BLE

About info: Wrapper of FS (LittleFS or not-advisable FATFS) for Arduino MBED nRF52840-based boards, such as Nano_33_BLE boards. This library facilitates your usage of FS (LittleFS or FATFS) for the onboard flash. FS supports power fail safety and high performance

Mentioned in:
https://forum.arduino.cc/t/fs-nano33ble-library-for-nano-33-ble-using-littlefs-fatfs/900463


body:
I am working on a project where I need to log data, but I was wondering if it is possible to log that data to a thumb drive? I know that I can log data to an SD card, but I thought a thumb drive would be more accessible to users who wish to obtain the data. And if it is possible to log to a thumb drive, could it be done in CSV format?
The data is just sensor data.

title: How can I log data to a thumb drive?

Answers: 2

body:
In principle you can log to a thumb drive any data you want, binary and text (thus also CSV).

However, the Arduino Uno does not support connecting a USB stick directly. If you want to connect a USB stick, you need a so called USB Host shield (for Arduino).

More information can be read on the Arduino site at this page:

https://docs.arduino.cc/retired/shields/arduino-usb-host-shield

body:
[Updated]

As an alternative to a Uno host shield, changing to a different Arduino MCU may also assist. USB host capabilty is needed for communicating with thumb drives.

[Some Arduino models][1] have a native USB port (e.g., Arduino Due, Arduino Leonardo, Arduino Micro, Arduino Nano 33 IOT, Arduino Zero, Arduino MKR Zero, Arduino MKR1000 ... ) which will work as a USB client device role.

A smaller set of MCU can act as either a USB client or host (e.g., Arduino Due, Arduino Portenta, ...). There is a [USBHost][2] library for Arduino Due listed in the Arduino Reference. Documentation for Arduino Portenta in USB host mode is [here][3].

[Here][4] is a discussion (and reference to an alternative library) regarding using a Due to write files to a thumb drive.

Of course an adapter cable or a thumb drive with a physical connector matching the native USB port on the selected MCU is required. Both are commonly available.

See also https://arduino.stackexchange.com/questions/24177/can-the-arduino-interface-with-usb-devices-without-the-usb-host-shield

  [1]: https://forum.arduino.cc/t/how-to-tell-if-a-board-has-native-usb-support-for-a-midi-project-with-a-mac/667494
  [2]: https://www.arduino.cc/reference/en/libraries/usbhost/
  [3]: https://docs.arduino.cc/tutorials/portenta-h7/usb-host
  [4]: https://forum.arduino.cc/t/usb-host-due-support-for-mass-storage-devices-thumbdrives/635331


body:
After HW reset (button or power reconnect) I get the correct NTP shift, but when I use `ESP.restart()` via MQTT I get the correct time without 3 3 HRS shift due to Tz. What happens after SW reset that behaves in such manner and how to fix it?

    bool myIOT2::_startNTP(const char *ntpServer, const char *ntpServer2)
    {
     unsigned long startLoop = millis();
     while (!_NTP_updated() && (millis() - startLoop < 20000))
     {
    #if defined(ESP8266)
      configTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); // configuring time offset and an NTP server
    #elif defined(ESP32)
      configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
    #endif
      delay(1000);
     }
     if (!_NTP_updated())
     {
      return 0;
     }
     else
     {
      return 1;
     }
    }
    bool myIOT2::_NTP_updated()
    {
     return now() > 1640803233;
    }

title: ESP32, NTP and SW reset

Answers: 1

body:
Apparently, time in ESP32 survives a sw reset, while in ESP8266 doesn't.
So in code, which is same for both  - if clock is updated (a rough criteria that time is greater than some day in 2020 ), it skipped TZ update  `configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);`

So after a crash and/or sending a MQTT message to reboot, time was missing TZ update.

Hope it'll help someone.

Guy


body:
I'm working on a project with a Digispark ATTiny85, that performs keystrokes using the DigisparkKeyboard library (https://github.com/digistump/DigisparkArduinoIntegration/tree/master/libraries/DigisparkKeyboard). Besides the DigiKeyboard, I also import EEPROM.h.

My own code is only about 150 lines, I've cut down the size following a number of online guides, trying to avoid larger data types and so on. The Digispark is limited to ~6kB and the imported DigiKeyboard library takes up a little more that 5.4kB. In total the compiled project takes up about 7kB, which exceeds the boards capacity.

From the DigiKeyboard library I only use `DigiKeyboard.sendKeyStroke()` and `DigiKeyboard.print()` (with about only ten different characters). So I assume there is a lot of unused code I could remove, but I don't know how to approach this. I use Visual Studio Code and PlatformIO.

How could I reduce the size of the used DigisparkKeyboard library?

title: How to cut down size of imported DigiKeyboard library

Answers: 2

body:
The compiler/linker will remove unused functions/methods automatically, so I doubt you can save memory by removing unused functions/methods yourself.

However, you could possibly gain by:

- Removing the calls of check functions/methods when you know the result will be always `false`, `true`, or always the same number, string or data type in general.
- Removing (parts of) functions/methods which are related to physical or logical functionality you never use. Like e.g. `if`, `case` statements that will never apply).
- Prevent using an entire class (e.g. `String`) (see second comment of Emma Makes below).

body:
With input from @EdgarBonet, I looked into the functions used and it turned out that the `String()` function, I used once in my code, takes up about 3kB of space in the compiled program.

I ended up removing the line with `String()` and kept the imported DigiKeyboard library as it is.


body:
I wanted to use an SD shield on an Arduino Elegoo to make a typewriter (for saving files).

I put the shield on the Arduino Elegoo, then connected an LCD screen, then tried to power on using USB to computer, but my Arduino Elegoo wouldn't power on.

I tried to power it on with the external power supply, but it still wouldn't power on.

If I power it on without the shield it works perfectly fine, so why is my Arduino Elegoo not powering on?

[![the arduino elegoo with the sheild connected to the lcd screen][1]][1]

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

title: Why is my SD shield making my Arduino not power on?

Answers: 0


body:
I have a simple problem here. I use an ESP8266 WiFi module and an Arduino Uno r3.

What I want is to receive a serial message from the ESP8266 on the Arduino Uno.

Note: I set the upload speed of the ESP8266 to 9600.

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

    void loop() {
      Serial.write("hello friend");
      delay(2000);
    }

Arduino Uno:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); //rx, tx

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

    String message = "";
    boolean check = false;

    void loop() {
      Serial.println(mySerial.available());
      mySerial.println("hindi nagagana");
      while (mySerial.available() > 0) {
        Serial.println(mySerial.readString());
        check = true;
      }

      if (check == true) {
        Serial.println(message);
      }

      delay(200);
    }

Or any idea on how to control the Arduino Uno via the internet, such as a simple LED blink?

I used Firebase for databases an I plan to use ReactJs for webApp/Native App (nodeJs).

title: Why doesn't serial communication work on Arduino Uno r3 and ESP8266 WiFi module?

Answers: 1

body:
i think you should change `Serial.write()` to `Serial.print()` because `Serial.write()` is for send data as bytes or series of bytes and `Serial.print()` send as human-readable text.

Reference:

Serial.write()

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

Serial.print()

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

esp 8266 code:

    void setup()
    {
     Serial.begin(9600);
    }
    void loop(){
        Serial.print("hello friend");
        delay(2000);

     }


body:
I want to make LED blink patterns with multiple LEDs with the `millis()` function. I researched about it but did not find a perfect solution.

I found [one blog][1], but it is using a LED pin number array; I need a solution without an array. Any help will be appreciated.

  [1]: https://www.baldengineer.com/arduino-chasing-leds-with-millis.html

This is my code which I have written:

    const int Button_code_1 = 2;
    const int Button_code_2 = 3;
    const int Button_code_stop = 4;

    const int LED_one = 6;
    const int LED_two = 8;
    const int LED_three = 10;
    const int LED_four = 12;

    int buttonState_code_1 = 0;
    int buttonState_code_2 = 0;
    int buttonState_code_stop = 0;

    void setup() {
      // put your setup code here, to run once:

      Serial.begin(9600);

      pinMode(Button_code_1,INPUT);
      pinMode(Button_code_2,INPUT);
      pinMode(Button_code_stop,INPUT);

      pinMode(LED_Button_one,INPUT);
      pinMode(LED_Button_two,INPUT);
      pinMode(LED_Button_three,INPUT);
      pinMode(LED_Button_four,INPUT);

      pinMode(LED_one, OUTPUT);
      pinMode(LED_two, OUTPUT);
      pinMode(LED_three, OUTPUT);
      pinMode(LED_four, OUTPUT);
    }

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

      buttonState_code_1 = digitalRead(Button_code_1);
      Serial.println(buttonState_code_1);
      buttonState_code_2 = digitalRead(Button_code_2);
      Serial.println(buttonState_code_2);
      delay(1000);
      buttonState_code_stop = digitalRead(Button_code_stop);

      if(buttonState_code_1==1)
      {
        pattern_one();
      }
      if(buttonState_code_2==1)
      {
        pattern_two();
      }

    }

    void pattern_one()
    {
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, HIGH);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, LOW);
      delay(3000);
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, HIGH);
      delay(3000);
      digitalWrite(LED_one, HIGH);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, LOW);
      delay(3000);
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, HIGH);
      digitalWrite(LED_four, LOW);
      delay(3000);
    }

    void pattern_two()
    {
      digitalWrite(LED_one, HIGH);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, LOW);
      delay(3000);
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, HIGH);
      digitalWrite(LED_four, LOW);
      delay(3000);
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, HIGH);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, LOW);
      delay(3000);
      digitalWrite(LED_one, LOW);
      digitalWrite(LED_two, LOW);
      digitalWrite(LED_three, LOW);
      digitalWrite(LED_four, HIGH);
      delay(3000);
    }

This is my sample code with four LEDs. I have written this code with `delay()`, so when I want to change the pattern I can't because `delay()` is blocking the code.

I researched this and found the `millis()` function as the solution. How can I implement this code using the `millis()` function?

title: LED blink patterns with multiple LEDs with millis() not using Delay()

Answers: 1

body:
This is one of the effects for 3 (sets) of LEDs from [my light alarm clock sketch][1]:
```
void cycleEffect() {

  static unsigned long previousMillis;
  static uint8_t cycleCounter;

  if (millis() - previousMillis > 100) {
    previousMillis = millis();
    digitalWrite(LEDS_CENTRAL_PIN, cycleCounter == 0);
    digitalWrite(LEDS_LEFT_PIN, cycleCounter == 1);
    digitalWrite(LEDS_RIGHT_PIN, cycleCounter == 2);
    cycleCounter++;
    if (cycleCounter == 3) {
      cycleCounter = 0;
    }
  }
}
```

  [1]: https://github.com/JAndrassy/SunriseClock/blob/main/SunriseClock/SunriseClock.ino


body:
I'm trying to build a device for my startup IoT-related, using an A7672S.

Here is the code:

```c++
mySerial.println("AT+HTTPINIT";
checkresponse("OK\r\n");

mySerial.println("AT+HTTPPARA=\"URL\",\"http://" + host + resources + "\"");
checkresponse("OK\r\n");

mySerial.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
checkresponse("OK\r\n");

String st = "AT+HTTPDATA=";
int pdl = postdata.length();
st += String(pdl);
st += ",15000";
mySerial.println(st);
checkresponse("DOWNLOAD");

mySerial.println(postdata);
checkresponse("OK\r\n");

mySerial.println("AT+HTTPACTION=1");
checkresponse("+HTTPACTION: 1,200");

if (BuildINString2.indexOf("+HTTPACTION: 1,200") != -1) {
  Serial.println("POST DONE");
} else
  Serial.print("ERROR POST: ");
  Serial.println(BuildINString2);
}

mySerial.println("AT+HTTPTERM");
checkresponse("OK\r\n");

// In the check function, we pass the check variable to check different possible responses of sim like ok, error, etc

void checkresponse(String check) {
  int start = millis();
  BuildINString2="";
  while (true) {
    if (mySerial.available() > 0) {
      inData =mySerial.read();
      BuildINString2 = BuildINString2 + char(inData);
    }

    if (BuildINString2.indexOf(check)! = -1) {
      delay(100);
      return;
    }

    if (millis()-start > 3000) {
      delay(100);
      Serial.println("SIM TIMEOUT");
      return;
    }
  }
}
```

How can we speed up the POST time? Because in my last module (SIM7600), I used CHTTPACTION which was POSTing in less than 500 ms, but on the A7672s, it's taking more than 1 s.

Can someone confirm possible issues or any other method for the fast posting of data?

Also, in this HTTP method, is HTTPTERM required for every POST or change in URL point or when it's required?

title: HTTP POST maximum speed at command SIMCom A7672

Answers: 0


body:
I'm trying to understand how to read/write [a UID struct from miguelbalboa](https://github.com/miguelbalboa/rfid/blob/master/src/MFRC522.h#L255) to EEPROM to persist a card ID across system restarts on my ESP32-S3 through the Arduino IDE. I expected Put/Get/Read to be symmetrical but can't seem to prove that. Here's my test program:

```
/**
 * This is a simple script to experiment with reading and writing MFRC522::Uid
 * structures to eeprom.
 */

#include <MFRC522.h>
#include <EEPROM.h>

#define UID_EEPROM_LOCATION 0
#define EEPROM_SIZE 256

void setup() {

  Serial.begin(115200);   // Initialize serial communications with the PC
  Serial.println("Serial started.");
  EEPROM.begin(EEPROM_SIZE);
  Serial.print("EEPROM started ");
  Serial.println(EEPROM_SIZE);
  printBytesFromEeprom();
  MFRC522::Uid uidToWrite = {
    0x04,
    {B00000000, B10000000, B11100000, B01100000},
    0
  };
  Serial.print("UID Before Write: ");
  printUid(&(uidToWrite));
  storeUidInEeprom(&(uidToWrite));
  printBytesFromEeprom();
  Serial.println("UID was put.");
  MFRC522::Uid uidFromRead;
  readUidFromEeprom(&(uidFromRead));
  printBytesFromEeprom();
  Serial.print("UID from Read: ");
  printUid(&(uidFromRead));
}

void loop() {
}

void printUid(MFRC522::Uid *uid) {
  Serial.print(uid->size, HEX);
  Serial.print(F(" byte card UID:"));
  for (byte i = 0; i < uid->size; i++) {
    if(uid->uidByte[i] < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(uid->uidByte[i], HEX);
  }
  Serial.println();
}

void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}

void storeUidInEeprom(MFRC522::Uid *uid) {
  EEPROM.put(UID_EEPROM_LOCATION, uid);
  EEPROM.commit();
  delay(1000);
}

void printBytesFromEeprom() {
  Serial.print("256 bytes from EEPROM: ");
  for (int i = 0; i < 256; i++) {
    byte myByte = EEPROM.read(UID_EEPROM_LOCATION + i);
    if(myByte < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(myByte, HEX);
  }
  Serial.println();
}
```

I'm an experienced Java developer, but new to C++. I could have made any number of basic errors.

When I run the above on my ESP32-S3-DevKitC-1, I get the following output:

```
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3fcd0108,len:0x43c
load:0x403b6000,len:0xbd0
load:0x403ba000,len:0x29c8
entry 0x403b61d8
Serial started.
EEPROM started 256
256 bytes from EEPROM:  E4 2C CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID Before Write: 4 byte card UID: 00 80 E0 60
256 bytes from EEPROM:  94 2D CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID was put.
256 bytes from EEPROM:  94 2D CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID from Read: C0 byte card UID: 79 CD 3F 00 00 00 00 00 00 00 00 0C FA 3B C7 00 00 00 00 04 00 00 00 4C 2F CE 3F 01 00 00 80 00 00 00 00 F0 2D CE 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2E CE 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
```

There are two unexpected things from this output:

* The output of `readUidFromEeprom()` is different than the input to `storeUidInEeprom()`

Any help would be welcome!

title: Arduino IDE EEPROM put() then read() returns different data on ESP32

Answers: 3

body:
Well...

I still don't know why the above wasn't working. But if I switch to my own byte encoding in EEPROM (the obvious one that I assumed `put()` used, then I get the right behavior:

```
/**
 * This is a simple script to experiment with reading and writing MFRC522::Uid
 * structures to eeprom.
 */

#include <MFRC522.h>
#include <EEPROM.h>

#define UID_EEPROM_LOCATION 0
#define EEPROM_SIZE 256

void setup() {

  Serial.begin(115200);   // Initialize serial communications with the PC
  Serial.println("Serial started.");
  EEPROM.begin(EEPROM_SIZE);
  Serial.print("EEPROM started ");
  Serial.println(EEPROM_SIZE);
  printBytesFromEeprom();
  MFRC522::Uid uidToWrite = {
    0x04,
    {B00000000, B10000000, B11100000, B01100000},
    0
  };
  Serial.print("UID Before Write: ");
  printUid(&(uidToWrite));
  storeUidInEeprom(&(uidToWrite));
  printBytesFromEeprom();
  Serial.println("UID was put.");
  MFRC522::Uid uidFromRead;
  readUidFromEeprom(&(uidFromRead));
  printBytesFromEeprom();
  Serial.print("UID from Read: ");
  printUid(&(uidFromRead));
}

void loop() {
}

void printUid(MFRC522::Uid *uid) {
  Serial.print(uid->size, HEX);
  Serial.print(F(" byte card UID:"));
  for (byte i = 0; i < uid->size; i++) {
    if(uid->uidByte[i] < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(uid->uidByte[i], HEX);
  }
  Serial.println();
}

void readUidFromEeprom(MFRC522::Uid* result) {
  byte uidSize = EEPROM.read(UID_EEPROM_LOCATION);
  for (byte i = 0; i < uidSize; i++) {
    result->uidByte[i] = EEPROM.read(UID_EEPROM_LOCATION + 1 + i);
  }
  byte uidSak = EEPROM.read(UID_EEPROM_LOCATION + 2 + uidSize);
  result->size = uidSize;
  result->sak = uidSak;
}

void storeUidInEeprom(MFRC522::Uid *uid) {
  EEPROM.write(UID_EEPROM_LOCATION, uid->size);
  for (byte i = 0; i < uid->size; i++) {
    EEPROM.write(UID_EEPROM_LOCATION + 1 + i, uid->uidByte[i]);
  }
  EEPROM.write(UID_EEPROM_LOCATION + 2 + uid->size, uid->sak);
  EEPROM.commit();
}

void printBytesFromEeprom() {
  Serial.print("256 bytes from EEPROM: ");
  for (int i = 0; i < 256; i++) {
    byte myByte = EEPROM.read(UID_EEPROM_LOCATION + i);
    if(myByte < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(myByte, HEX);
  }
  Serial.println();
}
```

And output as expected is:

```
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3fcd0108,len:0x43c
load:0x403b6000,len:0xbd0
load:0x403ba000,len:0x29c8
entry 0x403b61d8
Serial started.
EEPROM started 256
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID Before Write: 4 byte card UID: 00 80 E0 60
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID was put.
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID from Read: 4 byte card UID: 00 80 E0 60

```

body:
You wrote:

```c++
void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}
```

The `EEPROM.get()` method expects a _reference_ to the variable you are
setting. Here, you are providing a _pointer_ instead. The outcome is
that this call is updating the `result` local variable (the pointer),
rather than the memory region pointed by it.

You may try this:

```c++
void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, *result);  // notice the `*' operator
  delay(1000);
}
```

Same thing for `EEPROM.put()`.

**Edit**: As suggested by Juraj in a comment, it can make more sense to
have `readUidFromEeprom()` accept a reference rather than a pointer:

```c++
void readUidFromEeprom(MFRC522::Uid &result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}
```

But then you have to also change the caller:

```c++
readUidFromEeprom(uidFromRead);
```

body:
On the ESP23 platform, consider using the Preferences library. EEPROM in arduino-esp32 is emulated using the Preferences library. Might mess up the calls to MFRC522 lib though.

Preferences docs include the API and tutorial.


body:
I am testing out pyFirmata. I have a 360° servo, and know how to change its direction, but I dont't know how to stop it.

What command, like `servo.write()`, would work to make it stop moving until prompted to move again?

title: Using pyFirmata with a 360° servo; how do I stop it?

Answers: 1

body:
You'll need to check datasheets for your servos but a PWM value of 1500 microseconds would generally be near neutral / no rotation. Decreasing values less than this should generate increasing speed clockwise. Increasing values greater than neutral should generate increasing speed counter clockwise.

See https://arduino.stackexchange.com/a/88650/71575


body:
The datasheet for the ATmega328P contains this table, which describes bits 4 and 5 of EECR:

EEPM1 | EEPM0 | Programming Time | Operation
------|-------|------------------|----------
0     | 0     | 3.4ms            | Erase and write in one operation (atomic operation)
0     | 1     | 1.8ms            | Erase only
1     | 0     | 1.8ms            | Write only

I'm currently working on some non-blocking EEPROM-handling code and I'm wondering when and how I should erase the EEPROM.
- What does erasing do? Does it set one byte to 0x0, or the entire EEPROM?
- Should I erase it first whenever I want to write a byte?
  - If not, why is there an option to erase and write separately?
- How do I initiate an erase?

Either the datasheet is rather lacking concerning the EEPROM, or I'm just not finding what I'm looking for. I tried using a search engine, but all results are either about the Arduino EEPROM library or \<avr/eeprom.h>, both of which use polling instead of interrupts (and are therefore blocking).

title: How does erasing the EEPROM work?

Answers: 2

body:
Your questions are answered in [the AVR ATMega328 datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf).

The procedure for erasing and writing the internal EEPROM is outlined in chapter 7.6 (Register Description).

 - The Erase operation erases 1 byte (erasing an EEPROM cell sets it to all 1s, i.e. 0xff).
 - The EEPROM address to be erased/programmed is pointed to by the EEARL and EEARH registers. The value to be programmed into that address is set by the EEDR. Reading a value from EEPROM returns the value in the same EEDR register.
 - Before writing a new value to the EEPROM, the old value must first be erased. You can do that as two separate actions or one single action. You could also leave the cell deprogrammed (erased) by only erasing it and not programming it again.
 - You initiate an erase of the EEPROM address pointed to by EEARH/EEARL, by setting EEPM1 to 1, EEPM0 to 0 and setting EEPE to 1 to start the erase operation. Setting EEPM1 and EEPM0 both to 0 will erase and program a new byte in a single operation.

As for making EEPROM writes non-blocking, you could set a (non-blocking) timer for the duration of the write, erase or erase/write operation. According to the datasheet these operations respectively take 1.8, 1.8 and 3.4 ms. Just make sure your code does not access the EEPROM while these operations are taking place.

You could also (non-blocking) periodically poll the EEPE bit until it is cleared, signalling the operation is finished.

The most elegant way, i.m.o. is to make use of the EERIE flag by setting it to 1, which will enable the ATmega to generate an interrupt when the EEPROM operation is finished.

body: I switched to FRAM, 32K x 8 can be gotten for just a few $$$, generally less the imported Arduinos. It is as fast as the Arduino can access it, both read and write. You can use I2C or SPI depending on which unit you buy. There are some very nice libraries for it making it easy to use. It is non volatile, ie does not lost information when power fails. It will support in the range of a trillion memory cycles with no delay when writing or reading it so no blocking. Just a few extra processor cycles because of the SPI or I2C overhead. If you have code already written for the External EEPROM it should work as is but it will have an unneeded delay in it.


body:
On a small project, I have a DS3231 RTC module and a LCD I2C module that I'm trying to connect on a Arduino Pro Mini board. However, both the RTC and LCD require connecting the `SDA` and `SCL` to the pins `A4` and `A5` respectively.

The libraries do not seem to allow changing the connected pins. Why is that? I have other pins available, like `A6` and `A7`, can those be used?

title: How can I use a LCD I2C and a RTC3231 on a Arduino Pro Mini?

Answers: 1

body:
Welcome, I understand where you are coming from, without a background you do not know what to ask. Were were all where you are at one time. I hope this helps.  You need to do some studying on the I2C bus, online tutorials will make it easy. You you will find you can connect over 100 devices to it at one time The SCL and SDA lines go from module to module. Note each module has its own address, sometimes they are selectable. Some modules have pull up resistors, others do not. To keep it interesting the pull up resistors are mostly 10K but that is not a constant.

There are loading rules etc to be careful of if you have long wires or maybe more than three units. You need to add pull ups to each of the two lines (example: 4.7K from SCL to +5) or use something in the 3K range for a 3V3 system. The reason is because the bus has both dominant and recessive states where the recessive is high which the resistor provides. The SCL and SDA output/input on the parts have open collector/open drain outputs so they cannot source anything.

Once you have it hooked up you need to run a program called I2C scan or something like that. If you have wired it correctly it will give you the address of the module, you will probably get two or three as there is the RTC, Memory device and possible a temperature sensor.

The #1 rule is the Arduino A Power Supply it is NOT! A small module or two connected to the 5V out is fine but never connect a motor directly to any arduino you will probably fry the Arduino.

I use Vin and supply it with about 8 volts by using either a Buck or Sepic converter from a 12V 2A or larger supply. I do it this way because I get a more stable voltage on the Arduino because of the extra filtering etc built into the analog regulator section. Real nice when using the A/D, keeps things stable. Were here to help, ask questions any time and do not worry is some over eager person decides to vote you down. Read the guidelines etc and  you will do great.

You can search online for "Arduino RTC" and find a lot of programs with software.