text:
LCD TFT 2.4"" changes the values of analog read of Arduino Mega
I have a Arduino Mega with LCD TFT 2.4"" with reading 5v signal on A8 pin (Arduino mega pin) from a raspberry pi (just to test). They are grounded together. When the Arduino is without the LCD, the analog reading works fine (4.8V,same from multimeter). But when I assembly the LCD, even if I just assembly VCC and ground, the analog read increasce around of 0.2V measure. I already tried to change the voltage input with a potentiometer and I still receiving a measure error of 0.2V.  External energy supply to the LCD makes the things works, but I wouldn't like to have a external supply just to the screen.
What I'm doing wrong or what I can do ?

Measure the Arduino's 5V pin with the LCD attached. I'll bet it no longer measures 5V...

Yeah, without the LCD attached i got a 4.95V. When I attach the LCD the Arduino's goes to 4.85V

MCUFriend went through a number of revisions of the same 2.4" TFT shield over time. I guess it depended on what TFT screens they could get hold of cheapest at any given moment. I have two versions here, neither of which are the same as yours. Both have their own voltage regulator onboard for the 3.3V power (which yours doesn't). Both of them also have resistors present on the cathode of the back light - which yours doesn't.
I would imagine for this revision they mistakenly though the TFT screen's back light didn't require any current limiting resistors and omitted them, with the end result that connecting the TFT screen to the Arduino drags down the 5V voltage to that of the combined forward voltage of the LEDs in the back light circuit.
In short: your TFT screen is designed badly. Fixing it would require modifying the shield on a trace-level basis. Not easy.

Yeah, It make sense. I was expecting that. Which lcd Tft do you recommend me ?

@GabrielLincoln They're all pretty much of a muchness. Look for one with a few more components on it than just some IO buffers. Personally I design and build my own direcly into products instead of using shields, but I do have a large collection here for when I was developing a big display library system. If you see a "resistor array" on the images of the TFT it's a pretty safe bet it's good.

The short answer is to beef up your power supply:

Don't use small batteries or power supplies.  For instance use D Size Cells instead of 9 Volt Cells.  Or use a 3 Amp power supply instead of a 100mAmp power supply.

The longer answer:

Make sure you have mitigated any power problems.  Like long or thin power lines.  Long or thin wires have more resistance.  And the more current you pull over that resistance the less voltage you will have at the far end.  Remember it follows the rule:
Voltage = Resistance * Current

Probably the best answer:

Check the ADC specification of the processor and make sure your voltage reference is not adversely affected by power fluctuations.  Some processors, like most used on Arduinos, have the ability to switch between internal references and external references.  Most designers who really need a good ADC response will design an external reference and instruct the processor to use the external over the internal reference.  For most Arduinos the function to call to switch references is "analogReference()".  You can read more about this command and external references here.


text:
SPI problem with Bitcraze PMW3901 sensors and Arduino NANO
I am currently trying to connect four Bitcraze PMW3901 sensors to an Arduino NANO, but I seem to have issues with the SPI. When I connect two sensors using the code below, it works perfectly: I am able to retrieve the X and Y data from the serial port for both sensors.
include "Bitcraze_PMW3901.h"

 Bitcraze_PMW3901 flow(10);
 Bitcraze_PMW3901 flow2(9);

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

  if (!flow.begin()) {
    Serial.println("Initialization of the flow sensor 1 failed");
    while(1) { }
  }

  if (!flow2.begin()) {
    Serial.println("Initialization of the flow sensor 2 failed");
    while(1) { }
  }

}

int i =0;
int16_t deltaX,deltaY;
int16_t deltaX2,deltaY2;

void loop() {
  if ((i % 2) == 0) {
    digitalWrite(10, LOW); // sets the digital pin 10 on
    flow.readMotionCount(&deltaX, &deltaY);
    digitalWrite(10, HIGH);  // sets the digital pin 9 off
  }

  if ((i % 2) == 1) {
    digitalWrite(9, LOW); // sets the digital pin 10 on
    flow2.readMotionCount(&deltaX2, &deltaY2);
    digitalWrite(9, HIGH);  // sets the digital pin 9 off
  }

    i = i + 1;
    Serial.print("X1:");
    Serial.print(deltaX);
    Serial.print("\t");
    Serial.print("Y1:");
    Serial.print(deltaY);
    Serial.print("\t");
    Serial.print("X2: ");
    Serial.print(deltaX2);
    Serial.print("\t");
    Serial.print("Y2:");
    Serial.print(deltaY2);
    Serial.print("\n");

}

However, when I try to add a third Bitcraze PMW3901 sensor I cannot seem to be able to initilize it. Still, I declare a separete SS as

Bitcraze_PMW3901 flow3(6);

and add the initialization code in the setup() function as follows

if (!flow3.begin()) {
Serial.println("Initialization of the flow sensor 3 failed");
while(1) { }
}

What I get is the sentence "Initialization of the flow sensor 3 failed" or "Initialization of the flow sensor 1 failed" (it depends and I don't really understand why, since the code is always the same) printed on the serial port window.
I have already checked my sensors: they all work separetely and two-by-two. Do you have any suggestions? I hope I have managed to explain the problem clearly, otherwise please let me know if I can add or specify something more. Thank you in advance for your help!

powering issue? how do you power the sensors?

Do your sensors incorporate a tri-state buffer on the MISO line for each device?

Hi Juraj! I power the sensors directly through the Arduino Nano. I have already tried to use an external battery, but the result didn't change so I don't think that is the issue.

Hi sempaiscuba! I actually don't know and I can't seem to find this information on the sensors' datasheet. Could you please explain what would be the problem or the advantage of that? Thanks in advance!

Most SPI chips will be at tri-state on their MISO pin when their chip select signal is HIGH. Tri-stage means that it is neither HIGH nor LOW (i.e. floated) and effectively disconnect. However, it is not always the case. A SPI device without tri-state MISO could caused potential problem on a SPI bus where multiple SPI devices are connected. If the MISO is unable to be at tri-state, it will be either HIGH or LOW, this will affect other devices connected on the same bus in receiving data. see this for more explanation and solution.

It seems that the library is set to running the SPI at 4MHz, this might be a problem when running with multiple slaves, you might want to try to change the library manually to say 1MHz and see if it works?

Hi, I am facing the same issue with the pmw3901 sensors when connected to teensy 4.0
@wolly94 were you able to solve your problem? If yes, please could you mention the changes you made?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Servos "jump to fixed position" at startup when powered by external power supply only, but not by board
My question is about something that is happening ONLY when I use external power supply. When I use the power from the Arduino Mega directly, there is no problem. However, I need to use an external power supply, because I need to drive 42 servos. I believe this is related to the Arduino and external power supply not being powered on at exactly the same time, which is rather difficult given that the Arduino has some boot-up time.
When I connect a single 1 of these servos to any Arduino board directly (I have tried multiple boards), everything works as expected, in the sense that when I kill power to the Arduino, the servo stops, and when restarted, the program runs again and the servo continues working from the exact same position as when stopped. There is no default or initial sentinel value that the servo "jumps" to. Here is the sketch of this circuit working just fine w/ 1 servo:

However, when I connect an external power supply this setup even with a single servo, the servo "jumps" immediately to position ~90 (which would be the middle given that it has a 0-180 range). I need external power for my real project because I have 42 such servos that I am driving. After this initial "jump to position", the Arduino program continues as normal and all 42 servos are working as expected. But this "jump to position" is very disruptive! There are various parts connected to these servos. When I power up the system, the whole thing jumps to position immediately sometimes causing some damage to the system that I have to repair manually. It is extremely painful to watch 42 servos snap to position so quickly and so much of the system move so fast as a result.
I believe this has something to do with the control wires still connected to the Arduino, but the power and ground connected to the external power supply. So if the entire system (both Arduino and external power supply) is not powered on at exactly the time, then the servos are getting power without control or control without power and the incoming voltage sets them to some initial position, either by design or by undefined behavior.
But I don't know how to wire a circuit that allows the external power exactly after the pins have been attached to the servos in the setup() function of the Arduino program, so the servos have control and power at the same time... Should I be trying to do this? How can I make sure all these servos and their control pins are all powered and attached at the same time?
Here is a rough wiring diagram of my system with only 1 servo (problem still exists):

I am using an Arduino Mega 2560 (I think rev3).
Here is the external power supply (5V 30A DC):
https://www.amazon.com/dp/B01HJA3OUG

Here are the servos:
https://www.adafruit.com/product/169
I am using the Arduino Servo library, which does work w/ these servos and my board.
I used appropriate gauge wire for the DC amperage to drive these servos. They all seem to have enough power to run after this initial "jump to position". But I really want to avoid this!
UPDATE 10/7:
I put this delay in the setup() function to give me time to plug in the external power supply at a specific point after bootup:
  // LONG DELAY WAITING FOR EXTERNAL POWER TO BE APPLIED; LED blink
  pinMode(LED_BUILTIN, OUTPUT);
  start = curr = millis();
  while (curr - start <= 10000)
  {
    curr = millis();
    if (curr - prev >= 1000)
    {
      prev = curr;
      if (state == LOW)
        state = HIGH;
      else
        state = LOW;
    }
    digitalWrite(LED_BUILTIN, state);
  }

If I put this code after the calls to attach the servo pins (i.e. servo1.attach(1), then the jump happens immediately when I plug external power supply in. If I put this code before the servos are attached, then there is no jump at first when external power supply is plugged in, but then immediately after the delay code above finishes. This tells me that the jump is happening when the control wires are attached (i.e. servo1.attach(1) is called). However, this still doesn't give me any solution... If external power supply is applied either before or after when the servo control pins are connected, it jumps!
Why do these servos NOT jump when connected w/ power from the board, but jump when connected w/ external power supply?!
This must mean that either the actual amount of external power supplied to these servos is different than the Arduino is supplying (and thus causing different behavior) or it's the fact that the power ground and control pins are not all connected at the exact same time (and thus causing different behavior).

maybe in first case, program is already running when servo gets its signal, in second case it is bypassed by power, test it without the signal 'yellow' wire in both wiring to check if it the case, if yes it is just that, if not ... I don't know

remove the arduino from the equation completely ... do an experiment ... set servo to 45 degrees before each test ... apply power to the servo with the control line disconnected --- what happens? ... do same with control line grounded --- what happens? ... do same with control line pulled high --- what happens?

your question is not about the arduino until you determine a way to stop the servo from resetting at powerup

@jsotola I will do this experiment tomorrow, but my gut feeling is this: if power is applied before Arduino program's Servos attach() the pins, then it jumps. However, if I wait for the program to boot-up, then I don't know when I can attach power in time for the program to run. I tried putting a 10 second "startup" delay, but it didn't seem to work as expected. Perhaps I put it before the pins were attached, not after... I will try all of this tomorrow. Thank you.

@jsotola I agree w/ you 100%, but I was hoping my post might be familiar to someone on here... I'm sure there are many people who have powered a handful or more of servos from an external power supply, and so might be familiar with this idea of control and power on circuits that start at different times.

you may have to programmatically switch the power to the servos ... test the idea by using a manual switch, or attaching the servo +V wire after the arduino is running

@jsotola Updated. If you have any ideas, just let me know. Thx

@francoisP Updated. If you have any ideas, just let me know. Thx

You could try to add a pulldown to the control line. The problem could be that the servo gets an "undefined" voltage before the arduino powers up and takes control (pin gets configured as output).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
RTC DS3231 always remember the old time
I try to change time on windows to test my programing condition but RTC usually keep old time when i change time on windows and re-upload the code . I'm also removing the battery  and cut the power it is still not working.
here is my set up and library is https://github.com/adafruit/RTClib
void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);
   Serial.println("ESP start...");
  pinMode(Ledpin, OUTPUT);
  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, HIGH);

  delay(3000); // wait for console opening

if (! rtc.begin()) {
  Serial.println("Couldn't find RTC");
 while (1);
}

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

}

Does it print “RTC lost power, lets set the time!”?

Thanks.  I hadn't seen the rtc.adjust(DateTime(F(__DATE__),F(__TIME__))); construction, which uses the DateTime(char*,char*) routine from  https://github.com/adafruit/RTClib/blob/4ece412b89ed3b72093174d19b50afcf8ed6c6a8/src/RTClib.cpp#L281 and the C environment variables __DATE__, __TIME__  -- Rather than re-upload the code, you might need to re-compile to code to update the time encoded in the binary file.


text:
Adding an Interrupt to ATtiny45 with Arduino
I recently wrote a simple script to...we'll say, "flash some LED's" and uploaded it to an attiny45. In short, the script cycles through 3 LED's and turns them on for a specified frequency, in a specified direction. With a button, I can cycle through different modes. There are 7 modes (default (LED's OFF), then 3 different speeds forwards and 3 different speeds backwards).
The script works fine-ish, however I've noticed that in order to read from the button input properly, the function that turns the LED's ON and OFF must be completed, meaning that for the longer cycles, the user may have to hold the button until the function completes. This is further complicated during the shorter cycles, where the input may detect multiple button-presses (despite adding a delay following the digital read.
NOTE: I could just make the delay longer, but this doesn't fix the issue during lower frequencies, when the function may take multiple seconds to complete.
I feel the best way to sort this (though I'd be open to other ideas) is to use the attachInterrupt() function; however, it doesn't work. The button no longer works and I'm not sure why.
// Pin Variables
int led1 = 2;
int led2 = 3;
int led3 = 4;
int leds[] = {led1, led2, led3};
int modePin = 0; // (physical pin 5 on the IC)

// Mode Speeds and setting
int fastTime = 100;
int mediumTime = 300;
int slowTime = 1000;
int offTime = 100;
int mode = 0;

void setup() {
  for (int i=0; i<3; i++){
    pinMode(leds[i], OUTPUT);
    digitalWrite(leds[i], LOW);
  }
  attachInterrupt(modePin, callMode, RISING);
}

void loop() {
  // If we get here, reset and go back to default (all LED's OFF)
  if (mode >= 7) {
    mode = 0;
  }
}

void callMode(){
  ++mode;
  //TIME: 1000, 300, 100 (milliseconds)
   switch (mode) {
     case 0:
       // Default, OFF
       for (int i=0; i<3; i++){
         digitalWrite(leds[i], LOW);
       }
       break;
     case 1:
       // Forward, Fast
       ledMode(fastTime, offTime, true);
       break;
     case 2:
       // Forward, Medium
       ledMode(mediumTime, offTime, true);
       break;
     case 3:
       // Forward, Slow
       ledMode(slowTime, offTime, true);
       break;
     case 4:
       // Backwards, Fast
       ledMode(fastTime, offTime, false);
       break;
     case 5:
       // Backwards, Medium
       ledMode(mediumTime, offTime, false);
       break;
     case 6:
       // Backwards, Slow
       ledMode(slowTime, offTime, false);
       break;
     case 7:
       // Return to Zero
       for (int i=0; i<3; i++){
          digitalWrite(leds[i], LOW);
       }
       mode = 0;
       break;
   }
}

void ledMode(int onTime, int offTime, bool forward){
  if (forward) {
    for (int i = 0; i <= 2; i++) {
      digitalWrite(leds[i], HIGH);
      delay(onTime);
      digitalWrite(leds[i], LOW);
      delay(offTime);
    }
  }
  else {
    for (int i = 2; i >= 0; i--) {
      digitalWrite(leds[i], HIGH);
      delay(onTime);
      digitalWrite(leds[i], LOW);
      delay(offTime);
    }
  }
}

NOTE: callMode() and ledMode() are only split up into different functions because I know that the function passed to attachInterrupt() cannot contain any delays(). So each time the button is pressed, the mode variable should increment and then the switch-statement should cause the next mode to run. When we reach 7, let's reset to zero and enter the default/OFF mode.
I've been racking my head for a few days on this and not sure what the problem is. Perhaps I can only use the attachInterrupt() function to some other pin? Perhaps I'm not using that function correctly?
Thank you in advance for any and all help you can provide.
-Joe

Re “I know that the function passed to attachInterrupt() cannot contain any delays()”: you should not call delay() from interrupt context. Whether delay() is called directly by the interrupt handler or indirectly through another function makes no difference. 2. Did you try the Blink Without Delay approach?

use callMode() to set a flag, such as nextSeq = true; ... in ledMode(), check for flag ... if (nextSeq)

@EdgarBonet I think that would be doable with a single LED, but not when I'm cycling through 3 of them. I'm attempting to adopt it now, but it's definitely proving to be tricky, to say the least

Interrupts are overkill for this kind of ultra-slow problems, and they
can introduce some extra complexity. Here the best solution seems (to me
at least) to lie in the approach of the Blink Without Delay
Arduino tutorial. Obviously, it must be adapted. In that tutorial, the
system switches between only two states (LED off or on). Here the
cycling of the LEDs goes through six phases:

all LEDs are off
LED[0] is on
all LEDs are off
LED[1] is on
all LEDs are off
LED[2] is on

The basic algorithm is the same: when millis() tells us it is time to
move to the next phase, we do so and update the state of the LEDs.
Note that I numbered the phases in such a way that the last bit
(phase&1) tells us whether an LED is on, and in that case the
remaining bits (phase>>1) hold the index of the LED that is on.
Here is how to cycle the LEDs at a fixed speed:
if (millis() - last_change >= phase_time) {
    last_change += phase_time;

    /* If an LED is on, turn it off. */
    if (phase & 1)
        digitalWrite(leds[phase >> 1], LOW);

    /* Move to the next phase. */
    if (++phase >= 6) phase = 0;

    /* Turn on the LED if needed. */
    if (phase & 1)
        digitalWrite(leds[phase >> 1], HIGH);
}

On top of this you need a finite state machine that cycles
between the different modes (speeds and directions). In order to avoid
code repetition, I would split this mode into a “state” that can OFF,
FORWARD or BACKWARDS, and an index into an array of delay times (with 0,
1, 2 meaning fast, medium and slow, respectively).
Putting it all together (warning: not tested):
const uint8_t leds[] = { 2, 3, 4 };
const uint32_t times[] = { 100, 300, 1000 };

void setup() {
    for (int i = 0; i < 3; i++)
        pinMode(leds[i], OUTPUT);
}

enum { OFF, FORWARD, BACKWARDS } state = OFF;  // global state
uint8_t time_idx;      // index in times[] (0 = fast)
int8_t phase;          // 0 = all off, 1 = led[0] on, 2 = all off...
uint32_t last_change;  // last time the phase changed

void loop() {

    /* Change mode on button press. */
    if (button_pressed()) {
        if (state == OFF) {
            state = FORWARD;
            time_idx = 0;  // start fast
        } else {
            time_idx++;    // slow down
            if (time_idx >= 3) {  // change direction or stop
                time_idx = 0;
                if (state == FORWARD)
                    state = BACKWARDS;
                else              // state is BACKWARDS
                    state = OFF;
            }
        }
    }

    /* Cycle the LEDs. */
    if (state != OFF && millis() - last_change >= times[time_idx]) {
        last_change += times[time_idx];

        /* If an LED is on, turn it off. */
        if (phase & 1)
            digitalWrite(leds[phase >> 1], LOW);

        /* Move to the next phase. */
        if (state == FORWARD) {
            if (++phase >= 6) phase = 0;
        } else {  // BACKWARDS
            if (--phase < 0) phase = 5;
        }

        /* Turn on the LED if needed. */
        if (phase & 1)
            digitalWrite(leds[phase >> 1], HIGH);
    }
}

I did not write the button_pressed() function, which is meant to
debounce the button and detect the “just pressed” transition. It is left
as an exercise to the reader (or you can just use a debouncing
library).

Thank you so much for your feedback! Just to close the loop here, I was about to implement this on my project, but then I had another idea. I reverted back to an older pre-interrupt version of the firmware and following a button-press, I simply added a 4-second delay. This requires the user to press-&-hold the button until a press is detected (never more than the length of the current cycle), but works fairly well for this purpose. In all cases, the user presses until the LED's stop and then releases. Works like a charm. Talk about a simple solution.


text:
Fail upload sketches to ESP8266 only on Ubunto 20.04.3
I installed a fresh copy of Ubuntu 20.04, and Arduino IDE1.8.16. At the beginning adding user to dialout group enabled uploading sketch to Aruino AVR family, and ESP32, but still ESP8266 gives this error:
Sketch uses 260889 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27980 bytes (34%) of dynamic memory, leaving 53940 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port /dev/ttyUSB0
Connecting........_____....._____....._____....._____....._____....._____....._____
Traceback (most recent call last):
  File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/upload.py", line 66, in <module>
    esptool.main(cmdline)
  File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool/esptool.py", line 3552, in main
    esp.connect(args.before, args.connect_attempts)
  File "/home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/esptool/esptool.py", line 529, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

So I tried to erase flash using esptool.py :
guy@desktop:~$ esptool --chip  auto --port /dev/ttyUSB0 erase_flash
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting........_____....._____....._____....._____....._____....._____....._____

A fatal error occurred: Failed to connect to Espressif device: Timed out waiting for packet header

Since AVR's and ESP32 work properly using USB's and ACM's I can guess that is is not a problem with the ability to access serial comm.
What might it be ?

There is something wrong with some new kernels of Ubuntu 20.04 LTS, interfering with ESP8266 core uploading process
5.4.0-88-generic #99-Ubuntu SMP Thu Sep 23 17:29:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
I had the same issue and downgraded the kernel to
5.4.0-86-generic #97-Ubuntu SMP Fri Sep 17 19:19:40 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
solved the issue

The issue happens to ESP8266 core uploading process, with the following tested Ubuntu cores

linux-5.11.0-37-generic
linux-5.4.0-89-generic
linux-5.4.0-88-generic

and tested OK with

linux-5.11.0-38-generic
linux-5.11.0-36-generic
linux-5.8.0-48-generic
linux-5.4.0-90-generic
linux-5.4.0-86-generic

Temporarily fix
To temporarily fix the issue by using working kernel, e.g. linux-5.4.0-86-generic
A. Select from GNU GRUB boot menu

Advanced options for Ubuntu

Ubuntu, with Linux 5.4.0-86-generic

If you don't have that kernel, install by

sudo apt install linux-image-5.4.0-86-generic

Reboot and select 5.4.0-86-generic from GNU GRUB boot menu

To save the selected GRUB settings
More info GRUB Simple-configuration

Edit /etc/default/grub by

$ sudo gedit /etc/default/grub

Add to the file

 GRUB_DEFAULT=saved
 GRUB_SAVEDEFAULT=true

Activate the change so that last selected value is used for the next boot.

$ sudo update-grub

Update
Just testing OK with latest kernel

linux-5.11.0-38-generic
linux-5.4.0-90-generic

It seems recent kernel release has fixed the issue


text:
Using L298n motor driver without jumper (Voltage Regulator)
When I am using 9V supply with motor driver and Jumper connected so the red LED was blinking but when I did the same using 9V and 15V supply removing the jumper LED didn't blink.
Neither the voltage nor the current drop across the motor was observed. And I didn't found any documentation for using L298n using without a jumper.

You need to provide a link to that specific driver board. The L298N is only the H-bridge chip on it. The circuit around it (including the jumpers and headers) is specific to that board. Please include that link in your question (by editing it)

The jumper controls whether or not the on-board 5V regulator is used to power the on-board logic. With the jumper removed the board needs an external 5V supply in addition to the motor power supply.

Is your Arduino ground connected to the 15V power supply ground?


text:
why is my arduino stuck on uploading?
my arduino for the playground adafruit express gets stuck uploading, and is saying that it is not recognizing the ports. <Arduino: 1.8.16 (Windows Store 1.8.51.0) (Windows 10), Board: "Adafruit Circuit Playground"
Sketch uses 6360 bytes (22%) of program storage space. Maximum is 28672 bytes.

Global variables use 351 bytes of dynamic memory.

Forcing reset using 1200bps open/close on port COM13

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

Uploading using selected port: COM13

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM13 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_570140/sorting_numbers_test.ino.hex:i

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM13

         Using Programmer              : avr109

         Overriding Baud Rate          : 57600

         AVR Part                      : ATmega32U4

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PA0

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

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

           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00

           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly

         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

Found programmer: Id = "F"; type = @

    Software Version = �.v; Hardware Version = �.

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: buffered memory access not supported. Maybe it isn't

a butterfly/AVR109 but a AVR910 device?

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: programmer did not respond to command: leave prog mode

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: programmer did not respond to command: exit bootloader

avrdude done.  Thank you.

the selected serial port

 does not exist or your board is not connected

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.>

Not sure how windows works, I'm not using it, but it looks like serial protocol error, board might have been unplugged (physical or software side), in both case, the board is no more on that serial port number. This can occur when too many devices are serialized, consuming too much. Try to dispatch better all your serial devices on all serial ports.  Reinitialize hardware numbering & re associate the new serial port in Arduino IDE if needed, then it will be OK.

Do you have the correct hardware selected and if like the nano you may have to select a loder.

...for the playground adafruit express gets stuck...

avrdude: initialization failed, rc=-1

You appear to have selected the "Classic" rather than "Express" version of the board, which are different things.

The classic you have selected uses an AVR ATMega32u4 like you'd find in the Arduino Micro/Leonardo.

The "Express" uses an ATSAMD21 chip like an Arduino Zero.

They don't use the same family of microcontroller, bootloader, bootloader protocol, or upload tool. The boards manager package that supports the Class board is completely different from the one that supports the Express board; they are divided support along the lines of the AVR (8-bit) vs SAMD (32-bit arm) chips.
In short, choose the "Express" version of the board after you've gone through setup process for the Express.  If you have problems uploading to an Express with the Express board selected, you're likely to see errors that mention bossac, but you're not going to see anything about avrdude.


text:
Arduino Uno freezes for unknown reason during code execution
I am struggeling with a behaviour of my Arduino I do not fully understand.
Long story short:
When starting the communication over I2C the Arduino freezes. In my opinion during the "Wire.write()" command.
Long story and background:
I want to connect my Arduino Uno to an Arduino MKR Wifi 1010 via I2C. I implemented the code for the communication step by step, so I started with the code below.
Code for the Master Arduino Uno:
#include <Wire.h>
#include <Arduino.h>

#define SLAVE_ADRESS                            2

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

void setup() {
  Serial.begin(38400);
  while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
  Serial.setTimeout(2000);
  Serial.println(F("Serial Connection ready"));
  Wire.begin(); // join i2c bus (address optional for master)
}

void loop() {
  static int LedStatus = 0;
  if (LedStatus == 0)
  {
      LedStatus = 1;
  }
  else
  {
      LedStatus = 0;
  }
  Serial.print(F("Master LED status: "));
  Serial.println(LedStatus);
  Send_Data(SLAVE_ADRESS,LedStatus);
  delay(500);
}n

Code for the Slave Arduino MKR Wifi 1010:

#include <Wire.h>
#include <Arduino.h>

#define NODE_ADDRESS 2

int led = 0;

void setup()
{
  Serial.begin(38400);
  while (!Serial)
  {
        ; /* Wait for serial interface to be connected and ready for use. */
  }
  Serial.setTimeout(1000);

  Wire.begin(NODE_ADDRESS);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes)
{
  led = Wire.read();
  Serial.println("Data reveived!");
  Serial.print("Slave Value led: ");
  Serial.println(led);

}

void loop()
{

}

This piece of code works fine as expected.
So I implemented the very same functionality for the master into my projekt.
/****************************************************************************/
/*-------------------------------Description--------------------------------*/
/****************************************************************************/

/*
Used board: Arduino Uno

>>> Pin usage overview <<<
0:
1:
2: waterlevel tank sensor low (black sensor wires)
3: waterlevel tank sensor high (red sensor wires)
4: waterlevel reservoir sensor low (not used yet)
5: waterlevel reservoir sensor high (not used yet)
6: pump level tank
7: pump level reservoir
8: water temperature sensor
9: water temperature sensor
10:
11:
12:
13:
A0: EC sensor
A1: pH sensor
A2:
A3:
A4:
A5:
/*

/****************************************************************************/
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/

#include <Arduino.h>
#include <RTClib.h>
#include <TimerOne.h>
#include <Wire.h>
#include "WaterCondition.h"
#include "WaterFlow.h"
#include "Serial.h"

/****************************************************************************/
/*----------------------------------Macros----------------------------------*/
/****************************************************************************/

#define TIMER_INTERVAL                          2000000 // 5sec (timer in microsec)

#define RTC_INIT_TIME_SECOND                    0
#define RTC_INIT_TIME_MINUTE                    0
#define RTC_INIT_TIME_HOUR                      0
#define RTC_INIT_TIME_DAY                       0
#define RTC_INIT_TIME_MONTH                     0
#define RTC_INIT_TIME_YEAR                      0

#define OPERATING_MODE_AUTO                     0
#define OPERATING_MODE_TEST_TEMP_SENSOR         1
#define OPERATING_MODE_TEST_EC_SENSOR           2
#define OPERATING_MODE_TEST_PH_SENSOR           3
#define OPERATING_MODE_TEST_RTC                 4
#define OPERATING_MODE_TEST_WATERLEVEL          5
#define OPERATING_MODE_TEST_COMMUNICATION       6

#define SLAVE_ADRESS                            2 // adress of the slave for communication

/****************************************************************************/
/*-----------------------------Global Variables-----------------------------*/
/****************************************************************************/

/*
OPERATING_MODE 0: Automatic
OPERATING_MODE 1: Testing / Calibration
*/
uint8_t OperatingMode = 0;

/* Used for Serial.h to read the input from serial connection */
extern char StringBuffer[STRING_BUFFER_SIZE];
extern float WaterConPhVolt, WaterConEcVolt, WaterConPhVal, WaterConEcVal, WaterConTempVal;

/****************************************************************************/
/*------------------------------Initialization------------------------------*/
/****************************************************************************/

RTC_DS3231 rtc;
DateTime now;

int freeRam()
{
    extern int __heap_start, *__brkval;
    int v;
    return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/* standard operations */
void ISR_Task(void)
{
    if (OperatingMode == OPERATING_MODE_AUTO) // Automatic
    {
        Serial.println(F("Running in automatic mode"));

        uint8_t min;
        min = now.second(),DEC;
        if ((min == PUMP_TANK_ON_INTERVALL_1) || (min == PUMP_TANK_ON_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 0 or 30");
            //Activate pump
            //Function tbd
        }
        else if ((min == PUMP_TANK_OFF_INTERVALL_1) || (min == PUMP_TANK_OFF_INTERVALL_2))
        {
            //Serial.println(F("Test: RTC min = 20 or 50");
            //Deactivate pump
            //Function tbd
        }
        WaterConTempVal = WaterCon_Sensor_TEMP(0);
        WaterConEcVal = WaterCon_Sensor_EC();
        WaterConPhVal = WaterCon_Sensor_PH();
        if (Waterflow_Tank() == 99)
        {
            // tbd
        }

    }
    else // Testing
    {
        /* >>> Test the temperature sensor <<< */
        if (OperatingMode == OPERATING_MODE_TEST_TEMP_SENSOR)
        {
            Serial.print(F("Water temperature filtered: "));
            Serial.println(WaterCon_Sensor_TEMP(0));
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_PH_SENSOR)
        {
            float test_ph = 0;
            test_ph = WaterCon_Analog_Read(PH_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_PH);
            Serial.print(F("PH-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ph);
            Serial.print(F("PH-Value from 0 - 14: "));
            Serial.println(WaterCon_Sensor_PH());
        }

        /* >>> Test the PH sensor <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_EC_SENSOR)
        {
            float test_ec = 0;
            test_ec = WaterCon_Analog_Read(EC_PIN, VOLTAGE_PIN, RESOLUTION_SENSOR_EC);
            Serial.print(F("EC-Sensor-Value raw from 0 - 5000mV: "));
            Serial.println(test_ec);
            Serial.print(F("EC-Value from 0 - 2000uS: "));
            Serial.println(WaterCon_Sensor_EC());
        }

        /* >>> Test the RTC clock <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_RTC)
        {
            Serial.print(F("\nRTC-Time: "));
            Serial.println(now.second(),DEC);
        }

        /* >>> Test the waterlevel sensors <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_WATERLEVEL)
        {
            int WaterLvlSensorLow = 0;
            int WaterLvlSensorHigh = 0;
            WaterLvlSensorLow = digitalRead(TANK_LVL_LOW_PIN);
            WaterLvlSensorHigh = digitalRead(TANK_LVL_HIGH_PIN);

            Serial.print(F("Waterlevel Sensor Low: "));
            Serial.println(WaterLvlSensorLow);
            Serial.print(F("Waterlevel Sensor High: "));
            Serial.println(WaterLvlSensorHigh);
        }

        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

/****************************************************************************/
/*-------------------------Function Implementations-------------------------*/
/****************************************************************************/

void setup() {
    Serial.begin(38400);
    while (!Serial) {;} /* Wait for serial interface to be connected and ready for use. */
    Serial.setTimeout(2000);
    Serial.println(F("Serial Connection ready"));

    /* Initialize sensors */
    Serial.println(F("Setup Sensors"));
    WaterCon_Sensor_Init();
    Waterflow_Sensor_Init();

    /* Initialize RTC */
    Serial.println(F("Setup RTC"));
    rtc.begin();
    Serial.println(F("Test"));

    /* Initialize timers */
    Serial.println(F("Setup Timers"));
    Timer1.initialize(TIMER_INTERVAL);
    Timer1.attachInterrupt(ISR_Task);
    Serial.println(F("Setting the time for the RTC..."));
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

    /* Initialize I2C Master-Slave */
    Wire.begin();
}

void loop()
{
    now = rtc.now();

    delay(200);
    Serial_Read(1);
    /* Change operating mode to automatic */
    if (strcmp("opauto",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to automatic"));
        OperatingMode = 0;
    }
    /* Change operating mode to testing */
    else if (strcmp("optest1",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: temperature sensor"));
        OperatingMode = 1;
    }
    else if (strcmp("optest2",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: EC sensor"));
        OperatingMode = 2;
    }
    else if (strcmp("optest3",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: pH sensor"));
        OperatingMode = 3;
    }
    else if (strcmp("optest4",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: RTC clock"));
        OperatingMode = 4;
    }
    else if (strcmp("optest5",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Waterlevel Sensors"));
        OperatingMode = 5;
    }
    else if (strcmp("optest6",StringBuffer) == 0)
    {
        Serial.println(F("Operating Mode changed to Testing: Communication via I2C Master-Slave"));
        OperatingMode = 6;
    }
}

Some explanation for you to understand what I am trying to do:
Above you can see the code from the Main.ino file for a hydroponic project. I wanted to realize different operating modes for automatic and testing. So if I encounter a fault, I want to be able to plug the laptop on the USB port and start to read out some information over the serial port. Later this should be accomplished over the air but for the beginning this should be fine.
To achieve this, I put string compare into the loop to notice if the user did some input and respond to it.
I tested that functionality a lot and it worked fine. I am able to jump from any operating mode to another.
There is an external real time clock running for using interrupts and run code at specific times.
During this interrupt I check what operating mode is active and run the respective code. With the string compare I mentioned above I can jumo into the respective code with the next interrupt.
ISSUE:
Now I can describe the actual issue. Everytime I enter the "operating mode 6" to test the I2C connection, the Arduino freezes. As you can see I used the very same code inside the "else if" as tested before.
This is the relevant part of the code:
        /* >>> Test the communication over I2C <<< */
        else if (OperatingMode == OPERATING_MODE_TEST_COMMUNICATION)
        {
            static int LedStatus = 0;
            if (LedStatus == 0)
            {
                LedStatus = 1;
            }
            else
            {
                LedStatus = 0;
            }
            Serial.print(F("Master LED status: "));
            Serial.println(LedStatus);
            Send_Data(SLAVE_ADRESS,LedStatus);
        }
    }
}

void Send_Data(int receiver, int data)
{
    Wire.beginTransmission(receiver);
    Wire.write(data);
    Wire.endTransmission();
    Serial.println(F("Data sent"));
}

In the following picture it looks like the Board freezes during the serial communication when it prints out "Master LED status: ". I testet this by commenting out the serial.print commands and insert a print command between Wire.begin and Wire.write in the code.

I think the main problem is caused by the Wire.write function, but I am not able to debug it other than using serial.print commands. But the printed commands do not correlate with the line of code when the board actually freezes. I think I would need real debugger that stops the processor and gives me the possibility to go through the code step by step.
At first I thought this issue was caused because the SRAM got filled. So I put the Serial.print commands in the flash memory and inserted some lines of code for checking the usage of the SRAM and the Stack. You can see the "freeRam()" function in the code, but I removed them for better readability.
Did anyone have a similar issue or do you know what could cause this issue?
Thanks a lot in advance!

In addition to @chrisl's answer, please read Nick Gammon write-up on Interrupts.

The program most likely hangs at Wire.endTransmission();, because that's where the actual I2C communication happens. Wire.write() does nothing but placing the data into the internal buffer of the Wire library.
You experience problems because you are calling interrupt-dependent code inside an ISR, where interrupts are deactivated by default.
The Wire library uses the I2C hardware of the Uno. This hardware generated interrupts for the different stages in the communication (for example generating an interrupt so that the library can place the next data byte in the hardware buffer). That means that the Wire library will not work if interrupts are turned of for some reason. It will wait forever for an interrupt that will never come.
When entering an ISR (in this case of the Timer1 interrupt) other interrupts are deactivated by default. At the end of the ISR the compiler will again turn on interrupts. Any interrupts which happen during the execution of the current ISR will be executed after it has exited.
With Wire.endTransmission() you currently have a function call in your Timer1 ISR, which will wait for its corresponding I2C ISRs to run, which cannot happen inside the Timer1 ISR.
What to do now: You need to restructure your code. You shouldn't do that much stuff in an ISR either way. It needs to be as short as possible to not disturb other interrupt based functions. In the ISR just set a simple 1-byte flag variable. Then in loop() check this flag variable. If it is set, you can do the stuff, which currently is in your ISR. And then you reset the flag to be ready for the next ISR setting it again. For this to work correctly you need to ditch the delay() call in loop(). If you want to do timed things, you can use millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE. Make sure that nothing can block the loop() function for a long period of time (meaning longer than the interval between 2 interrupts or longer than the minimal time resolution, that you want in your system).

Note: You thought of the wrong line while debugging, because of your Serial output. But Serial output is only helping to a certain extent with debugging, since it too needs interrupts to work correctly. All the data that gets printed in your ISR will only be send once the ISR exits. Serial.print() and its siblings only fill the buffer of the library, while the actual sending is done in the background via ISRs. So the sending stopped when it got stuck at the ISR, but that doesn't mean that this actually was what you printed directly before that line. Even when not having interrupts involved this might not be the case. Just keep that in mind when using Serial prints for debugging.

Thank you so so much for taking your time to give me such a detailed insight into the topic of ISR and I2C. I appreciate every comment that helps me writing better code :). I will restructure my code and give a feedback!

Restructuring the code, as you mentioned above, solved the issue. I created a flag for the ISR and only change that value inside the ISR. The other stuff was put inside the loop().


text:
Help needed to check if my solenoid wiring is correct
I'm planning a new custom keyboard project which involves a solenoid being controlled by a Teensy2.0++, and i would like to power everything with just a USB cable.
I don't have much electronics or electrical engineering background but from my research, this is how I think i should be wiring my solenoid up.
I would appreciate if anyone can help me to check if this is correct and doesn't blow anything up.

Your question is not really about arduino. But your wiring is correct if you get the transistor polarity right. You should also consider adding a pulldown at the base to avoid that the solenoid acts randomly on power-up/-down.

Add the pull down resistor at the port pin thereby eliminating a dividing network to the base.


text:
multiple mpu9250 using tca9548a with esp32
I'm using ESP32 and 1 sensor mpu9250(only for test) with tca9548a, connections are:
TCA <-> ESP
VIN - VCC
GND - GND
SDA - GPIO21
SCL - GPIO22
TCA <-> MPU
SD2 - SDA
SC2 - SCL
VIN - VIN
GND - GND
And my code here:
#include <SparkFunMPU9250-DMP.h>
#include <Wire.h>

#define TCAADDR 0x70
void tcaselect(uint8_t i) {
  if (i > 7) return;

  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

MPU9250_DMP imu;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  tcaselect(2);
  if (imu.begin() != INV_SUCCESS)
  {
    while (1)
    {
      Serial.println("Unable to communicate with MPU-9250");
      Serial.println("Check connections, and try again.");
      Serial.println();
      delay(5000);
    }
  }

  imu.dmpBegin(DMP_FEATURE_6X_LP_QUAT | // Enable 6-axis quat
               DMP_FEATURE_GYRO_CAL, // Use gyro calibration
              10); // Set DMP FIFO rate to 10 Hz
              delay(10000);
}

void loop()
{
  tcaselect(2);
    imu.dmpUpdateFifo();
  float q0 = imu.calcQuat(imu.qw);
  float q1 = imu.calcQuat(imu.qx);
  float q2 = imu.calcQuat(imu.qy);
  float q3 = imu.calcQuat(imu.qz);
  Serial.println("Q: " + String(q0, 4) + ", " +
                    String(q1, 4) + ", " + String(q2, 4) +
                    ", " + String(q3, 4));delay(10);
}

I need to get quaternions from the MPU sensor but I'm only getting zeros on the output.

Library that I used: https://github.com/rupin/SparkFun_MPU-9250-DMP_Arduino_Library
What could be wrong, my connection or library?

did you read the answer to this question? https://arduino.stackexchange.com/questions/70834/multiple-mpu9250-synced

You could try adapting the I2C Scanner sketch to use the TCA9548a like you do. Then you can check if the MPU is really visible on the bus. I would think, that the Arduino cannot reach the MPUn thus giving only zeros

@Juraj yes, I will try this method later. But now I'd like to figure out why my method doesn't work

@Juraj It works, thanks!

@chrisl It`s true, TCA scanner cannot find any addresses of MPU9250. Seems like clock stretching(idk). But now I use method of changing address of MPU that i use in 1 tick.

The solution is that I just removed the tca9548a from the circuit. Then I connected each AD0 pin to the corresponding GPIO ESP32 pins to turn on the sensor, I send a low signal to it, and a high signal to all the others. Thus, the library only works with a sensor whose address is 0x68.
There is example function from my sketch:
#include <SparkFunMPU9250-DMP.h>

/*INIT SENSORS*/
MPU9250_DMP imu;
MPU9250_DMP imu1;
const int sensor1 = 18;
const int sensor2 = 19;

String IMU_1Update(){
  String res;
    digitalWrite(sensor1, LOW); // 1st sensor enable - 0x68
    digitalWrite(sensor2, HIGH); // 2nd sensor disable - 0x69
  if ( imu1.fifoAvailable() ){
    if ( imu1.dmpUpdateFifo() == INV_SUCCESS){
      float q0 = imu1.calcQuat(imu1.qw);
      float q1 = imu1.calcQuat(imu1.qx);
      float q2 = imu1.calcQuat(imu1.qy);
      float q3 = imu1.calcQuat(imu1.qz);
      Serial.print("G1|");
      Serial.print(q0);
      Serial.print("|");
      Serial.print(q1);
      Serial.print("|");
      Serial.print(q2);
      Serial.print("|");
      Serial.print(q3);
      Serial.println("|");
    }
  }
  return res;
}


text:
Why does the send pin influence the receive pin with Arduino Capacitive Sensing Library
I'm trying to figure out how the Arduino Capacitive Sensing Library https://playground.arduino.cc/Main/CapacitiveSensor/ works. It says:

When the send pin changes state, it will eventually change the state of the receive pin.

However, when I look at the following schematic, I don't understand why this is the case. It seems like the send pin is set to OUTPUT and HIGH and the receive pin to INPUT with deactivated pull-up. I think it's okay to ignore the capacitance at first, yes? Doesn't all the voltage drop over the resistor R and the receive pin will just be floating and showing LOW or HIGH randomly?

Source: https://playground.arduino.cc/Main/CapacitiveSensor/

If we ignore the capacitance of the input pin, then it would instantly follow the voltage of the send pin. A voltage drop over the resistor only happens if a current is flowing though it, which cannot happen without any capacitance the receive side. Without current a resistor is just a wire.
A floating pin doesn't directly have its state randomly changes between LOW and HIGH. That can only be the result as the voltage on that pin is changes by the noise. We need the noise to not be directly in the logic voltage range, so that the state of the digital input pin is not totally dictated by noise. That often the case. Also the additional capacitance added by the sensing foil helps with filtering the noise.
The actual measurement works as follows: We set the send pin to a known state and wait a bit (to fully load or unload the capacitance on the pin). Then we change the send pin to the other state and count the time until we see that change on the receive pin. That is when the capacitance of the pin is loaded. Then we are doing that procedure many times, averaging the measured time. What the receive pin does outside of the measurements is not important. During the meausrement its state is mainly dictated by us setting the send pin. Though the library might use some optimization to get a better reading. You could read the libraries code to learn more about that.

Huh okay. Thank you for the answer! I think I'm learning a lot new stuff here. So you're saying when I simply connect two GPIO pins with a resistor, one is set to output, one is set to input - then no current is flowing at all and therefore the resistor is like a wire? If no current is flowing, how does the input pin "know" the output pin's state?

I wanted to say, that there actually is a bit of current flowing, because you simply cannot leave out the capacitance of the pin in this case. Also the digital input pin is basically a Schmitt trigger, which only has very very low input current. And why shouldn't the input pin "know" the state? It senses voltage, not current. I'm not sure, where the confusion is here.

I'm sorry for the confusion. Yes, it measures voltage. So I thought all the voltage has already dropped over the resistor, so nothing is left to measure at the input pin. But that's the point, right? There is current flowing as long as the "capacitor" (sensor plate + human) isn't charged, so the voltage drops over the resistor. The input pin is low. When it's charged, no more current flows and the resistor becomes a wire, the input pin is now high. Is that correct?

Yes, thats correct

Ahh, thank you. I think I'm beginning to get a grip on it. Sorry, another follow-up question: so the "capacitor" gets fully charged/discharged for every measuring cycle? (I would have thought that's quite a lot of electric charge?)

Yes, it gets "fully" (dis)charges on every measurement (fully to a certain extend, since the voltage will approach the slower when it gets near the supplied voltage, refer to the charging curve of a capacitor). If thats a lot depends on your definition of a lot. In relation to other commonly with Arduino used compnents: No, not a lot. The capacitance will greatly depend on your foil layout/position, but it will be rather small in relation to other normally used capacitors (like the ones in the uF range used for filtering)

Perfect, thanks a lot! :)

Next step is that I just have to figure out why my board keeps showing me erroneous readings for the sense pin haha. (When I set send pin to 1 and keep reading the receive pin, I sometimes get 0, sometimes 1.) If you're interested: https://forum.micropython.org/viewtopic.php?f=2&t=11237


text:
Capacitive touch on Adafruit Trinket M0 goes unstable when USB cable from laptop is disconnected
Note that to get to this point, I used much of the helpful information from the Post
How to use capactive touch on Adafruit board in Arduino mode?
I am using a Trinket M0 with the Arduino IDE with the Adafruit_FreeTouch.h library.
Also used the example code found here
https://github.com/adafruit/Adafruit_FreeTouch/blob/master/examples/freetouch/freetouch.ino
I modified the code to use the A0 input as a touch sensor with a wire and aluminum foil.
Using a FET on the digital output A2 to turn a fan on or off when the foil is touched.
I am using a small 12VDC wall transformer (1.25A) and then a DC-DC converter to output 5vdc for the Trinket on the BAT in.  The 12Vdc also supplies power to the small computer fan ( uses about 200ma)
The circuit and code work great when the USB cable from my laptop is connected to the Trinket.
BUT, when I disconnect the USB cable from the Trinket and touch the sensor, everything goes unstable.  Fan and built-in led cycle on/off randomly at 0.5sec to 2sec intervals.
I've tried all different parameters for the library including the series resistor, sampling rate and frequency modes. I've checked grounds multiple times and this one is really stumping me.
I suspected fan noise early on so the most interesting experiment I've tried so far IMHO is to remove the 12vdc to the fan but keep it supplying the DC-DC converter for the 5v to the trinket-But, the onboard led has the same instability as when fan is connected.
Lastly, I used an Arduino Uno to develop the code and the circuit earlier and it worked fine without USB cable connected.
I feel so close.
Any suggestions or insights much appreciated.
Here is my code
/ touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
// Note: the pin silkscreened 1 is Analog Pin 0.

#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_0, FREQ_MODE_NONE);
int led = 13; // blink 'digital' pin 1 - AKA the built in red LED
int FAN = 2;  //

void setup() {
// initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(FAN, OUTPUT);
  digitalWrite(led, LOW);
  digitalWrite(FAN, LOW);
  delay(50);
  // Initialize A0 as a touch sensor
  if (! qt_1.begin())
    //Serial.println("Failed to begin qt on pin A0");
    digitalWrite(led, HIGH);    // Turn on the led
}
void loop()
{
  int counter;
  int result = 0;
  counter = millis();
  result = qt_1.measure();
  if (result > 950) {
    digitalWrite(FAN, HIGH);    // Turn on the FAN
    digitalWrite(led, HIGH);    // Turn on the led
  }
  else {
      digitalWrite(FAN, LOW);    // Turn off the FAN
      digitalWrite(led, LOW);    // Turn off the led
  }
  delay(50);
}

Here is schematic

Not sure if I'm doing this right by posting an answer?
I didn’t expect this to be as complex!  Unfortunately adding the suggestion to add the capacitors did not change anything.
But the answer makes sense to me because when I think of why it worked so well on my Arduino Uno development circuit, it could have been because I was using the Capacitive Sense library which utilized two pins that to my understanding measured a RC type of decay to achieve the touch sensing.
Too bad that the Trinket doesn’t operate the same way.  And my programming skills are not strong enough to come up with a similar design solution as the Arduino Uno RC sensing.
So, I will try the idea in the answer where I implement the “side by side with a gap” touch sensor just for learnings sake.  I’ve seen these touch sensors often as traces on a pcb.
But I should share what my ultimate design goal is.
That is to make a touch sensitive art lamp that has a steel body. The lamps are diodes and diodes strips which will be brightness controlled with a PWM input.  So, there is no need for an AC connection other than for the wall transformer which supplies DC.  The design needs to sense a touch whenever someone touches anywhere on the lamp body so that the SW can simulate a three-way switch.  So, a “side by side” gap doesn’t work in this application.  I was hopeful that the Trinket would work since I had everything working in my Arduino proto.  And I’m really looking for a “small” trinket type board solution to fit in the lamp.  In the past I have been successful achieving this functionality with AC power lamps by using those replacement touch circuit modules for 3-way AC switched bulbs.  But for this I wanted to use LED energy saving light sources with a microcontroller.
I think I will try to research “dedicated or discrete” touch sensing circuits that can give me digital input to the Trinket when a touch is sensed on the lamp body.
Any other suggestions/comments are greatly appreciated.
Cheers

What would happen if you connected the USB cable ground with a jumper wire to the 12v. power supply ground without plugging in the USB cable?

As far as I can tell from Trinker M0 schematic, there should be no difference by powering via VBUS or VBAT. So here are a few of suggestions that you could try, 1) add a 10uF e-capacitor at the output of your DC-DC converter (i.e. between 5V and ground), 2) add another 0.1uF between VBat and GROUND near the VBat pin. 3) You should also add a protection diode (1N4148 or equivalent) between the fan by connecting the cathode of the diode to +12V and anode to pin 1 of Q1. 4) reduce the expose or the surface of the aluminium foil, as it might be too sensitive and acts like an antenna...

Have you tried putting another foil connected to ground near the sensing foil? Capacitive touch sensors work by building a capacitor between the input pin and ground whose capacity is changed by the finger. Bringing to devices ground near the foil might help

The problem is most likely your power supply coupled with the poor design of the capacitive sensing system.
The capacitive sensing is done by measuring the capacitance between your foil plate and "ground". That "ground" is usually a connection through the USB cable and your computer's power supply through the earth wire of your power cable to the physical ground, so you are then between the two "plates" of the capacitor.  That ground connection is "clean". For a laptop the "ground" is usually just the case of the laptop or metal parts of the internals. This has no, or little, power supply noise.
However when you use a USB power supply you no longer have that "clean" connection. Instead your "ground" is going through the negative lead of the USB into the negative rail of the USB power supply which is then capacitively coupled to the neutral of the mains through a "class Y" capacitor across the transformer (there to remove inductive switching noise). That capacitor handles some quite high voltages and lots of noise, so you get that noise also reflected into your USB "ground", meaning the ground that you are using in your capsense "capacitor" is really quite noisy. Noisy enough to make your readings meaningless. On some laptops you may even notice a change when you plug the charger in compared to running on batteries for this same reason. (It's also why some early aluminium Apple laptops could give you an electric shock if you used them while plugged in...)
If you look at proper capacitive sensing arrangements you will see that the aren't just a bit of metal foil. They are properly arranged traces on a PCB which not only include the "sense" side but also the "ground" side of the capacitor. Your finger then affects the capacitance between these two points, not between a bit of foil and the floor of your room.
You should get a piece of cardboard and glue two pieces of foil side by side on it with a small gap between them. Then connect one of them to the Arduino's ground and the other to your input pin. Then recalibrate your readings to work with the new arrangement. You should find it far more stable and reliable.


text:
What external battery do I need?
For a school project I need to connect an Arduino with an accelerometer gyroscope sensor and 2 mini servo motors. Of course I need a battery for this. However, I don’t know what battery I need for this. I have no clue where to start. Does anyone know which battery I can use? Or how I can find this out? I added links of the sensor, Arduino and servo motors that I have below.
Thanks in advance! :)
Sensor:
https://www.tinytronics.nl/shop/nl/sensoren/acceleratie-rotatie/mpu-6500-accelerometer-gyroscope-6dof-module-3.3v-5v
Arduino uno:
https://www.tinytronics.nl/shop/nl/development-boards/microcontroller-boards/arduino-compatible/uno-r3-met-usb-kabel
Mini servo motor:
https://www.tinytronics.nl/shop/nl/mechanica-en-actuatoren/motoren/servomotoren/ts90d-mini-servo-1.6kg-continuous

Before you can select a battery, you have to find out how much current your setup uses. You could do this by connecting everything up to a power supply, running the code you intend to run on batteries and measuring the (average) current from the power supply with a multimeter. You also have to figure out how long you need your battery to last as this will determine the minimum capacity you need. You need to take into account voltage conversion (for example for converting the output of a 3.7V LiPo to the 5V needed by the Arduino).

If you don't want to build your own battery system, you could probably just use a common 5V power bank (i.e. the type used for charging your phone on the road) with sufficient capacity.

Unless you want to make the battery part of your learning experience I second StarCats suggestion of the USB power bank. It is the easiest way to add a battery. I often use them in my projects. Though this can also depend on the exact power bank. Often the bigger ones automatically turn off, when not enough current is drawn. Havent seen that with cheap little power banks (which might be enough for you)

@chrisl There is kind a remedy for these auto turn-off power banks, designed by Mr Carlson

Hi Thank you for answering! Sadly I do not have a multimeter of anything like that. I am really not familiar with things like this to be honest… So what battery should I use now then? …

given the constraints of usb power bank, and an unknown amp hour need and no ability to figure it out, go with the highest amp hour usb power bank you can use and hope it's enough.

If you can't figure the requirements out you are only left with trail and error. I would think any USB power bank can provide enough current for your project. Then choose a power bank with an amp hour rating of your liking (that sets the run time with the fully charged power bank


text:
String Split Issue
I am getting multiple messages from a GPS device at different frequencies. After getting strings I have to save this data on the SD card. It works well when we have the same frequencies messages but if the frequencies are not same the saved data gets some blank spaces.
I am using the split strings method.
    CR1A = String1.indexOf(13);  //finds location of first
    String1A = String1.substring(0, CR1A + 2 );   //captures first data String
    CR1B = String1.indexOf(13, CR1A + 2 ); //finds location of second ,
    String1B = String1.substring(CR1A , CR1B + 2 ); //captures second data String
    CR1C = String1.indexOf(13, CR1B + 2 );
    String1C = String1.substring(CR1B , CR1C + 2 );
    CR1D = String1.indexOf(13, CR1C + 2 );
    String1D = String1.substring(CR1C , CR1D + 2 );
    CR1E = String1.indexOf(13, CR1D + 2 );
    String1E = String1.substring(CR1D , CR1E + 2 );
    CR1F = String1.indexOf(13, CR1E + 2 );
    String1F = String1.substring(CR1E , CR1F + 2 );

    strID = (String1A.substring(0, 2));
    if (strID == "$G") {
      File dataFile = SD.open("GPS1.txt", FILE_WRITE);
      // if the file is available, write to it:

      strID = (String1A.substring(0, 5));
      if (strID == "$GPGG") {
        dataFile.print(dt);
        dataFile.print(" ");
        dataFile.print(tm);
        dataFile.print(msec);
        dataFile.print(",");
        dataFile.print(String1A);
        String1A = "";
      }

      strID = (String1D.substring(4, 6));
      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
        dataFile.print(String1B);
        String1B = "";
      }
      strID = (String1C.substring(4, 6));
      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
        dataFile.print(String1C);
        String1C = "";
      }
      strID = (String1D.substring(4, 6));
      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
        dataFile.print(String1D);
        String1D = "";
      }
      strID = (String1E.substring(4, 6));
      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
        dataFile.print(String1E);
        String1E = "";
      }
      strID = (String1F.substring(4, 6));
      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
        dataFile.print(String1F);
        String1F = "";
      }
      dataFile.close();
    }

EDIT:
This is the code now I am using. I have turned off all the commands which extract strings from my available data received at the serial port. I am just using an interrupt timer for it.. and it is working perfectly. But I didn't like this simple method and I don't know it's a good way to get strings like this or not as I am not a good programmer.
#include <TimerOne.h>
#define RxTimeOut 5

/*
  ** MEGA MINI **
  ** MOSI - pin 51
  ** MISO - pin 50
  ** CLK - pin 52
  ** CS - pin 53 (for MKRZero SD: SDCARD_SS_PIN)
  ** SDA - pin 20
  ** SCL - pin 21
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <EEPROM.h>
#include "math.h"
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"
#define DS1307_CTRL_ID 0x68
unsigned long int ticks = 0;
RTC_DS1307 rtc;
bool flag = false;
String GPSmessage = "";
const int chipSelect = 53;
String dataString = "";
//String dataString1 = "";
//String dataString2 = "";
//String dataString3 = "";
bool stringComplete = false;
bool string1Complete = false;
bool string2Complete = false;
bool string3Complete = false;
String strID = "";

unsigned long msec;
const long interval = 500;

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

unsigned long CurrentBaudRate = 9600;

unsigned long x = 0;

int Up = 3;
int Dn = 4;
int Mnu = 5;

String String1;
String inputString1 = "";         // a String to hold incoming data
boolean NewDataFlag1 = 0;
unsigned int Serial1TimeOut = 0;

String String2;
String inputString2 = "";         // a String to hold incoming data
boolean NewDataFlag2 = 0;
unsigned int Serial2TimeOut = 0;

String String3;
String inputString3 = "";         // a String to hold incoming data
boolean NewDataFlag3 = 0;
unsigned int Serial3TimeOut = 0;

void timerIsr()
{
  serial1Event();
  serial2Event();
  serial3Event();

  if (Serial1TimeOut > 0)Serial1TimeOut--;
  if (Serial1TimeOut == 0 && NewDataFlag1 == 1)
  {
    String1 = inputString1;
    inputString1 = "";
    NewDataFlag1 = 0;
  }

  if (Serial2TimeOut > 0)Serial2TimeOut--;
  if (Serial2TimeOut == 0 && NewDataFlag2 == 1)
  {
    String2 = inputString2;
    inputString2 = "";
    NewDataFlag2 = 0;
  }

  if (Serial3TimeOut > 0)Serial3TimeOut--;
  if (Serial3TimeOut == 0 && NewDataFlag3 == 1)
  {
    String3 = inputString3;
    inputString3 = "";
    NewDataFlag3 = 0;
  }

}

void setup() {

  Timer1.initialize(5000); // Timer event time
  Timer1.attachInterrupt( timerIsr );

  Serial.println("Sonay di nathli");

  //========================================= SD Card =======================================================//
  //  Serial.println("Initializing SD card...");

  // see if the card is not present:
  if (!SD.begin(chipSelect)) {
    //    Serial.println("Card failed, or not present");
    //     don't do anything more:
    return;
  }
  //  Serial.println("SD card Ready");

  //====================================================== RTC =============================================//
  if (!rtc.begin())
  {
    //    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (!rtc.isrunning()) {
    //    Serial.println("RTC is NOT running, let's set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  //================================================ OLED Baudrate selection ====================================================//
  pinMode(Up, INPUT_PULLUP);
  pinMode(Dn, INPUT_PULLUP);
  pinMode(Mnu, INPUT_PULLUP);

  unsigned char bdindx = EEPROM.read(0);
  if (bdindx > 3) bdindx = 0;
  if (bdindx == 0) CurrentBaudRate = 4800;
  if (bdindx == 1) CurrentBaudRate = 9600;
  if (bdindx == 2) CurrentBaudRate = 19200;
  if (bdindx == 3) CurrentBaudRate = 115200;
  delay (500);

  while (!Serial) { }// wait for serial port to connect
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(CurrentBaudRate);
  Serial1.begin(CurrentBaudRate);
  Serial2.begin(CurrentBaudRate);
  Serial3.begin(CurrentBaudRate);
  Serial.println(CurrentBaudRate);
  delay (1000);

  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  display.clearDisplay();
  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.display();

}

String String1A, String1B, String1C, String1D, String1E, String1F;
String String2A, String2B, String2C, String2D, String2E, String2F;
String String3A, String3B, String3C, String3D, String3E, String3F;
int CR1A, CR1B, CR1C, CR1D, CR1E, CR1F;
int CR2A, CR2B, CR2C, CR2D, CR2E, CR2F;
int CR3A, CR3B, CR3C, CR3D, CR3E, CR3F;

// ============================================ Showing baud rate on screen (position) ===========================================//

void DrawBaudRate(unsigned long BdRt)
{
  unsigned char Xoffset = 0;
  if (BdRt >= 0 && BdRt < 10000) Xoffset = 37;
  if (BdRt >= 10000 && BdRt < 100000) Xoffset = 30;
  if (BdRt >= 100000 ) Xoffset = 25;
  //  display.drawRect(0,0,128,64,SSD1306_WHITE);
  //  display.setTextSize(2);
  //  display.setCursor(15,10);
  //  display.println("Baudrate");
  //  display.setTextSize(2);
  //  display.setCursor(15,10);
  //  display.println(tm);
  //  display.setCursor(Xoffset,37);// 6 digit
  //  display.println(BdRt);
  //  display.display();
  //  delay(10);
}

// ================================================== Selection of Baud Rate ========================================================//
unsigned long SelectBaudRate(unsigned long BdRt)
{
  unsigned char BdRtIndx = 0;
  unsigned int FlashCnt = 0;

  if (BdRt == 4800) BdRtIndx = 0;
  if (BdRt == 9600) BdRtIndx = 1;
  if (BdRt == 19200) BdRtIndx = 2;
  if (BdRt == 115200) BdRtIndx = 3;

  unsigned char Xoffset = 0;
  if (BdRt >= 0 && BdRt < 10000) Xoffset = 37;
  if (BdRt >= 10000 && BdRt < 100000) Xoffset = 30;
  if (BdRt >= 100000 ) Xoffset = 25;
  display.drawRect(0, 0, 128, 64, SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(15, 10); display.println("Select Baudrate");
  display.setCursor(15, 20); display.println("by Up/Dn Buttons");
  display.setTextSize(2);
  display.setCursor(Xoffset, 37); // 6 digit
  display.println(BdRt);
  display.display();
  delay(10);

  while (digitalRead(Mnu) == 0) delay(10);
  delay(100);

  while (digitalRead(Mnu) == 1)
  {
    delay(10);
    FlashCnt++;

    if (digitalRead(Up) == 0)
    {
      if (BdRtIndx < 3) BdRtIndx++;
    }

    if (digitalRead(Dn) == 0)
    {
      if (BdRtIndx > 0) BdRtIndx--;
    }

    if (BdRtIndx == 0) BdRt = 4800;
    if (BdRtIndx == 1) BdRt = 9600;
    if (BdRtIndx == 2) BdRt = 19200;
    if (BdRtIndx == 3) BdRt = 115200;

    if (BdRt >= 0 && BdRt < 10000) Xoffset = 37;
    if (BdRt >= 10000 && BdRt < 100000) Xoffset = 30;
    if (BdRt >= 100000 ) Xoffset = 25;
    display.clearDisplay();
    display.drawRect(0, 0, 128, 64, SSD1306_WHITE);
    display.setTextSize(1);
    display.setCursor(15, 10); display.println("Select Baudrate");
    display.setCursor(15, 20); display.println("by Up/Dn Buttons");
    display.setTextSize(2);
    display.setCursor(Xoffset, 37); // 6 digit
    if (FlashCnt > 1) display.println(BdRt);
    if (FlashCnt > 2) FlashCnt = 0;
    display.display();
    delay(250);

    //while(digitalRead(Up)==0 || digitalRead(Dn)==0) delay(10);
  }
  while (digitalRead(Mnu) == 0) delay(10);

  display.clearDisplay();
  display.drawRect(0, 0, 128, 64, SSD1306_WHITE);
  display.setTextSize(2);
  display.setCursor(20, 10); display.println("Saving");
  display.setCursor(20, 35); display.println("Changes");
  display.display();
  delay(2000);

  EEPROM.write(0, BdRtIndx);

  return (BdRt);

}

//=================================================== OLED showing time ===============================================//
char Time[]     = "  :  :  ";
byte i, second, minute, hour;

void DS3231_display() {
  // Convert BCD to decimal
  second = (second >> 4) * 10 + (second & 0x0F);
  minute = (minute >> 4) * 10 + (minute & 0x0F);
  hour   = (hour >> 4)   * 10 + (hour & 0x0F);
  // End conversion

  Time[7]     = second % 10 + 48;
  Time[6]     = second / 10 + 48;
  Time[4]     = minute % 10 + 48;
  Time[3]     = minute / 10 + 48;
  Time[1]     = hour   % 10 + 48;
  Time[0]     = hour   / 10 + 48;
  display.drawRect(0, 0, 128, 64, SSD1306_WHITE);
  draw_text(16, 25, Time, 2);                         // Display the time
}

void blink_parameter() {
  byte j = 1;
  while (j < 10 && digitalRead(Up) && digitalRead(Dn)) {
    j++;
    delay(25);
  }
}

byte edit(byte x_pos, byte y_pos, byte parameter) {
  char text[3];
  sprintf(text, "%02u", parameter);
  while (!digitalRead(Up));                     // Wait until button B1 released
  while (true) {
    while (!digitalRead(Dn)) {                  // If button B2 is pressed
      display.clearDisplay();
      parameter++;
      if (i == 0 && parameter > 23)                  // If hours > 23 ==> hours = 0
        parameter = 0;
      if (i == 1 && parameter > 59)                  // If minutes > 59 ==> minutes = 0
        parameter = 0;
      sprintf(text, "%02u", parameter);
      draw_text(x_pos, y_pos, text, 2);
      delay(200);                                    // Wait 200ms
    }
    display.drawRect(0, 0, 128, 64, SSD1306_WHITE);
    draw_text(x_pos, y_pos, "  ", 2);
    blink_parameter();
    draw_text(x_pos, y_pos, text, 2);
    blink_parameter();
    if (!digitalRead(Up)) {                     // If button B1 is pressed
      i++;                                           // Increament 'i' for the next parameter
      //      display.clearDisplay();

      return parameter;                              // Return parameter value and exit
    }
  }
}

void draw_text(byte x_pos, byte y_pos, char *text, byte text_size) {
  display.setCursor(x_pos, y_pos);
  display.setTextSize(text_size);
  display.print(text);
  display.display();
}

//---------------------------------------------
void loop() {

  // ========================================= Editing time and displaying on OLED ============================================//
  if (!digitalRead(Up)) {                       // If button B1 is pressed
    i = 0;
    while (!digitalRead(Up));                   // Wait for button B1 release

    hour   = edit(16, 25, hour);                     // Edit hours
    minute = edit(52, 25, minute);                   // Edit minutes

    // Convert decimal to BCD
    minute = ((minute / 10) << 4) + (minute % 10);
    hour = ((hour / 10) << 4) + (hour % 10);
    // End conversion

    // Write data to DS3231 RTC
    Wire.beginTransmission(0x68);               // Start I2C protocol with DS3231 address
    Wire.write(0);                              // Send register address
    Wire.write(0);                              // Reset sesonds and start oscillator
    Wire.write(minute);                         // Write minute
    Wire.write(hour);                           // Write hour
    Wire.endTransmission();                     // Stop transmission and release the I2C bus
    delay(200);                                 // Wait 200ms
  }

  Wire.beginTransmission(0x68);                 // Start I2C protocol with DS3231 address
  Wire.write(0);                                // Send register address
  Wire.endTransmission(false);                  // I2C restart
  Wire.requestFrom(0x68, 7);                    // Request 7 bytes from DS3231 and release I2C bus at end of reading
  second = Wire.read();                         // Read seconds from register 0
  minute = Wire.read();                         // Read minutes from register 1
  hour   = Wire.read();                         // Read hour from register 2
  Wire.beginTransmission(0x68);                 // Start I2C protocol with DS3231 address
  Wire.write(0x11);                             // Send register address
  Wire.endTransmission(false);                  // I2C restart
  Wire.requestFrom(0x68, 2);                    // Request 2 bytes from DS3231 and release I2C bus at end of reading
  DS3231_display();                             // Diaplay time & calendar

  delay(50);                                    // Wait 50ms

  { display.clearDisplay();
    if (digitalRead(Mnu) == 0) CurrentBaudRate = SelectBaudRate(CurrentBaudRate);
    //  DrawBaudRate(CurrentBaudRate);
    delay(10);

    x++;
    if (x > 123456) x = 0;
  }

  // ======================================= Reading Date and Time from RTC =============================================//
  DateTime now = rtc.now();
  char dt[16];
  char tm[16];
  char buffer [16];
  uint8_t thisSec, thisMin, thisHour;
  thisSec = now.second();
  thisMin = now.minute();
  thisHour = now.hour();
  sprintf(dt, "%02d-%02d-%02d", now.year(), now.month(), now.day());
  sprintf(tm, "%02d%02d%02d", now.hour(), now.minute(), now.second());
  sprintf (buffer, "%02d:%02d:%02d", thisHour, thisMin, thisSec);
  msec = millis() % 1000; //TO USE LAST 3 DIGITS OF MILLIS OF ARDUINO

  //SERIAL_PORT_1

//  if (string1Complete)
  { Serial.print (String1);
//    CR1A = String1.indexOf(13);  //finds location of first
//    String1A = String1.substring(0, CR1A + 2 );   //captures first data String
//    CR1B = String1.indexOf(13, CR1A + 2 ); //finds location of second ,
//    String1B = String1.substring(CR1A , CR1B + 2 ); //captures second data String
//    CR1C = String1.indexOf(13, CR1B + 2 );
//    String1C = String1.substring(CR1B , CR1C + 2 );
//    CR1D = String1.indexOf(13, CR1C + 2 );
//    String1D = String1.substring(CR1C , CR1D + 2 );
//    CR1E = String1.indexOf(13, CR1D + 2 );
//    String1E = String1.substring(CR1D , CR1E + 2 );
//    CR1F = String1.indexOf(13, CR1E + 2 );
//    String1F = String1.substring(CR1E , CR1F + 2 );
//
//    strID = (String1A.substring(0, 5));
//    if (strID == "$GPGG") {
//      Serial.println(String1);
//    }
//    strID = (String1B.substring(0, 5));
//    if (strID == "$GPVT") {
//      Serial.println(String1B);
//    }
//    strID = (String1C.substring(0, 5));
//    if (strID == "$GPZD") {
//      Serial.println(String1C);
//    }
//    strID = (String1D.substring(0, 5));
//    if (strID == "$GPGL") {
//      Serial.println(String1D);
//    }
//    strID = (String1E.substring(0, 5));
//    if (strID == "$GPGN") {
//      Serial.println(String1E);
//    }
//    strID = (String1F.substring(0, 5));
//    if (strID == "$GPGR") {
//      Serial.println(String1F);
//    }
//    strID = (String1.substring(0, 2));
//    if (strID == "$") {
      File dataFile = SD.open("GPS1.txt", FILE_WRITE);
      // if the file is available, write to it:

      strID = (String1A.substring(0, 5));
      if (strID == "$GPGG") {
        dataFile.print(dt);
        dataFile.print(" ");
        dataFile.print(tm);
        dataFile.print(msec);
        dataFile.print(",");
        dataFile.print(String1);
        Serial.print (String1);
        String1 = "";
        Serial.print (String1);
        dataFile.close();
      }
//    }
//      strID = (String1D.substring(4, 6));
//      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
//        dataFile.print(String1B);
//        String1B = "";
//      }
//      strID = (String1C.substring(4, 6));
//      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
//        dataFile.print(String1C);
//        String1C = "";
//      }
//      strID = (String1D.substring(4, 6));
//      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
//        dataFile.print(String1D);
//        String1D = "";
//      }
//      strID = (String1E.substring(4, 6));
//      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
//        dataFile.print(String1E);
//        String1E = "";
//      }
//      strID = (String1F.substring(4, 6));
//      if (strID == "TG" || "DA" || "LL" || "NS" || "RS") {
//        dataFile.print(String1F);
//        String1F = "";
//      }

//    }
    else {
      File dataFile = SD.open("ES2.txt", FILE_WRITE);

      if (dataFile) {
        dataFile.print(dt);
        dataFile.print(" ");
        dataFile.print(tm);
        dataFile.print(msec);
        dataFile.print(",");
        dataFile.println(String1);
        Serial.print (String1);
//        dataFile.println(String1B);
        String1A = "";
        String1B = "";
        dataFile.close();
      }
    }
//  }
  string1Complete = false;
  }

}

//-----------------------------------------------------------------------------------------------------------------

void serial1Event() {
  while (Serial1.available()) {
    char inChar1 = (char)Serial1.read();
    inputString1 += inChar1;
    Serial1TimeOut = RxTimeOut;
    NewDataFlag1 = 1;

    if (NewDataFlag1 == 1) {
      string1Complete = true;
    }

  }
}

You never check that indexOf() does find the '\r'. Why do you try to process five messages at a time instead of processing them one by one?

Please provide a more detailed description of what message data you have in that string, what errornous output you get and where in the code that happens.

If (strID == "TG" || "DA" || "LL" || "NS" ... that is nonsense

I will provide you my complete program. Actually there is no delay between sentences so when the processor writes one sentence to sd card 2nd message arrives and most of the time it saves glitch in sd card.

If you're curious, "DA", "LL", and "NS" are all truthy in C++.  So, the above mentioned nonsense is functionally equivalent to if (true).

@OmarRai, just to be clear, you want to be using the "edit" link under your question to add additional details to the question.  If you want to intact with the people asking you questions you want to "Add comment".  The only time you're going to "Post Your Answer" is if you've managed to solve our own problem.

I do not know what the “frequencies” have to do with your problem, but I
would bet that you would get more reliable results if you handle one
NMEA sentence at a time, instead of trying to handle six of them at
once, and hoping to get the right ones.
Below is a function that processes one complete sentence at a time. It
records the sentence to the SD file if its type belongs to a list of
“interesting” types you want to monitor:
// Sentence types that are to be recorded.
const char monitoredTypes[6][4] = {
    "GGA", "VTG", "ZDA", "GLL", "GNS", "GRS"
};

// Process a complete, CRLF-terminated NMEA sentence.
void processSentence(String &sentence) {

    // Sanity check.
    if (sentence.substring(0, 3) != "$GP") {
        Serial.print("WARNING: invalid sentence: ");
        Serial.print(sentence);
        return;
    }

    // Record the sentence if it has an interesting type.
    String type = sentence.substring(3, 6);
    for (int i = 0; i < 6; i++) {
        if (type == monitoredTypes[i]) {
            File dataFile = SD.open("GPS1.txt", FILE_WRITE);
            if (type == "GGA") {  // this type seems to be special
                dataFile.print(dt);
                dataFile.print(" ");
                dataFile.print(tm);
                dataFile.print(msec);
                dataFile.print(",");
            }
            dataFile.print(sentence);
            dataFile.close();
        }
    }
}

The way to use it is to buffer the incoming characters until you get a
complete sentence (identified by the final LF), then submit that buffer
to this function:
String buffer;

void loop() {
    while (Serial.available() > 0) {
        char c = Serial.read();
        buffer += c;

        // On end of sentence, process and clear the buffer.
        if (c == '\n') {
            processSentence(buffer);
            buffer = "";
        }
    }
}

Note that it wouldn't take too much work to get rid of the String
class and use plain C strings instead. Plain strings are way more memory
friendly.


text:
Arduino Zero not recognised as MIDI device via native USB port
I'm currently trying to get an Arduino Zero to show up as a native USB MIDI device in my DAW (ableton). No matter what I try, I cannot get it to show up as a device in Ableton. I have previously used an arduino DUE for a similar project, but cannot get this to work the same. Is there something I'm missing to get the Zero to show up as a native USB Device?
Below is the code have written. I had assumed that the MIDIUSB library takes care of the arduino being recognised as a USB device.
#include <MIDIUSB.h>

const byte CHANNEL = 1;
const byte OFFSET = 48;

void setup(){}

void loop()
{
    delay(100);
    sendNoteOn(CHANNEL, 50 + OFFSET, 127);
    delay(100);
    sendNoteOff(CHANNEL, 50 + OFFSET, 0);
}

void sendNoteOn(byte channel, byte pitch, byte velocity)
{
  midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOn);
}

void sendNoteOff(byte channel, byte pitch, byte velocity)
{
  midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOff);
}

What OS and hardware are you using?

Windows 10 PC. Intel 6700k cpu.

what is windows detecting when you plug in your device?

Remove all of the Adafruit_Trellis stuff from your posted code.  If that doesn't make it work (and it may easily) the number of people here that can and are willing to replicate your problem skyrockets.

Check windows device manager and see if it is actually detecting a MIDI device or just a simple CDC/ACM one. If Windows detects it as MIDI then the problem is with your DAW not liking it. If Windows is not detecting it as MIDI the problem is your code or the MIDI library.

Thanks all for the comments. @jsotola, this is what found the solution for me. The device manager looked spooky so I tracked down the drivers on github and used them instead of relying on it all working automatically.

also, @timemage, I've removed all the irrelevent code for future people who come accross the same issue.

After extended trouble shooting and device manager fiddling, It turned out that Windows was auto installing the wrong (or partially wrong) drivers that made the native port not be recognised as a USB device. The device was detected as two different ports in the USB drivers, one of which had an error warning. I could still upload to it via either of the USB ports, just couldn't get it to be recognised as a MIDI device.
The solution was to:

completely uninstall the drivers from the device manager
uninstall the SAMD boards from the Arduino IDE
manually download the drivers from github
plug the arduino back in and install everything again as normal using those drivers

It now works like a charm.


text:
Which C++ standard does the Arduino language support?
The "Arduino language" (as they call it) of the Arduino IDE 1 is obviously C++. Which C++ exactly?
I tried to figure it out myself (Arduino IDE 1.8.13 for Arduino Uno), but I can't conclude what C++ standard it supports.
From these tests, it seems to support C++14

C++ 14 variable templates are supported (template<typename T> constexpr T pi = T(3.1415926535);)

C++ 14 lambda captures are supported (auto lambda = [value = 1] {return value;};)

C++ 14 deprecated is supported ([[deprecated]]int fdep(){return 5;})

But not fully:

C++ 14 digit separators are not supported (int j = 2'000;)

From these tests, it even seems to support some C++17:

Nested namespace definitions are supported (namespace X::Y {int func(){ return 1; } })

But also not fully:

UTF-8 characters are not supported (char x = u8'a';)

If it partially supports everything, is there an overview like a list or table where I can look it up?

It supports whatever the particular core and compiler you are using supports and is configured to support. Turn on verbose compilation and you will see the commands it is running including the command line flags (-std*, etc).

look around here https://arduino.github.io/arduino-cli/0.19/platform-specification/#recipes-to-compile-source-code

I expect your tests to give different results on different versions of Arduino IDE and different boards.

The Arduino "language" is nothing more than a set of C++ functions and classes. It does not mandate any particular C++ standard.
The standard is dictated purely by the compiler that the core you are using happens to support (and is configured to use through command line flags).
Different cores use different compilers. Different versions of the same core use different compilers. Different compilers provide different C++ standard levels.
Most cores use GCC or some variant thereof. That could be anything from GCC 3.x.x through to the most recent release (whatever that is this week).
Currently the AVR core uses GCC 7.3.0 and is configured to use the gnu++11 standard by default (though avr-gcc and the associated libraries lack a full STL implementation). You can of course change that in the configuration files if you want.

"nothing more than a set of C++ functions and classes" -> And the very important preprocessing, which is missing for example in PlatformIO.

@AndreKR That's not really part of the language - more a bit of convenience fudging that really shouldn't exist anyway (and until fairly recently was broken horribly anyway).

Without that preprocessing you would need something called "Header Guards", a technique so strange I find it hard to explain why it needs to exist.

@AndreKR No, that's wrong. All the preprocessing does is scrape your code for functions and insert prototypes for you at the top of your sketch. It does nothing with header guards, which is something you should always have in your header files regardless.

Arduino language isn't even fully C++11 because it doesn't support std::erf() in C99 and C++11. https://godbolt.org/z/dP1W1xfW6

@phuclv you're confusing the compiler and the STL which are two different things. True avr-gcc lacks the full STL but it is still C++11 (with GCC extensions) syntax.