title: Vacuum pressure sensor for Arduino

text:
# Question
Title: Vacuum pressure sensor for Arduino
I have an application that is being controlled by an Arduino. At one point in the process, it needs to determine the level of vacuum in a chamber and adjust it to within a range of values.

I can control the vacuum pumps easily enough, but it is hard to find a vacuum sensor for the Arduino. I need a sensor that can be reasonably accurate down to roughly 28 inches mercury and would connect by a tube. I can't put the sensor directly into the chamber.

Does anyone know of an Arduino sensor that would work? If not, could someone suggest a sensor component that may work with an Arduino. I would prefer to not have to engineer a solution from the sensor component up but I can if I need to.

# Answer
Industrial pressure/vacuum sensors are sturdy and rigid. They have extra protection, for example to use it submersible. The manufacturer often make them for certain voltages (for example 24v) and with different outputs (0..5v output, or 5-20ma output, and so on).
There are cheap versions of those sensors. They are between 5 and 20 dollars on Ebay and Aliexpress.
The manufacturers do not tell which sensor they use inside, and it can be hard to find a sensor that is exactly the one that you need.

The bare sensor is often a piezoresistive sensor in a wheatstone bride configuration. The output voltage span of those sensors is very low and not suitable to connect directly to an arduino board.
The advantage can be that they do not have a operating voltage. Only a maximum voltage.

The ideal pressure/vacuum sensor has a temperature compensation and a gain and a output span that is near 5v. You find most of them at nxp.com.
Luckely they have also a vacuum sensor with a large range, for example the MPXV6115V.

Those sensors are ratiometric. Power them with the arduino 5v and use the arduino 5v as analog reference (that is the Arduino default setting). When the 5v changes, the resulting measured pressure does not change and is still accurate.

Never solder something to the unused pins. Those pins can be connected to something inside.

There are a few ways to calculate the pressure. One way is to use the formula from the datasheet, the other way is to map the output voltage span to the pressure span and correct for the offset of the output voltage.
> 1 votes

---
Tags: sensors
---


# Question
Title: Interfacing AD7606 with Arduino Due. How to data-log?
I have an 16 bit ADC7606. It is in parallel mode. I have a working sketch that allows me to read 8 channels, convert the 16 bit integer to decimal and then serial prints to monitor. I would like to increase the frequency of the sampling rate. The serial monitor can not keep up with a sampling rate faster than 40millis. The Due is connected via USB on COM3.

How do I log the data to a file on my laptop/computer?

All and any help greatly appreciated.

Code below,

```
#include <EnableInterrupt.h>

#define BUSY 3
#define RD 4  //RD+CS tied together
#define RESET 5
#define CONVST 6 //CONVSTA+CONVSTB soldered together on the board
#define RANGE 7

#define DB0 38
#define DB1 39
#define DB2 40
#define DB3 41
#define DB4 42
#define DB5 43
#define DB6 44
#define DB7 45
#define DB8 46
#define DB9 47
#define DB10 48
#define DB11 49
#define DB12 50
#define DB13 51
#define DB14 52
#define DB15 53

// declare rawData as an array of 16 integers
int rawData[16];

void setup() {

  enableInterrupt(BUSY, ISR_, FALLING);

  pinMode(RESET, OUTPUT);
  pinMode(CONVST, OUTPUT);
  pinMode(RD, OUTPUT);
  pinMode(RANGE, OUTPUT);
  pinMode(BUSY, INPUT);

  Serial.begin(9600);

  //reset ADC to begin conversion
  digitalWrite(RESET, HIGH);
  delayMicroseconds(10);
  digitalWrite(RESET, LOW);

  digitalWrite(CONVST, LOW);
  digitalWrite(RD, HIGH);
  digitalWrite(RANGE, HIGH);
  digitalWrite(BUSY, LOW);

  delayMicroseconds(1000);

}

void loop() {

  disableInterrupt(BUSY);

  delayMicroseconds(40000);
  digitalWrite(CONVST, LOW);
  delayMicroseconds(10);
  digitalWrite(CONVST, HIGH);
  enableInterrupt(BUSY, ISR_, FALLING);

}

void ISR_ ()  {

  //Serial.print(millis());
  //Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);
  Serial.print(",");

  delayMicroseconds(1);
  digitalWrite(RD, LOW);
  delayMicroseconds(1);
  readDBpins(); // do read
  digitalWrite(RD, HIGH);

  Serial.println(" ");

}

void readDBpins()
{
  rawData[0] = digitalRead(DB15);
  //Serial.print (rawData[0]);
  if (rawData[0] > 0) {rawData[0] = 32768;}
  rawData[1] = digitalRead(DB14);
  //Serial.print (rawData[1]);
  if (rawData[1] > 0) {rawData[1] = 16384;}
  rawData[2] = digitalRead(DB13);
  //Serial.print (rawData[2]);
  if (rawData[2] > 0) {rawData[2] = 8192;}
  rawData[3] = digitalRead(DB12);
  //Serial.print (rawData[3]);
  if (rawData[3] > 0) {rawData[3] = 4096;}
  rawData[4] = digitalRead(DB11);
  //Serial.print (rawData[4]);
  if (rawData[4] > 0) {rawData[4] = 2048;}
  rawData[5] = digitalRead(DB10);
  //Serial.print (rawData[5]);
  if (rawData[5] > 0) {rawData[5] = 1024;}
  rawData[6] = digitalRead(DB9);
  //Serial.print (rawData[6]);
  if (rawData[6] > 0) {rawData[6] = 512;}
  rawData[7] = digitalRead(DB8);
  //Serial.print (rawData[7]);
  if (rawData[7] > 0) {rawData[7] = 256;}
  rawData[8] = digitalRead(DB7);
  //Serial.print (rawData[8]);
  if (rawData[8] > 0) {rawData[8] = 128;}
  rawData[9] = digitalRead(DB6);
  //Serial.print (rawData[9]);
  if (rawData[9] > 0) {rawData[9] = 64;}
  rawData[10] = digitalRead(DB5);
  //Serial.print (rawData[10]);
  if (rawData[10] > 0) {rawData[10] = 32;}
  rawData[11] = digitalRead(DB4);
  //Serial.print (rawData[11]);
  if (rawData[11] > 0) {rawData[11] = 16;}
  rawData[12] = digitalRead(DB3);
  //Serial.print (rawData[12]);
  if (rawData[12] > 0) {rawData[12] = 8;}
  rawData[13] = digitalRead(DB2);
  //Serial.print (rawData[13]);
  if (rawData[13] > 0) {rawData[13] = 4;}
  rawData[14] = digitalRead(DB1);
  //Serial.print (rawData[14]);
  if (rawData[14] > 0) {rawData[14] = 2;}
  rawData[15] = digitalRead(DB0);
  // Serial.print (rawData[15]);
  if (rawData[15] > 0) {rawData[15] = 1;}

  Serial.print (rawData[0]+rawData[1]+rawData[2]+rawData[3]+rawData[4]+rawData[5]+rawData[6]+rawData[7]+rawData[8]+rawData[9]+rawData[10]+rawData[11]+rawData[12]+rawData[13]+rawData[14]+rawData[15]);
}

```

# Answer
You can use python on the command line to log your serial monitor output. This is described here. The script below has a baud rate of `250000` but can be set according to how you program your arduino.

```
from time import sleep
import serial

# Change port and baud rate to match your setup
ser = serial.Serial('/dev/ttyACM0', 250000) # Establish the connection on a specific port

counter = 32 # Below 32 everything in ASCII is gibberish

while True:
     counter +=1
     ser.write(str(chr(counter))) # Convert the decimal number to ASCII then send it to the Arduino
     print(ser.readline()) # Read the newest output from the Arduino
     sleep(.1) # Delay for one tenth of a second
     if counter == 255:
         counter = 32

```

Script from here. You must put in your appropriate port and baud rate. This Mathworks link describes how to find your port number.

* In windows look in Device Manager under USB Serial Port.
* In linux or OSX open a terminal and search with `ls /dev/*` or `ls /dev/tty*`. You can `| grep <search>` on the same line to search `usb` or `ACM`

This is a discussion about maximum baud rate. I have gone up to `250000` on the Due's programming port but you can go faster using the native port. You may also be limited by your computer usb though unlikely. 480 Mbit/s max for USB 2.0.

> The Arduino Due has two USB ports available. The Native USB port (which supports CDC serial communication using the SerialUSB object) is connected directly to the SAM3X MCU. The other USB port is the Programming port. It is connected to an ATMEL 16U2 which acts as a USB-to-Serial converter. This Programming port is the default for uploading sketches and communicating with the Arduino.
>
> The USB-to-serial converter of the Programming port is connected to the first UART of the SAM3X. It's possible to communicate over this port using the "Serial" object in the Arduino programming language.
>
> The USB connector of the Native port is directly connected to the USB host pins of the SAM3X. Using the Native port enables you to use the Due as a client USB peripheral (acting as a mouse or a keyboard connected to the computer) or as a USB host device so that devices can be connected to the Due (like a mouse, keyboard, or an Android phone). This port can also be used as a virtual serial port using the "SerialUSB" object in the Arduino programming language.

From the Arduino Due guide you can switch `Serial.print` to `SerialUSB.print`, same with other serial functions like `println`. Then if you plug your usb into the Native port you can read off that port at a higher baud rate. You must also initialize the SerialUSB,

```
SerialUSB.begin(2000000);    // Initialize Native USB port
while(!SerialUSB);           // Wait until connection is established

```

It shouldn't matter what you set the baud rate at on the native port, it will run at the maximum bus speed but from what I know it has to be set regardless.

When running on the command line you can use `>` to send the output to a log file.

For example,

```
python serial_log.py > out.txt

```
> 2 votes

---
Tags: datalogging
---


# Question
Title: what the benefit uploading hex file merely to arduino board?
What the benefit of uploading merely hex file to avr based board like arduino uno Since the arduino ide it self will send intel hex file to the board after compile .ino file to hex file by the avrdude compiler (https://github.com/arduino/Arduino/wiki/Build-Process)?

# Answer
> 1 votes
If you want to upload the same sketch to many Arduinos compiling it again and again would take much longer. Or if you create a firmware ànd don't want to disclose the source code, you can distribute it in compiled form.

---
Tags: arduino-ide
---


# Question
Title: Arduino sketch for NodeMCU v1.0 (ESP8266-12E) has no error of compiling but does not run on NodeMCU v1.0 (ESP8266-12E) Board
i compiled a Arduino Sketch for NodeMCU v1.0 (ESP8266-12E) which have no error while i test with verifiy button in Arduino IDE 1.8.6 but i don't know what is the problem when i upload and test it . it \[ NodeMCU v1.0 (ESP8266-12E) \] is not showing an static IP address while there is turned ON WiFi hotspot from my android phone. I'm sharing two codes (code 1, code 2) here. Code 2 connect to the WiFi Hotspot but i make changes in code 2 to make code 1 for desired output which is not working. Need help for making proper code.

code 1

```
#include <ESP8266WiFi.h>

int pin1 = 2; // GPIO 14 (D5)
int pin2 = 3; // GPIO 5 (D1)
int pin3 = 6; // GPIO 5 (D2)

  const char* ssid = "wifi";
   const char* password = "12345678";

  WiFiServer server(80);

void setup()
{

  Serial.begin(115200);
  delay(10);

  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(6, OUTPUT);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

// Start the server
  server.begin();
  Serial.println("Server started");

// Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
  return;
}

// Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
  delay(1);
}

// Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
// Match the request
  int value = LOW;
  if (request.indexOf("/pin1=ON") != -1) {
  digitalWrite(2, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin1=OFF") != -1) {
  digitalWrite(2, LOW);
  value = LOW;

}

  if (request.indexOf("/pin2=ON") != -1) {
  digitalWrite(3, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin2=OFF") != -1) {
  digitalWrite(3, LOW);
  value = LOW;

}

  if (request.indexOf("/pin3=ON") != -1) {
  digitalWrite(6, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin3=OFF") != -1) {
  digitalWrite(6, LOW);
  value = LOW;

}

// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
// Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println("<head>");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
  client.println("</head>");
  client.println("<body bgcolor = \"#f7e6ec\">");
  client.println("<hr/><hr>");
  client.println("<h4><center>Wifi Based Project</center></h4>");
  client.println("</center>");
  client.println("<hr/><hr>");
  client.println("<center>");
  client.println("<a href=\"/a\"\"><button>Data </button></a><br />");
  client.println("</center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("Load 1");
  client.println("<a href=\"/l1on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/l1off\"\"><button>Turn Off </button></a><br />");
  client.println("</center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("Load 2");
  client.println("<a href=\"/l2on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/l2off\"\"><button>Turn Off </button></a><br />");
  client.println("</center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("Load 3");
  client.println("<a href=\"/l3on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/l3off\"\"><button>Turn Off </button></a><br />");
  client.println("</center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("<table border=\"5\">");
  client.println("<br><br>");
  client.println("<tr>");

  if(digitalRead(pin1)){client.print("<td>Load 1 is ON</td>");}
  else{client.print("<td>Load 1 is OFF</td>");}

  if(digitalRead(pin2)){client.print("<td>Load 2 is ON</td>");}
  else{client.print("<td>Load 2 is OFF</td>");}

  if(digitalRead(pin3)){client.print("<td>Load 3 is ON</td>");}
  else{client.print("<td>Load 3 is OFF</td>");}

  client.println("</tr>");
  client.println("</table>");
  client.println("</center>");
  client.println("</html>");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

```

if you will upload this code in your NodeMCU v1.0 (ESP8266-12E) , this will connect with your Android phone. You can consider it, code 2 and above code 1.

code 2

```
#include <ESP8266WiFi.h>

int pin1 = 14; // GPIO 14 (D5)
int pin2 = 5; // GPIO 5 (D1)
int pin3 = 4; // GPIO 5 (D2)

const char* ssid = "wifi";
const char* password = "12345678";

WiFiServer server(80);

void setup()
{

Serial.begin(115200);
delay(10);

pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);

// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");

}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

if (request.indexOf("/l1on") > 0)  {
digitalWrite(pin1, HIGH);

}
if (request.indexOf("/l1off") >0)  {
digitalWrite(pin1, LOW);

}

if (request.indexOf("/l2on") > 0)  {
digitalWrite(pin2, HIGH);

}
if (request.indexOf("/l2off") >0)  {
digitalWrite(pin2, LOW);

}
if (request.indexOf("/l3on") >0)  {
digitalWrite(pin3, HIGH);

}
if (request.indexOf("/l3off") > 0)  {
digitalWrite(pin3, LOW);

}

// Set ledPin according to the request
//digitalWrite(ledPin, value);

// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); //  do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("</head>");
client.println("<body bgcolor = \"#f7e6ec\">");
client.println("<hr/><hr>");
client.println("<h4><center>Wifi Based Project</center></h4>");
client.println("</center>");
client.println("<hr/><hr>");
client.println("<center>");
client.println("<a href=\"/a\"\"><button>Data </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 1");
client.println("<a href=\"/l1on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/l1off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 2");
client.println("<a href=\"/l2on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/l2off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 3");
client.println("<a href=\"/l3on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/l3off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("<br><br>");
client.println("<center>");
client.println("<table border=\"5\">");
client.println("<br><br>");
client.println("<tr>");

if(digitalRead(pin1)){client.print("<td>Load 1 is ON</td>");}
else{client.print("<td>Load 1 is OFF</td>");}

if(digitalRead(pin2)){client.print("<td>Load 2 is ON</td>");}
else{client.print("<td>Load 2 is OFF</td>");}

if(digitalRead(pin3)){client.print("<td>Load 3 is ON</td>");}
else{client.print("<td>Load 3 is OFF</td>");}

client.println("</tr>");
client.println("</table>");
client.println("</center>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");

}

```

# Answer
> 0 votes
You can't use io 6. IO 6 is for internal use to connect the flash memory to esp8266. IO 6 has no Dx pin on the board. And io 3 is Serial RX connected to USB.

Use `Dx` constants and the corresponding 'D' labeled pins of the NodeMcu. (and remove conflicting comments)

```
const int pin1 = D2;
const int pin2 = D3;
const int pin3 = D6;

```

pin D3 is io 0 used to put the board into flashing mode. do not connect there something that pulls the pin LOW at reset or power-up

---
Tags: esp8266, nodemcu, iot
---


# Question
Title: "exit status 1" error when invoking "useInterrupt" method
for context to this post you can catch up on this post

I am working with an Arduino Leonardo and Adafruit Music Maker shield.

I am trying to use the `startPlayingFile` method via the interrupt pin but I am getting a `exit status 1` error when instantiating the interrupt pin. I have pin pointed the error down this one statement. If I comment this statement out, the sketch compiles.

```
if (! musicPlayer1.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
    Serial.println(F("DREQ pin is not an interrupt pin"));

```

The frustrating thing is that this is also the case with the example sketch "player\_interrupts" provided by Adafruit.

Does anyone have a clue as to what is causing this compile error?

---

Here's my code which is a slightly simplified version of the example sketch

```
// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

// These are the pins used for the breakout example
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)

// These are the pins used for the music maker shield
//SHIELD 1
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define DREQ          3       // VS1053 Data request, ideally an Interrupt pin

// SHIELD 2
#define SHIELD_CS_2     5      // VS1053 chip select pin (output)
#define SHIELD_DCS_2    2      // VS1053 Data/command select pin (output)
#define DREQ_2          0       // VS1053 Data request, ideally an Interrupt pin

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt

  Adafruit_VS1053_FilePlayer musicPlayer1 = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
  Adafruit_VS1053_FilePlayer musicPlayer2 = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_2, SHIELD_DCS_2, DREQ_2, CARDCS);
//  Adafruit_VS1053_FilePlayer musicPlayer3 = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_3, SHIELD_DCS_3, DREQ_3, CARDCS);

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

  if (! musicPlayer1.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053_1, do you have the right pins defined?"));
     while (1);
  }

  Serial.println(F("VS1053 found"));

  musicPlayer1.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working
  musicPlayer2.sineTest(0x44, 500);

  if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }
  Serial.println("SD OK!");

  // list files
  printDirectory(SD.open("/"), 0);

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer1.setVolume(20,20);
  musicPlayer2.setVolume(20,20);

  /***** Two interrupt options! *******/
  // This option uses timer0, this means timer1 & t2 are not required
  // (so you can use 'em for Servos, etc) BUT millis() can lose time
  // since we're hitchhiking on top of the millis() tracker
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT);

  // This option uses a pin interrupt. No timers required! But DREQ
  // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla
  // that's Digital #2 or #3
  // See http://arduino.cc/en/Reference/attachInterrupt for other pins
  // *** This method is preferred
  if (! musicPlayer1.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
    Serial.println(F("DREQ pin is not an interrupt pin"));

//     if (! musicPlayer2.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
//    Serial.println(F("DREQ pin is not an interrupt pin"));
}

void loop() {
  // Alternately, we can just play an entire file at once
  // This doesn't happen in the background, instead, the entire
  // file is played and the program will continue when it's done!
//  musicPlayer1.playFullFile("track001.mp3");

  // INTERRUPT
  // StartS playing a file, then we can do stuff while waiting for it to finish
  musicPlayer1.startPlayingFile("track002.mp3");
//  musicPlayer2.startPlayingFile("track002.mp3");

}

/// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

```

---

This is the output of the compiler which seems to show the error happening at "Linking everything together..."

```
Arduino: 1.8.7 (Windows Store 1.8.15.0) (Windows 10), Board: "Arduino Leonardo"

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\tools-builder -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -built-in-libraries C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries -libraries C:\Users\edwar\Documents\Arduino\libraries -fqbn=arduino:avr:leonardo -ide-version=10807 -build-path C:\Users\edwar\AppData\Local\Temp\arduino_build_927460 -warnings=none -build-cache C:\Users\edwar\AppData\Local\Temp\arduino_cache_535084 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -verbose C:\Users\edwar\Documents\Arduino\Test_simul_play\Test_simul_play.ino
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\arduino-builder -compile -logger=machine -hardware C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\tools-builder -tools C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -built-in-libraries C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries -libraries C:\Users\edwar\Documents\Arduino\libraries -fqbn=arduino:avr:leonardo -ide-version=10807 -build-path C:\Users\edwar\AppData\Local\Temp\arduino_build_927460 -warnings=none -build-cache C:\Users\edwar\AppData\Local\Temp\arduino_cache_535084 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr -verbose C:\Users\edwar\Documents\Arduino\Test_simul_play\Test_simul_play.ino
Using board 'leonardo' from platform in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr
Detecting libraries used...
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o nul
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\libraries\\SPI\\src" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o nul
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\libraries\\SPI\\src" "-IC:\\Users\\edwar\\Documents\\Arduino\\libraries\\Adafruit_VS1053" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o nul
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\libraries\\SPI\\src" "-IC:\\Users\\edwar\\Documents\\Arduino\\libraries\\Adafruit_VS1053" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\libraries\\SD\\src" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o nul
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SPI\src\SPI.cpp
Using cached library dependencies for file: C:\Users\edwar\Documents\Arduino\libraries\Adafruit_VS1053\Adafruit_VS1053.cpp
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD\src\File.cpp
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD\src\SD.cpp
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD\src\utility\Sd2Card.cpp
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD\src\utility\SdFile.cpp
Using cached library dependencies for file: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD\src\utility\SdVolume.cpp
Generating function prototypes...
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\libraries\\SPI\\src" "-IC:\\Users\\edwar\\Documents\\Arduino\\libraries\\Adafruit_VS1053" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\libraries\\SD\\src" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\preproc\\ctags_target_for_gcc_minus_e.cpp"
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\preproc\\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 "-DUSB_MANUFACTURER=\"Unknown\"" "-DUSB_PRODUCT=\"Arduino Leonardo\"" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\variants\\leonardo" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\arduino\\avr\\libraries\\SPI\\src" "-IC:\\Users\\edwar\\Documents\\Arduino\\libraries\\Adafruit_VS1053" "-IC:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\libraries\\SD\\src" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp" -o "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp.o"
Compiling libraries...
Compiling library "SPI"
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SPI\SPI.cpp.o
Compiling library "Adafruit_VS1053"
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\Adafruit_VS1053\Adafruit_VS1053.cpp.o
Compiling library "SD"
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SD\File.cpp.o
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SD\SD.cpp.o
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SD\utility\Sd2Card.cpp.o
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SD\utility\SdVolume.cpp.o
Using previously compiled file: C:\Users\edwar\AppData\Local\Temp\arduino_build_927460\libraries\SD\utility\SdFile.cpp.o
Compiling core...
Using precompiled core: C:\Users\edwar\AppData\Local\Temp\arduino_cache_535084\core\core_arduino_avr_leonardo_83dd9225a3a2a4e5654b35f3e742d65a.a
Linking everything together...
"C:\\Program Files\\WindowsApps\\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega32u4 -o "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460/Test_simul_play.ino.elf" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\sketch\\Test_simul_play.ino.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SPI\\SPI.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\Adafruit_VS1053\\Adafruit_VS1053.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SD\\File.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SD\\SD.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SD\\utility\\Sd2Card.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SD\\utility\\SdFile.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460\\libraries\\SD\\utility\\SdVolume.cpp.o" "C:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460/..\\arduino_cache_535084\\core\\core_arduino_avr_leonardo_83dd9225a3a2a4e5654b35f3e742d65a.a" "-LC:\\Users\\edwar\\AppData\\Local\\Temp\\arduino_build_927460" -lm
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SPI\src\SPI.cpp: In function 'begin':

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SPI\src\SPI.cpp:64:1: internal compiler error: Segmentation fault

 }

 ^

Please submit a full bug report,

with preprocessed source if appropriate.

See <http://gcc.gnu.org/bugs.html> for instructions.

lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status

compilation terminated.

c:/program files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed

collect2.exe: error: ld returned 1 exit status

Using library SPI at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SPI
Using library Adafruit_VS1053 at version 1.0.5 in folder: C:\Users\edwar\Documents\Arduino\libraries\Adafruit_VS1053
Using library SD at version 1.2.2 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\libraries\SD
exit status 1
Error compiling for board Arduino Leonardo.

```

# Answer
The code is OK. It compiles in IDE 1.8.6. You have some strange version of IDE and the compiler crashes with "internal compiler error: Segmentation fault"
> 1 votes

---
Tags: interrupt, arduino-leonardo, adafruit, audio, compilation-errors
---


# Question
Title: Arduino tool to enumerate where RAM is being used?
In a sketch I have, I use a few libraries and have discovered that a large amount of RAM is being consumed.

Is there a tool that can identify how this RAM is being allocated, e.g. which libraries, which piece of code?

# Answer
> 2 votes
I use this code for Heap memory of AVR (UNO, Mega, etc.):

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

```

To show heap memory just use `Serial.print("Write here a name of the function from which you print it"); Serial.println(freeRam());` anywhere in the code.

Compiler shows stack memory but not the heap, so this code helps me to find exact place where my program uses too much of heap memory. I just print it in every suspicious place in my code.

I hope this will help.

---
Tags: memory
---


title: Autoranging ohmmeter

text:
# Question
Title: Autoranging ohmmeter
Note: Before i explain my issue i would like to note that I am a beginner in electronics. Please pay attention to that when providing solutions and explanations. Thank you.

I have succeeded at making an auto ranging Ohmmeter it is still ofcours experimental there for I would like to get some opinions and perhaps solutions to some of the issues I’m facing How it works:

It is based on a simple voltage divider. After experimenting it seems that a voltage drop across the unknown resistor in a certain range (this case \[3.135V, 0.99V\] with a voltage source equal to 3.3V) gives the most precise results compared to other values.

This Ohmmeter has a very useful feature and that is auto ranging, it changes the range automatically when the voltage drop values are not in the previously mentioned interval (\[3.135V, 0.99V\]). The accompanied image shows how the device works.

If the value of Rx is too small compared to (R1+R2+R3) the Arduino switches the analog reading from A0 to A1 if the problem still accurse the Arduino will change again to A2 meaning it is now measuring not the value of Rx but (Rx+R1+R2) in series after that the Arduino is programmed to do the subtraction accordingly.

This device presents some noticeable inconvenients that need to be eliminated:

1. It depends on experimental values, so it is not certain if it’ll function properly in different conditions.
2. For accurate (still not exact) measurements the value of Rx has to be greater than R1
3. It provides acceptable measurements compared to the actual value with an error that is not too big (less than 1% relative error) the precision was obtained by the use of some of the arduino functions (such as voltage reference) also I have chosen the voltage source to be 3.3V instead of 5V to reduce noise, now if one wishes to use a different microcontroller other than arduino will it still be possible to obtain the same precision.

I would like to know your professional opinion regarding these inconvenients and if you may solutions for them, I have accompanied the code for better understanding.

# Thank you

```
#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analogPin0(A0, true);
ResponsiveAnalogRead analogPin1(A1, true);
ResponsiveAnalogRead analogPin2(A2, true);

int raw1= 0,raw2=0,raw3=0;
int Vin= 3.3;
float Vout1= 0,Vout2=0,Vout3=0;

float R1= 10000,R2=100000,R3=1000000;
float Rx= 0;
float buffer= 0;

void setup()
{
  analogReference(EXTERNAL);

Serial.begin(9600);
}

void loop()
{
  analogPin0.update();
  analogPin1.update();
  analogPin2.update();
raw1=analogPin0.getValue();
buffer= raw1 * Vin;
Vout1= (buffer)/1024.0;
if(Vout1<=3.135&&Vout1>=0.99) //firstif
{

buffer= (Vin/Vout1) -1;
Rx= (R1+R2+R3) * buffer;
Serial.print("Vout1: ");
Serial.println(Vout1);
Serial.print("Rx: ");
Serial.println(Rx);
delay(1000);
}
   else //else1 of first if
   {

   raw2=analogPin1.getValue();
   buffer= raw2 * Vin;
   Vout2= (buffer)/1024.0;
      if(Vout2<=3.135&&Vout2>=0.99) //second if of first else
      {
      buffer= (Vin/Vout2) -1;
      Rx= (R2+R3) * buffer;
      Rx=Rx-R1;
      Serial.print("Vout2: ");
      Serial.println(Vout2);
      Serial.print("Rx: ");
      Serial.println(Rx);
      delay(1000);
      }
      else
      {
      raw3=analogPin2.getValue();
      buffer= raw3 * Vin;
      Vout3= (buffer)/1024.0;
          if(Vout3<=3.135&&Vout3>=0.99)
          {
          buffer= (Vin/Vout3) -1;
          Rx= R3 * buffer;
          Rx=Rx-(R1+R2);
          Serial.print("Vout3: ");
          Serial.println(Vout3);
          Serial.print("Rx: ");
          Serial.println(Rx);
          delay(1000);
          }
       }
   }
}

```

======================================================

to jot here are the results as i have previously explained the ohmmeter worked pretty well at the beginning but when i turned it off Then back on the value measured changed, the error got much bigger i tried changing the caliber aka R1 from 220 to 100 but the results were the same, the error was still big thank you

# Answer
The answer by @EdgarBonet seems to be a very nice solution for the lowered output voltage of a pin, when a low resistor value is used.

A arduino uno pin can output 20mA without problem, even up to 40mA if needed. So a safe value to measure low resistor values is 220 ohm, which could result in a maximum of 23mA.

Analog input A1 is used both as digital output to power the circuit and also as a analog input to measure how much the voltage has dropped.

This is a quick test:

```
// Using the idea in the answer by Edgar Bonet
//
// Allow that the voltage of a digital output is
// lowered by the low resistor value,
// to calculate the unknown resistor.
//
// With two resistors in series.
// A1 - 220 ohm - A0 - 10 ohm - GND
//
// The circuit is a voltage divider.
// A1 powers the voltage divider.
// A0 measures the output.

#define R1 220
#define N_SAMPLES 10

void setup() {
  Serial.begin(9600);
  pinMode(A1,OUTPUT);
  digitalWrite(A1, HIGH);
}

void loop() {

  // Pin A1 is already set as a digital output and set HIGH.
  // Using analogRead(A1) is to measure the real output
  // voltage. There is a voltage drop, because of the current.
  float Vin = averageRead(A1);
  Serial.print("Vin=");
  Serial.print(Vin);

  float Vout = averageRead(A0);
  Serial.print(" Vout=");
  Serial.print(Vout);

  if(Vin > 0.0 && Vout < Vin) {
    float Vt = Vout / Vin;
    float Rx = (Vt * R1) / (1 - Vt);
    Serial.print(" Rx=");
    Serial.println(Rx);
  }

  delay(500);
}

float averageRead(int analogPin) {
  int total = 0;
  for(int i=0; i<N_SAMPLES; i++) {
    total += analogRead(analogPin);
  }
  return float(total) / N_SAMPLES;
}

```

That is very nice. It is no problem when the unknown resistor is 10 ohm.

Because of the low resistor values, I did not add delays. With high resistor values, some delay is needed before measuring the analog values.

The next step is to find the best value by finding the value that is the most in the middle, as Edgar Bonet has explained in his answer.

```
// Autoranging by finding the value that is most in the middle.
// Using the answer by Edgar Bonet

#define N_SAMPLES 10          // the number of samples to average, maximum 30

// Four resistors to power the circuit (one at a time).
// A1 has a resistor of 220 ohm, A2 has 3k3, A3 47k, and A4 750k
// The other leg of the resistors are all connected to A0.
// The unknown resistor Rx is at pin A0 and GND.
const float R[4] = {220.0, 3300.0, 47000.0, 750000.0};
const int pinR[4] = {A1, A2, A3, A4};
const unsigned long wait[4] = {1, 2, 4, 10};  // delay, values guessed.
const int pinMeasure = A0;

void setup() {
  Serial.begin(9600);
  Serial.println("Autoranging");
}

void loop() {
  float Vin[4];    // Vin is the pin that powers the circuit
  float Vout[4];   // Vout is the voltage over the unknown resistor

  for(int i=0; i<4; i++) {
    // Power the circuit with this resistor
    pinMode(pinR[i], OUTPUT);
    digitalWrite(pinR[i], HIGH);

    // Vin is the pin that powers the circuit.
    // This is always low impedance, no need to wait.
    Vin[i]  = averageRead(pinR[i]);

    // Extra delay to wait for the voltage to become steady,
    // before reading the analog data.
    // Might be needed for the higest resistor values
    // Perhaps there is a cable to the unknown resistor
    // that has capacitance.
    delay(wait[i]);

    // The first 'analogread()' sets the multiplexer.
    // For a high impedance circuit, the first
    // 'analogread()' might be less acurate.
    // Read it a few times, and throw it away.
    averageRead(pinMeasure);

    // Everything is settled by now.
    // Read the analog input for real.
    Vout[i] = averageRead(pinMeasure);

    pinMode(pinR[i], INPUT);  // Make this pin high impedance
  }

  // Find the value for Vout that is the most in the middle.
  // For an Arduino Uno, the middle ADC value is 512.
  float diff = 2000.0; // set to value higher than possible as default
  int best = 0;        // index of the best resistor

  for(int i=0; i<4; i++) {
    float d = fabs(512.0 - Vout[i]); // difference for this resistor
    if(d < diff) {                   // closer to the middle?
      diff = d;                      // remember new difference
      best = i;                      // remember index best resistor
    }
  }

  if(Vin[best] <= 0.0) {
    Serial.println("Something wrong with the circuit");
  }
  else if(Vout[best] >= Vin[best]) {
    Serial.println("Rx not connected");
  }
  else {
    float Vt = Vout[best] / Vin[best];     // temporary precalculation
    float Rx = (Vt * R[best]) / (1 - Vt);  // calculate unknown resistor

    Serial.print(" Rx=");
    Serial.print(Rx);
    Serial.print(" ohm (with resistor ");
    Serial.print(R[best]);
    Serial.print(")");
    Serial.println();
  }

  delay(250);
}

float averageRead(int analogPin) {
  int total = 0;
  for(int i=0; i<N_SAMPLES; i++) {
    total += analogRead(analogPin);
  }
  total += N_SAMPLES / 2;  // see www.gammon.com.au/adc
  return(float(total) / float(N_SAMPLES));
}

```

I would like to add a capacitor from A0 to GND (parallel with the unknown resistor) to reduce noise. This capacitor should be 1nF or less. The delay in the code is large enough to wait for the voltage to settle with 1nF.

The increase of the resistors by 15 times is a large step. That makes it less accurate, but the arduino uno has only 6 analog inputs. By using 5 resistors with an increase of 6 times is better.
4 resistors 15x : 220, 3k3, 47k, 750k
5 resistors 6x : 220, 1k2, 8k2, 47k, 270k

There are a few ways to do more:

* When two resistors result in a output that is close to the middle, it is possible to average the results.
* When the 5 resistors are used, it is for example possible to lower the value of the 8k2 resistor. When all higher values are turned on, the resulting resistor value becomes 6k8 instead of 8k2.
* For high resistor values, the output voltage of a pin is not lowered, and digital outputs can be used as well.

An protection resistor for A0 might be needed. I think that a value of 470 ohm or 1k should be fine.

**Many thanks to @EdgarBonet**, I used his answer and added the average and the delay.

---

Update November 2018

@RekaiaDraoui

When using a breadboard, there can be contacts which are not perfect. That can cause a lot of troubles.

Are you using a circuit as this:
> 2 votes

# Answer
As you probably already know, the standard setup for measuring a resistance with an Arduino is to put the unknown resistor in series with a known one between 5V and GND, and measure the voltage at the point in-between them:

```
     5V
     │
     R₁
 A0 ─┤
     R
     │
    GND

```

where R is the unknown resistor and R1 is the known reference. The resistance is then computed as:

```
const float R1 = ...;  // reference resistance

int reading = analogRead(A0);
float R = (float) reading / (1024 - reading) * R1;

```

First, it is worth noting that the reference voltage does not appear in this calculation. You could, of course, do the calculation in terms of voltage, but you should then notice that the reference voltage can be simplified away. This is not surprising if you realize than the ADC of the Arduino does not actually measure a voltage: it rather measures a voltage *ratio*: the ratio of the input voltage to the reference voltage. This ratio can then be easily related to the resistance ratio R/R1. What all this implies is that you should not expect to get better accuracy by using a 3.3 V reference rather than 5 V. Any inaccuracy in the voltage reference is irrelevant to the measurement of the resistance.

Next, when measuring a physical quantity, you are almost always interested in the *relative* rather than the *absolute* accuracy. From the equation above, it can be easily shown that you get the best relative resolution when the reading is near the middle of the ADC range:

```
raw reading    │   64 │  128 │  256 │  512 │  768 │  896 │  960
───────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────
resolution (%) │ 1.67 │ 0.89 │ 0.52 │ 0.39 │ 0.52 │ 0.89 │ 1.67

```

This is consistent with your observations, and it means that the reference resistor should ideally have a value that is of the same order as the unknown resistor.

Now, for the autoranging, I would advise you against putting all your reference resistors in series. With this setup, you always have the same voltage across the unknown resistor, irrespective of what range you choose. Reading a different input does not help. You may find out that the voltage between R1 and R2 gives a better reading (closer to mid-range), and you get a better accuracy on the measurement of R+R1. However, when you subtract R1 you are immediately degrade the *relative* accuracy of the result. In the end you cannot really improve the accuracy this way.

What I suggest is to put the reference resistors in parallel instead of in series, and power each one from an analog pin:

```
     A1  A2  A3
     │   │   │
     R₁  R₂  R₃
 A0 ─┼───┴───┴── ...
     R
     │
    GND

```

You then use these analog pins in digital mode: all of then in `INPUT` mode, except one which is set to `OUTPUT` `HIGH`. You can try all of them in turn and select whichever gives a result closer to mid-range. Or you can implement a smarter algorithm that finds the optimal one without trying them all.

There is something to be aware of with this setup: the pins have an output resistance that is about 25 Ω, which ends up being in series with the corresponding reference resistors. You can account for that by adjusting, in your code, the values of those references. But then that output resistance is not very well known, and can vary with temperature. This should only be an issue when you are in the low ranges though. You can mitigate this problem by measuring the voltage at the pin that is currently pulling up, and replacing `1024` in the equation for R by that reading. That's why I suggest to use analog instead of digital pins.

Finally, there are a couple of limitations that you should be aware of when measuring resistances with the Arduino ADC. At the low end of the resistance range, you cannot use a reference resistor with a very low value, because you have to make sure you do not pull more than about 20 mA from the pin that pulls up. Your smallest reference may then end up being somewhere around 220 Ω, and you will loose significant accuracy when you try to measure anything below 50 Ω. At the upper end of the range, you should be aware that the ADC is meant to measure voltage sources with an output resistance no larger than 10 kΩ, otherwise you risk cross-talk between the ADC channels. Then your higher reference should probably be 10 kΩ, and any measurement above 50 kΩ will give poor accuracy. Going past these limitations would require extra electronics, like a good-quality op-amp to “condition” the signal into something that the ADC can reliably measure.
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: Output set to 'low' when new variable in buffer
I would like to turn on and off the output of two pins on my arduino independently from each other. However, so far all my attempts have failed.

My current idea is to save the status (which I chose to be 0 as 'low' and 'high' as 1) of each of the pins in an integer array and then change the status of the pin depending of the entry in the variable. However, the entries in the variable are always set back to 0 and I do not know why this is happening.

This is my arduino code

```
const byte numChars = 32;
byte receivedChars[numChars];
boolean newData = false;
const int num_of_pins=2;
int output_pins[num_of_pins]={22,26};
int status_pins[num_of_pins]={0,0};

void setup() {
    int ii=0;
    Serial.begin(9600);
    for(ii=0; ii<num_of_pins; ii++){
        pinMode(output_pins[ii],OUTPUT);
    }

}

void loop() {
    recvWithStartEndMarkers();
    chooseFunction();
}

void chooseFunction(){
  if (receivedChars[0]==0){
    shutter();
    }
}

void shutter(){
        // get number of pin
        int pin_number_rcvd;
        int ii;
        int pin_status_rcvd;
        pin_number_rcvd=receivedChars[1];
        pin_status_rcvd=receivedChars[2];
        //check all status of pins and turn on and off
        for (ii=0; ii<num_of_pins; ii++){
          if (pin_number_rcvd==output_pins[ii]){
            status_pins[ii]=pin_status_rcvd;
          }
          if (status_pins[ii]==0){
            digitalWrite(output_pins[ii],LOW);
          }
          if (status_pins[ii]==1){
            digitalWrite(output_pins[ii],HIGH);
          }
        }
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    byte startMarker = 8;
    byte endMarker = 9;
    byte rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

```

I use pyserial to send the input data to the arduino. my python code:

```
import serial
import time, struct, sys
ser=serial.Serial('COM17', 9600, timeout=10)
time.sleep(2)
ser.reset_input_buffer()
ser.reset_output_buffer()
pin_number= int(sys.argv[1])
high_or_low=int(sys.argv[2])

ser.write(struct.pack('>5B',8,1,pin_number,high_or_low,9))

```

I am using an ArduinoDue together with the arduino IDE.

# Answer
> 1 votes
Your problem is in one tricky option for arduino's com connection. When you reopen COM port where arduino is connected your arduino resets automatically.

**Here's workaround from arduino.cc:**

> **DisablingAutoResetOnSerialConnection**
>
> The simple way that doesn't require any permanent modifying of your hardware or software configuration changes:
>
> Stick a 120 ohm resistor in the headers between 5v and reset (you can find these on the isp connector too). 120 is hard to find so just combine resistors. Don't go below 110 ohms or above 124 ohms, and don't do this with an isp programmer attached. You can just pull out the resistor when you want auto-reset back.

http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

Or you can just modify you script to be able to start over without reopening it. For example use a loop there and some exit command to end that loop:

```
try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

```

https://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke Replace `do_something()` with this part of your code:

```
ser.reset_input_buffer()
ser.reset_output_buffer()
pin_number= int(sys.argv[1])
high_or_low=int(sys.argv[2])

ser.write(struct.pack('>5B',8,1,pin_number,high_or_low,9))

```

I hope I was clear enough.

---
Tags: arduino-due, python
---


# Question
Title: How to prevent interference between dc motor and arduino?
It may be already asked question in somewhere but I am struggling!

I have a four wheel robot which I want to drive it to perform 90-degree left/right turn, I am using the **MPU6050 3dof** to get angles, however everything is ok when the DC motors are off and the readings from the **MPU6050** are pretty good.

But when the DC motors are on, the readings start to be increase randomly. I tried to use a different power supply to the DC motors and the Arduino, but with no solution. At the end when I reset the Arduino everything was back to be normal even if the DC motors are on!

Any help will be appreciated and I am open for any suggestion.

# Answer
There are two basic things you need to do:

1. Use proper pullup resistors on your I2C lines (2.2kΩ) instead of relying on the (terrible) internal pullups of the ATMega
2. Add capacitors to the motors.

For point 2 you need two or three small ceramic capacitors (10nF to 100nF) per motor.

* Connect one from each terminal to the motor's body
* Optionally connect a third between the two terminals of the motor

This will reduce the EMI produced by the motor, and the improved pullups should reject EMI easier.

(Even if this doesn't entirely fix your underlying issue, it's certainly something that you *should* do regardless.)
> 2 votes

# Answer
You can just change ground port for your MPU6050 or for your motors(experiment with different choices). You have another ground port near pin13. As far as I know some of them are for analog devices and some of them are for digital (to avoid interference). Adding capacitors may not help. If none of the methods will help, try to add an inductor to your circuit.

Please, try that and write here if these were helpful or not.

**Update:** As per this site the problem is caused by data cables.

> Thank you a lot !
>
> Didn't have to change frequency. I just **eliminated SDA and SCL** wires and **plugged** a chip with **MPU-6050 directly into Arduino** and it works without any problems. Thanks to you this issue is solved :)

In addition, I would like to mention that Arduino standard pin cables are very noisy, so all connected modules which use high data rates or which are very sensitive to data errors (for example, nRF24L01+) will have strange behavior.

**Temporary and harsh workaround:** You could reset your Arduino after first initialization process (at the end of setup) then, save a flag("1") to EEPROM so it will not reset each time you start Arduino (warning: EEPROM cells can be rewritten only 10000 times).

```
if(EEPROM.read(0))
{
  EEPROM.write(0,1);
  //put your reset code here
}

if(EEPROM.read(1))
{
  EEPROM.write(0,0); //make it back "0" for next start
}

```
> 1 votes

---
Tags: motor, interrupt, mpu6050
---


# Question
Title: NRF24L01+ - After stopListening, can't write data
Okay so this is the code for my receiver.

This is quite confusing so let's dub Receiver = `DEVICE 1` and Transmitter = `DEVICE 2`

`DEVICE 1`: NRF24L01+, HC-05 (Bluetooth)

`DEVICE 2`: NRF24L01+

So `DEVICE 1` will receive data from `DEVICE 2`. Also When it receives data from my phone that is connected to the HC-05 module, it will `radio.StopListening` and `radio.write`.

But for some reason, after i do `radio.StopListening`, `radio.write` doesnt work.

Currently, `DEVICE 2` has a very simple code to receive data being sent from `DEVICE 1`. I've done this just to check if there's any data being sent when `DEVICE 1`'s HC-05 module receives data.

Code:

```
#include "Arduino.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 radio(9, 8);

byte addresses[][6] = {"1Node","2Node"};

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_2MBPS);
  radio.setChannel(124);

  // Open a writing and reading pipe on each radio, with opposite addresses
  radio.openWritingPipe(addresses[0]);
  radio.openReadingPipe(1, addresses[1]);
}

void loop() {
  unsigned char rf_data; //Make a variable to store the data
  unsigned char bt_data;
  unsigned char tosend;
  radio.startListening();

  if (radio.available()){
    while (radio.available()){
      radio.read(&rf_data, sizeof(rf_data));
      Serial.println(rf_data);
      }
    }

  if (Serial.available()>0){
    while (Serial.available()>0){
      bt_data = Serial.read();
      radio.stopListening();
      Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
      radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
      }
    }

}

```

I've added comments to show which part works and which part doesn't

I hope this question isn't too hard to understand.

# Answer
There could be few reasons but, firstly I would like to ask you to check if your write command is working at all. Try to disable reading mode and leave just write mode:

```
#include "Arduino.h"
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 radio(9, 8);

byte addresses[][6] = {"1Node","2Node"};

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_2MBPS);
  radio.setChannel(124);

  // Open a writing and reading pipe on each radio, with opposite addresses
  radio.openWritingPipe(addresses[0]);
  //radio.openReadingPipe(1, addresses[1]);
}

void loop() {
  unsigned char rf_data; //Make a variable to store the data
  unsigned char bt_data;
  unsigned char tosend;
  //radio.startListening();

 // if (radio.available()){
 //   while (radio.available()){
 //     radio.read(&rf_data, sizeof(rf_data));
 //     Serial.println(rf_data);
 //    }
 //   }

  if (Serial.available()>0){
    while (Serial.available()>0){
      bt_data = Serial.read();
      //radio.stopListening();
      Serial.println(bt_data); //----------- I'M ABLE TO SERIAL PRINTLN ----
      radio.write(&bt_data, sizeof(bt_data)); //-------- BUT I'M UNABLE TO PERFORM THIS CODE HERE FOR SOME REASON
      }
    }

}

```

Try above code and if it will not work change `RF24_2MBPS` to `RF24_1MBPS` and `RF24_PA_MIN` to `RF24_PA_LOW` on both modules (transmitter and receiver)
> 1 votes

---
Tags: serial, nrf24l01+
---


# Question
Title: Sending a digital signal from one Arduino to another to trigger an event
I am wanting to send a digital signal from one Arduino to another. The goal is for one Arduino send a HIGH signal to a pin on the receiving Arduino. While the pin is HIGH, do function

I initially successfully tested this by blinking the LED on pin 13 but then I tried to add the functionality I needed but I couldn't get the state to change of pin 12 to change.

The circuit is simple

GND \<--\> GND

pin 10 --\> pin 12

I saw there is already a post with a similar title but it didn't help me.

Any ideas?

---

Host Arduino

```
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//DIGITAL SIGNAL PIN
int pin = 10;

void setup() {

 Serial.begin(9600);

  if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // list files
  printDirectory(SD.open("/"), 0);

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);

  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT); // timer int

  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

    pinMode(pin, OUTPUT);}

void loop() {

  digitalWrite(pin,LOW);
  Serial.print(digitalRead(pin));

  // Play one file, don't return until complete
  Serial.println(F("Playing track 001"));
  musicPlayer.playFullFile("track001.mp3");
  // Play another file in the background, REQUIRES interrupts!
  Serial.println(F("Playing track 002"));
  musicPlayer.startPlayingFile("track002.mp3");

  delay(100);
}

/// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

```

---

Slave Arduino

```
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//DIGITAL SIGNAL PIN
int inPin =  12 ;
int state;

void setup() {

  Serial.begin(9600);

 if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // list files
  printDirectory(SD.open("/"), 0);

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);

  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT); // timer int

  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

  pinMode(inPin, INPUT);
}

void loop() {

  state = digitalRead(inPin);
  Serial.println(digitalRead(state));

  if(state == HIGH){
    musicPlayer.playFullFile("track001.mp3");
    Serial.println(F("Playing track 001"));
    }
}

/// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

```

# Answer
> 1 votes
One method is to use interrupts with a state machine. Here is a minimal example:

**Master**

```
#define pin 10 // connect to slave digital input pin
void setup(){
  pinMode(pin,OUTPUT);
  digitalWrite(pin,LOW);
}

void loop(){
if( // insert your condition to trigger the slave Arduino ){
 digitalWrite(pin,HIGH);
 delay(10); // short delay
 digitalWrite(pin,LOW);
 }
}

```

**Slave**

```
#define pin 2 // connect to master digital output "pin"
unsigned int state;
void setup(){
  pinMode(pin,INPUT);
  state=0;
  attachInterrupt(digitalPinToInterrupt(pin),isr,RISING) // trigger ISR on rising edge of master voltage signal
}

void loop(){
if(state==1){
  // your code here
  state=0;  // reset when done
 }
}

void isr() {
 state=1;
}

```

Digital interrupts can be done on the Arduino UNO with pins 2,3. Don't forget to also connect a common electrical ground between Arduinos.

# Answer
> 0 votes
If you use SPI, you can't use pin 12 as GPIO. Pin 12 is SPI MISO.

---
Tags: arduino-uno, arduino-leonardo, digital, digitalwrite
---


# Question
Title: Using Waveshare Raspberry Pi TFT LCD with Arduino Uno
I have a 3.5 inch Waveshare Raspberry Pi TFT LCD which uses the XPT2046 Touch Controller. I want to use this LCD screen with my Arduino Uno.

I originally believed something like this was impossible, but then I found out that the XPT2046 Touch Controller is compatible with the Arduino, and a large number of libraries for the same exist. However, I'm not really very sure whether I can use this with my Arduino; the design of the screen I have is slightly different from the ones I've found online, which are supposed to be compatible with an Arduino Uno.

Is it possible for me to use this screen with my Arduino Uno? If so, what would the wiring schematics look like, and would I be able to use libraries like URTouch?

# Answer
Possibly.

The XPT2046 chip is only for the touch screen, not the LCD. That will be easy to get going on the Arduino since many many Arduino LCD screens use the same chip.

However, you will need to find out what driver chip the LCD display uses (maybe ILI9488 or HX8357 or something similar), and what pins on the Pi header relate to what function on the display (note: it is probably a 16 bit parallel interface, so uses a lot of pins).

Also note that this only applies to displays that connect *only* to the big 40 pin header. If it uses the FPC display connector you will have no luck trying to use it with an Arduino.
> 1 votes

---
Tags: arduino-uno, lcd, raspberrypi, tft
---


title: Tian stops working after some hours

text:
# Question
Title: Tian stops working after some hours
I'm having a very strange problem. I have a Tian that is programmed to send out sensor data to a server every x seconds. My program run well but after 14,15 hours of operation it stops working and I don't receive datas. The program is fast at the beginning, then after 2 to 3 hours before stopping, it becomes more and more slow with the message "timeout".

I think maybe a misuse of the Ciao library on my part could be at the root of the problem. Or maybe a modification at the program level could correct the problem. So if I can have some help about this.. (the problem doesn't come from the use of String, I have already tested use of array with cstrings and it doesn't work).

Here is the part of the program that I think is problematic (there is another CiaoReadWrite nearly similar to the first) :

```
void CiaoReadWrite1() { CiaoData data = Ciao.read("restserver");
if (!data.isEmpty())
{
  String id = data.get(0);
  String sender = data.get(1);
  String message = data.get(2);

  splitString(message,"=",LtT2,9);

  gen            =LtT2[0].toInt(); LtT2[0]="";
  belt           =LtT2[1].toInt(); LtT2[1]="";
  genReady       =LtT2[2].toInt(); LtT2[2]="";
  hvOnOff        =LtT2[3].toInt(); LtT2[3]="";
  beep           =LtT2[4].toInt(); LtT2[4]="";
  heart1         =LtT2[5].toInt(); LtT2[5]="";
  sendConf       =LtT2[6].toInt(); LtT2[6]="";
  heart2FB       =LtT2[7].toInt(); LtT2[7]="";

  beepFB         =beep;
  heart1FB       =heart1;
  sendConfFB     =sendConf;

  Ciao.writeResponse("restserver",id, String(baroAlti*100)+"="+baroHumi*10+"="+baroPres+"="+baroTemp*10+"="+beepFB+"="+heart1FB+"="+heart2+"="+sendConfFB+"="+
                                      secCust1+"="+secCust2+"="+secEmrgSW+"="+secloop+"="+secLoop1+"="+secLoop2+"="+gndSwGnd+"="+gndSwUGnd+"="+statusA1+"="+
                                      statusA2+"="+statusA3+"="+beltStat1+"="+beltStat2+"="+beltStat3+"="+beltStat4+"="+request+"=");
  request++;
}

```

}

# Answer
> 1 votes
You're using the String (upper-case 'S') functions, which allocate and de-allocate memory, a limited commodity, even with 64K. The standard heap management functions will tend to fragment the heap into pieces too small for further use. That can make new allocations slower because the heap has to be searched for a big-enough piece, and can eventually make it the heap grow toward the stack, until a collision (something gets overwritten) inevitable. We can't say for sure that this is your problem; we don't have enough information.

But try allocating one or a few buffers large enough for the worst case requirement, and use the C string functions instead (lower-case 's'), sprintf(), strcpy(), strcat(), etc. instead.

# Answer
> 0 votes
Well, if your program works some time and stops, the first thing you have to check is if there's some variable entering in overflow. Maybe some variable is concatenating and after some time it goes overflow. I haven't check your code or the lib, because that is a common problem and already happened with me.

---
Tags: programming, library, time, datalogging, ciao-library
---


# Question
Title: How is a long int stored in an 8 bit Arduino register
Assume the following code in C:

```
long int a = 262143;

```

which in binary will be `111111111111111111` (18 bits). If an atmega328p register can hold 8 bits, how is the above represented in the register?

Compiled Assembly:

```
    .file   "a.c"
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__SREG__ = 0x3f
__tmp_reg__ = 0
__zero_reg__ = 1
    .text
.global main
    .type   main, @function
main:
    push r28
    push r29
    rcall .
    rcall .
    in r28,__SP_L__
    in r29,__SP_H__
/* prologue: function */
/* frame size = 4 */
/* stack size = 6 */
.L__stack_usage = 6
    ldi r24,lo8(-1)
    ldi r25,lo8(-1)
    ldi r26,lo8(3)
    ldi r27,0
    std Y+1,r24
    std Y+2,r25
    std Y+3,r26
    std Y+4,r27
    ldi r24,0
    ldi r25,0
/* epilogue start */
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop r29
    pop r28
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 8.2.0"

```

# Answer
> 2 votes
It isn't. It's split into four 8-bit values, each representing a quarter of the bits. Each value is stored in a separate register or memory location (depending on what is being done with it).

Software then combines them together to act as a single 32-bit value.

---
Tags: c
---


title: LED on Arduino does not blink

text:
# Question
Title: LED on Arduino does not blink
I successful installed arduino, added me to uucp and lock and loaded cdc\_acm module.

I use Arduino Uno R3, so I also installed arduino-avr-core.

I have Arduino on /dev/ttyUSB0.

I configured with:

```
stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

```

I have this folder with these files: ~/Documents/Arduino

```
build.options.json
------------------------------------------------------------
{
    "fqbn": "archlinux-arduino:avr:uno",
    "hardwareFolders": "/usr/share/arduino/hardware",
    "toolsFolders": "/usr/bin"
}

sketch.ino
------------------------------------------------------------
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

```

After this commands I got output:

```
arduino-builder -build-options-file build.options.json sketch.ino

Sketch uses 914 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

```

But nothing happened on my Arduino, what's my problem?

Thanks.

P.S. I don't have external LED, I try to use bultin LED.

# Answer
You invoked the builder, but not an upload to the board. The builder created a hex file.You should use avrdude for upload.

Or use Arduino IDE which does it with a click on a button
> 2 votes

---
Tags: led, linux
---


title: Arduino Due ADC negative voltage

text:
# Question
Title: Arduino Due ADC negative voltage
I’m trying to sample an AC signal on the Arduino Due. The AC signal will never exceed +-80mv across a frequency range of 6-833Hz. Current is negligible.

I believe there are clamping diodes to protect from this but cannot find any datasheets for the Due.

I understand that the Due cannot read negative voltage but can a negative voltage damage the ADC or it’s accuracy?

# Answer
The best thing you can do is to simply add a DC offset to your signal. Instead of having it be 0V ±80mV, have it 1.65V ±80mv. All you need is a capacitor and two resistors:

simulate this circuit – Schematic created using CircuitLab

However, 80mV is not going to have much resolution unless you reduce your reference voltage considerably, and in that case you'd need to reduce the 3.3 down to the same (or around) the reference voltage you use.

But, just feeding your signal directly into the ADC will give you the positive 80mV signal which you can use a smaller reference voltage with directly with no problem - after all, the datasheet shows:

> Voltage on Input Pins with Respect to Ground (except VBUS)...............-0.3V to +4.0V

So you can provide down to -300mV on an analog input before it potentially becomes a problem.

This is because all the IO pins have ESD protection diodes, which look like this:

simulate this circuit

Those diodes have a forward voltage of about 300mV, and so anything below -300mV will cause the lower diode to start conducting. When that happens too much current can flow and the diode risks burning out. But you can add further protection by simply adding a small resistor (1kΩ is good) in series with the IO pin to limit the current in the case that the voltage goes below -300mV and protect the internal circuitry.
> 1 votes

---
Tags: analogread, analog-sampling
---


# Question
Title: how to connect 100 Leds and Blink them on Arduino
I am planning to connect 100 LEDs to an arduino in a parallel circuit.

The current limit exceed beyond the Arduino UNO board.

In want to blink all 100 LEDs at same time. So how can I provide power source to 100 LEDs so they can blink with arduino programming.

Thanks in advance

Edit: As per discussion, MOSFET is required but which value MOSFET is required. There are many P- and N-channel MOSFETs available.

# Answer
For 100 LEDs in parallel you will also need 100 resistors, and a transistor (MOSFET) that can handle the total current for all the LEDs.

For instance, at 20mA drive current you would be dealing with 2A - you'd need a (minimum) 2A power supply and a MOSFET that can handle 2A.

*Or* you can think a little differently.

If you use a higher voltage power supply you can group your LEDs together into chains. For example with a 12V power supply you could (depending on the voltage of the LEDs) have up to 4 in a chain (red LEDs, 2V forward voltage, 2x4=8. White LEDs, 3V forward voltage, 3x4=12). Each chain then has a single resistor, and you're working with a quarter of the current (500mA) - just 25 chains of 20mA but at a higher voltage. So you can use a smaller MOSFET and you have only 25 resistors.

Another thing you could consider is to then further group those chains together. Maybe 5 groups of 5 chains, each with their own MOSFET. Then you switch just one group on at a time, but cycle through them very rapidly. Each group only then uses 100mA (5 chains at 20mA = 100mA), and you can use a really small MOSFET, and your power supply needs only be able to provide a couple of hundred mA (give it some headroom) and can be smaller and cheaper.

The only down-side of that method is you can get flicker which may be noticeable if the LEDs are moving. It also means your Arduino is doing more work to light all the LEDs.
> 5 votes

---
Tags: led, mosfet
---


title: Arduino YUN Rev. 2 power supply

text:
# Question
Title: Arduino YUN Rev. 2 power supply
I want to connect my YUN Rev. 2 to 7.4V. I read that the older version only provides exactly 5 V at the Vin Pin. Is the Rev. 2 similar to it? I read that the power supply should be improved, but what does that mean? I just tried to connect the Vin to regulated 5 V by a power supply board, but it didn't work. If I connect it to the 5V Pin the board is working, but I think this isn't recommended. So has anybody experience with that board? Thanks for your answers.

# Answer
For version 1 VIN is connected, through a Schottky diode, to the 5V rail. That means you can only provide, at absolute most, 5V plus a little bit for the diode drop into VIN. The 5V pin can only source power on the Yun, since it is also connected to the 5V rail through a Schottky diode.

In effect the two pins form the "In" and "Out" of the 5V power.

However in version 2 the 5V pin's diode has been removed, and the VIN's diode has been reversed. VIN is now known as "5V\_OUT".

So the 5V pin can be used for both in and out, and what was VIN can only be used for power out.

To provide more than 5V to the Yun you will have to first pass the voltage through a regulator of some form. Since you want to use 7.4V it sounds like you are using 2S Li-Ion (or similar) batteries. Because of that I'd recommend a switching regulator, rather than a linear one. I commonly use 5V UBEC modules from my favourite RC model supplier.

For version 1 you will provide it to VIN. For version 2 you will provide it to 5V. Quite why they'd change something quite so fundamental as the power pin arrangement from one version to another is beyond me. It would cause havoc with compatibility between versions with certain shields.
> 1 votes

---
Tags: power, voltage-level, arduino-yun, battery, input
---


title: Arduino direction sensor

text:
# Question
Title: Arduino direction sensor
I am working on a school project for next week And I need my Arduino to 'sense' at which direction it is moved is it possible? Are there any direction sensors that 'sense' at which direction the Arduino is moving?

# Answer
> 1 votes
As Juraj wrote, you need an MPU, which is a module, that consists of an 3-dimensional accelerometer and a 3-dimensional gyroscope. With the first you can sense acceleration in each of the 3 dimensions (up-down, left-right, forwards-backwards), with the seconds you can sense rotation around these three directions. Sometimes (depending on the module) there is also an magnetometer included, which can be used as a compass.

Note, that you cannot sense the actual speed of a device directly, without using some external reference. With an accelerometer you have to do some maths on the data to get the speed (basically integrating). But since you just want to sense the direction, without bothering about the exact speed, you don't have to think about this.

How exactly you have to program this is out of scope for this side, since it is a rather big topic. Also it depends on the module and library you use. The link, that was provided by Juraj, is a good starting point for reading about this. There are also some further links, for example to a library for controlling the MPU-6050 (if you have one of these) at this github site.

Basically you will have to regularly measure the acceleration in all three dimensions with the MPU. If for an axis the acceleration gets greater than a threshold value, you can count this as direction. To get a more precise direction (not only directly along the axis) you will have to combine the values of the dimensions as a vector. How this is to be solved depends greatly on what you want to achieve.

---
Tags: arduino-uno, sensors
---


title: Use MQTT to update internal clock

text:
# Question
Title: Use MQTT to update internal clock
I write code to upload to ESP8266. I wish to use time stamp in order to log events. I found an NTP sketch, I can work with ( since it has a wifi connection ), but I wish to keep my code as simple as possible.

So I'm thinking to use my MQTT server to send time updates from time to time ( have a certain topic for that ), and in between updates, use `millis()` .

Since I'm new here, I want to know from experienced programmer if it makes sense ? I would love to hear pros and cons ( before I start coding ).

Any help will be appreciated,

Guy

# Answer
> 1 votes
Use the Time library a.k.a. TimeLib.h. It will keep time between calls to your source of time, if it is your MQTT call or NTP server.

In your code you will use the Time library to get time and the source of the current time is independent from the rest of the code.

The TimeLib has a function `setTime` to set the current time and then it keeps the time using millis(). You can update the time by calling `setTime` again. The timestamp value for `setTime` is 'Unix Epoch' - number of seconds from "1970-01-01 00:00:00".

If you decide to add NTP to your project, you can use NtpClientLib. It sets the time to TimeLib with one simple line of code in setup(). Example `NTP.begin("pool.ntp.org", 1, false);`.

---
Tags: esp8266, millis, mqtt
---


# Question
Title: Arduino Uno - MQTT message using PUBSUB on ESP8266
I'm trying to write code involving MQTT messages to operate an ESP8266 relay ( a Sonoff device ), using `PubSub` library.

For some, unknown for me, reason - messages larger than 99 chars are not sent. It this a known limitation ? can it be changed ?

```
void pub_msg(char *inmsg){
        char tmpmsg[255];
        // sprintf(tmpmsg,"[Cl:oc:k] [%s] %s",deviceTopic, inmsg);   ---> wish to add a time stamp
        sprintf(tmpmsg,"[][%s] %s",deviceTopic, inmsg);  ---> using this line just to find that 99 chars sent OK
        Serial.print("published MSG:");
        Serial.println(tmpmsg);
        Serial.print("Total chars:");
        Serial.println(strlen(tmpmsg));
        client.publish(msgTopic, tmpmsg);

}

```

# Answer
The maximum MQTT packet size in PubSubClient is 128 bytes. After all the MQTT header information that leaves only 99 bytes for a message.

You can change it by editing the `PubSubClient.h` file:

```
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 128
#endif

```

As it says in the PubSubClient README.md:

> * The maximum message size, including header, is **128 bytes** by default. This is configurable via `MQTT_MAX_PACKET_SIZE` in `PubSubClient.h`.
> 2 votes

---
Tags: esp8266, mqtt
---


# Question
Title: How to connect a SilentStepStick TMC2130 stepper driver?
please excuse the noob question

Am connecting a SilentStepStick to arduino with a stepper, for bench testing.

It requires 5V power, plus I have a 24V power supply for the steppers. +5V connected to Vio, and +24V connection to VM.

Question: how to connect the grounds? The device has two GND pins. Should I just connect one ground, from the 5V power supply, to avoid ground loops?

Or should grounds from both power supplies be connected?

Thankyou for any advice.

# Answer
> 0 votes
Answer: (from Electrical Engineering), yes both grounds must be connected.

In this example, +5V and GND from the arduino would connect to the two top left pins in the diagram (Vio & GND).

The two 24v power lines would connect to the bottom left two pins, Vm & GND

---
Tags: arduino-uno, stepper
---


# Question
Title: Unable to receive data when using multiple SoftSerial on Arduino Nano
I am trying to use several (four) software-based serial ports to talk to different peripheral hardware. However, I am unable to receive data through the SoftSerial when using more than one software serial port.

I tested each pair of pins be defining it to the first port. All pairs are working as desired. In addition, I am only interested in bridging/piping from a software serial port to the hardware serial (for debugging reasons).

My code is as follows:

```
#include <stdint.h>
#include <SoftwareSerial.h>

#define SOFT_SERIAL_A_RX        5
#define SOFT_SERIAL_A_TX        6
#define SOFT_SERIAL_B_RX        7
#define SOFT_SERIAL_B_TX        8
#define SOFT_SERIAL_C_RX        9
#define SOFT_SERIAL_C_TX        10
#define SOFT_SERIAL_D_RX        11
#define SOFT_SERIAL_D_TX        12

#define SERIAL_BAUD_RATE        9600

SoftwareSerial softwareSerials[] = {
    SoftwareSerial(SOFT_SERIAL_A_RX, SOFT_SERIAL_A_TX),
    // Unable to receive data on first software serial when un-commenting following lines.
    // All pins are working when declaring each pair for first software serial (tested pins by doing this)
    // SoftwareSerial(SOFT_SERIAL_B_RX, SOFT_SERIAL_B_TX),
    // SoftwareSerial(SOFT_SERIAL_C_RX, SOFT_SERIAL_C_TX),
    // SoftwareSerial(SOFT_SERIAL_D_RX, SOFT_SERIAL_D_TX)
};
const uint8_t numberSoftwareSerials = sizeof(softwareSerials)/sizeof(*softwareSerials);

void initHardwareSerial()
{
  Serial.begin(SERIAL_BAUD_RATE);
}

void initSoftwareSerials()
{
    for(uint8_t i=0; i<numberSoftwareSerials; i++) {
        softwareSerials[i].begin(SERIAL_BAUD_RATE);
    }
}

void setup()
{
    initHardwareSerial();
    initSoftwareSerials();
}

void loop()
{
  // Only one software serial can be used (receive/transmit) at once.
  // So just using a single software serial port (first element from array)
  if (softwareSerials[0].available()) {
    Serial.write(softwareSerials[0].read());
  }
  if (Serial.available()) {
    softwareSerials[0].write(Serial.read());
  }

}

```

How can I narrow down the issue of being unable to receive when defining several serial ports? If there is no suitable solution I might switch to an Arduino Mega with its four hardware ports (would need only one additional software serial in that case), but an Arduino Nano is strongly preferred due to smaller footprint.

# Answer
> 2 votes
You cannot receive on more than one SoftwareSerial port. It's sad, but that's the way it is.

You can manually select which port you are listening to at any time with the `softwareSerials[x].listen()` function, but only one can ever listen at a time.

SoftwareSerial is a fudge at best and should only be used for one port and even then only if you *really* have to.

---
Tags: serial, arduino-nano, communication, softwareserial
---


# Question
Title: Arduino UNO LED half brightness when connected to digital GND but not analog
I am using an Arduino UNO. When lighting an LED with the switch button on a joystick module, I have two situations:

* If the LED's cathode is connected to GND on the digital pin side of the Uno, the LED only dimly lights up on button press.
* If the LED's cathode is connected to GND on the analog pin side of the Uno, the LED fully lights up on button press.

The device is receiving power from my laptop, and I am writing a digital HIGH/LOW to the LED pin (on press/release).

Is this a fault in my board, or is there a (perhaps more enlightening) reason why this is happening?

# Answer
Despite double checking my cables before asking this question, it seems I had connected the LED's cathode to digital pin 13, and not GND. The issue is now resolved. Takeaway: Triple check your cables :)
> 2 votes

---
Tags: arduino-uno, led, digital
---