body:
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!

[![the bellow image is my schema][1]][1]
Any help will be appreciated and I am open for any suggestion.

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

title: How to prevent interference between dc motor and arduino?

Answers: 2

body:
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.)

body:
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][1] 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][2] 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]: http://forum.balanduino.net/index.php?topic=47.0
  [2]: https://www.instructables.com/id/two-ways-to-reset-arduino-in-software/


body:
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]);
    }

title: Interfacing AD7606 with Arduino Due. How to data-log?

Answers: 1

body:
You can use python on the command line to log your serial monitor output. This is described [here](http://playground.arduino.cc/interfacing/python). 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](https://www.instructables.com/id/Interface-Python-and-Arduino-with-pySerial/#step2). You must put in your appropriate port and baud rate. This [Mathworks link](https://www.mathworks.com/help/supportpkg/arduinoio/ug/find-arduino-port-on-windows-mac-and-linux.html) 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](http://forum.arduino.cc/index.php/topic,131872.0.html) 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](https://www.arduino.cc/en/Guide/ArduinoDue) 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](https://www.lifewire.com/how-to-redirect-command-output-to-a-file-2618084).

For example,

    python serial_log.py > out.txt


body:
I'm configuring an ESP8266 using Arduino Uno.

I have several MQTT topics I wish it to subscribe, and I do not want to repeat code 3 or 4 times ( in `Python` I would have created a list - and make a for loop to subscribe all )

These are my topics:

    //MQTT topic
    const char* deviceName = "Sonoff1";
    const char* deviceTopic = "HomePi/Switches/Sonoff1";
    const char* msgTopic = "HomePi/Messages";
    const char* groupTopic = "HomePi/All";

This is the function registering a single topic:

    void reconnect() {
            // Loop until we're reconnected
            while (!client.connected()) {
                    Serial.print("Attempting MQTT connection...");
                    // Attempt to connect
                    if (client.connect(deviceName,user, passw)) {
                            Serial.println("connected");
                            pub_msg("Power On");
                            client.subscribe(deviceTopic);
                    } else {
                            Serial.print("failed, rc=");
                            Serial.print(client.state());
                            Serial.println(" try again in 5 seconds");
                            // Wait 5 seconds before retrying
                            delay(5000);
                    }
            }
    }

Appriciate you kind help,

Guy

title: Connecting multiple topics- MQTT

Answers: 2

body:
just for a closure:

added an array (thank to Juraj):`const char* topicsArry[]={deviceTopic, msgTopic, groupTopic, "HomePi/Dvir/Clock", "HomePi/Dvir/Alerts"};`

a for loop to over this that loop, and using `sizeof` ( which was not trivial for me ), led to :

    void reconnect() {
            // Loop until we're reconnected
            while (!client.connected()) {
                    Serial.print("Attempting MQTT connection...");
                    // Attempt to connect
                    if (client.connect(deviceName,user, passw)) {
                            Serial.println("connected");
                            pub_msg("Power On");
                            for (int i=0; i<=sizeof(topicsArry)/sizeof(char *); i++){
                              client.subscribe(topicsArry[i]);
                              char msg[50];
                              sprintf(msg, "Subscribed to %s",topicsArry[i]);
                              pub_msg(msg);
                            }
                    } else {
                            Serial.print("failed, rc=");
                            Serial.print(client.state());
                            Serial.println(" try again in 5 seconds");
                            // Wait 5 seconds before retrying
                            delay(5000);
                    }
            }
    }

body:
You can make life easier if you arrange your topic names hierarchically.
As an example suppose we have a multimedia controller that accepts various commmands:
 - mediaserver/set/volume
 - mediaserver/set/pause
 - mediaserver/set/audio/source
 - mediaserver/set/video/subtitles
 - etc...

You can then subscribe to "mediaserver/set/#"

For looping over the array of topics, you can take advantage of modern C++'s range-based for loop:
 - https://en.cppreference.com/w/cpp/language/range-for

Example code:

    const char *topicArry[] = {
        deviceTopic, msgTopic, groupTopic,
        "HomePi/Dvir/Clock", "HomePi/Dvir/Alerts"
    };
    void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");
            // Attempt to connect
            if (client.connect(deviceName,user, passw)) {
                Serial.println("connected");
                pub_msg("Power On");
                for (const char *topic : topicsArry) {
                    client.subscribe(topic);
                    char msg[50];
                    sprintf(msg, "Subscribed to %s",topic);
                    pub_msg(msg);
                }
            } else {
                Serial.print("failed, rc=");
                Serial.print(client.state());
                Serial.println(" try again in 5 seconds");
                // Wait 5 seconds before retrying
                delay(5000);
            }
        }
    }


body: 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)?

title: what the benefit uploading hex file merely to arduino board?

Answers: 1

body: 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.


body:
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("");
      client.println("");
      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("");
      client.println("");
      client.println("

");
      client.println("
Wifi Based Project
");
      client.println("");
      client.println("

");
      client.println("");
      client.println("<button>Data </button>
");
      client.println("");
      client.println("

");
      client.println("");
      client.println("Load 1");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");
      client.println("

");
      client.println("");
      client.println("Load 2");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");
      client.println("

");
      client.println("");
      client.println("Load 3");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");
      client.println("

");
      client.println("");
      client.println("

");
      client.println("");
      client.println("
");
      client.println("

");
      client.println("
");

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

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

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

      client.println("
");
      client.println("
");
      client.println("");
      client.println("");
      delay(1);
      Serial.println("Client disonnected");
      Serial.println("");

    }

[![NodeMCU V1.0 Pinout][1]][1]

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

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("");
    client.println("");
    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("");
    client.println("");
    client.println("

");
    client.println("
Wifi Based Project
");
    client.println("");
    client.println("

");
    client.println("");
    client.println("<button>Data </button>
");
    client.println("");
    client.println("

");
    client.println("");
    client.println("Load 1");
    client.println("<button>Turn On </button>");
    client.println("<button>Turn Off </button>
");
    client.println("");
    client.println("

");
    client.println("");
    client.println("Load 2");
    client.println("<button>Turn On </button>");
    client.println("<button>Turn Off </button>
");
    client.println("");
    client.println("

");
    client.println("");
    client.println("Load 3");
    client.println("<button>Turn On </button>");
    client.println("<button>Turn Off </button>
");
    client.println("");
    client.println("

");
    client.println("");
    client.println("

");
    client.println("");
    client.println("
");
    client.println("

");
    client.println("
");

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

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

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

    client.println("
");
    client.println("
");
    client.println("");
    client.println("");
    delay(1);
    Serial.println("Client disonnected");
    Serial.println("");

    }

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

Answers: 1

body:
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


body:
for context to this post you can catch up on [this post][1]

  [1]: https://arduino.stackexchange.com/questions/55466/stacking-3-of-the-same-shields-on-top-of-each-other-and-instructing-them-in-sync

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.

title: "exit status 1" error when invoking "useInterrupt" method

Answers: 1

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

  [1]: https://www.arduino.cc/en/Main/Software


body:
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();
       }
    }

title: Sending a digital signal from one Arduino to another to trigger an event

Answers: 2

body:
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.

body: If you use SPI, you can't use pin 12 as GPIO. Pin 12 is SPI MISO.


body:
I have a [3.5 inch Waveshare Raspberry Pi TFT LCD](https://www.waveshare.com/wiki/3.5inch_RPi_LCD_(A)) 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?

title: Using Waveshare Raspberry Pi TFT LCD with Arduino Uno

Answers: 1

body:
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.


body:
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"

title: How is a long int stored in an 8 bit Arduino register

Answers: 1

body:
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.


body:
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.

title: LED on Arduino does not blink

Answers: 1

body:
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


body:
please excuse the noob question

Am connecting a [SilentStepStick](https://github.com/watterott/SilentStepStick/blob/master/hardware/SilentStepStick-TMC2130_v11.pdf) 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.

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

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

title: How to connect a SilentStepStick TMC2130 stepper driver?

Answers: 1

body:
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


body:
I have water level/humidity sensor and a LDR diode hooked to arduino like this (the resistor is 10k)
[![schema][1]][1]

- On `A0` I can read signal from water sensor (blue)
- On `A1` I can read signal from light sensor (yellow)

The problem is that both signals seem to be correlated. When I dip the water sensor to water and keep the light levels the same, the signal from light goes up as well (dramatically).

I suspect that this is due to Ohm's law. The voltage in a circuit depends on the total resistance of the circuit. Both sensors act as a sort of resistors so when one's resistance changes the voltage in the circuit changes as well.

How can I wire the sensors such that the change in resistance of either sensor doesn't affect the second? Or do I need a separate power supply for each sensor?

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

title: Correlated signal from two sensors in one circuit

Answers: 1

body:
If I've found the same humidity sensor, it has pretty big output impedance and the maximum input impedance for the `ADC` input is `10kOhms`. According the the datasheet the recommended minimum load for the sensor is about `80kOhms` (?). That means readings of humidity sensor will be highly affected by sampling capacitor initial charge (= the value of previous reading).

Basically reading `GND` between sensor readings helps to separate the results from each other, but the humidity sensor won't be able to charge sampling capacitor to its output voltage without amplifying the current (you'll get values much lower than it should be).

Or you can repeat the readings on humidity sensor channel several times until the value is more "stable".


body:
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?

title: Arduino Due ADC negative voltage

Answers: 1

body:
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:

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

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

<!-- End schematic -->

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:

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

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

<!-- End schematic -->

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.


body:
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?

title: Arduino direction sensor

Answers: 1

body:
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][1].

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.

  [1]: https://github.com/jrowberg/i2cdevlib


body:
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.

title: how to connect 100 Leds and Blink them on Arduino

Answers: 1

body:
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.


body:
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.

title: Arduino YUN Rev. 2 power supply

Answers: 1

body:
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](https://hobbyking.com/en_us/kingkong-5v-3a-ubec.html).

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.


body:
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);

    }

title: Arduino Uno - MQTT message using PUBSUB on ESP8266

Answers: 1

body:
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](https://github.com/knolleary/pubsubclient/blob/master/README.md):

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


body:
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

title: Use MQTT to update internal clock

Answers: 1

body:
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);`.


body:
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.

title: Unable to receive data when using multiple SoftSerial on Arduino Nano

Answers: 1

body:
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.


body:
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?

title: Arduino UNO LED half brightness when connected to digital GND but not analog

Answers: 1

body: 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 :)


body:
The following is taken from ATmega328-328P Data sheet.

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

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

According to this, I can access all the 32 registers in CPU using memory addresses. For example:

     unsigned char *register = 0x0;

will access the first register. Is this true? if so, then is this also possible to do on regular CPUs (like my laptop), since I thought you can only use a pointer to access memory and not CPU registers.

Is the register mapped into the SRAM in this case?

title: How is it possible to access the CPU registers using memory addresses?

Answers: 1

body:
Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.

As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

> Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM


body: I want to know if I could connect many Arduino Nano  boards together (Example : 10 boards ) , Also i want to know  if there is any problem in Communication between them  using I2C , could this affects processing speed on every board ,  and  if there's going to be any kind of delay when communicating?

title: Could I Connect many Arduino Nano boards together?

Answers: 2

body:
> I want to know if I could connect many Arduino Nano boards together...

Yes, you can read about it [here at arduino.cc][1]. Where is says: "...it can be helpful to set up two (or more!) Arduino ... boards to share information with each other..."

> ... i want to know if there is any problem in Communication between
> them using I2C ...

This feature, according to the above link, is expected to work.  (Can you explain the type of problems you are avoiding?)

> ...could [i2c communication] affect processing speed on every board ...

Most likely it will.  Most Arduino platforms do not run [operating systems][2].  So your program is all that is running.  If your program is busy sampling sensors, it will be difficult (not impossible) to concurrently handle i2c communications.

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter
  [2]: https://en.wikipedia.org/wiki/Operating_system

body:
Yes it certainly is possible. And can work well if done properly. The concern that I have is when longer wiring lengths are used. I2C is not intended for extended distributions. And if that were the plan then I STRONGLY advise using proper I2C buffer chips designed for that purpose.

The more devices, the more wire, all adds to the capacitance on the lines. Because I2C uses pull up resistors to produce a high the added capacitance limits either the length of wire that can be used, or the transmission frequency. I have used I2C buffers in may products and it is very useful when extended length is required. I use both I2C buffers, and also I2C isolated buffers. The company I work for manufactures distributed control electronics. I am one of the hardware designers. I have been using I2C like this for about 15 years.

For now have a look at this web page.  http://www.techbitar.com/how-to-network-many-arduinos-with-sensors-using-i2c.html

I'm sure it will spur some questions. It makes things simpler if there is only one master controlling the communications bus. Multimast is possible but can have more conflicts and you then need to deal with that issue. Best not to go there.

I2C is not a very robust protocol but still can be usable between processors if handled carefully. Keep it simple.


body:
I have an Arduino Uno and I would like to attach a Waveshare 1.54“ display (red, black & white) to it.

All the specs tell me that it consumes 3.3 V which I have readily available on the Arduino Uno.

I could not get the display to work until I attached the Power pin to 5V instead of 3.3V.

I did try this with two different ePaper displays and the situation was the same.

I also tried to power the display with a Raspberry Pi‘s 3.3V (with the GNDs connected). But this did not work either.

So I am wondering what I am missing here, is it simply a power issue and my Arduino can‘t deliver the necessary current?

title: Waveshare 1.54 inch ePaper display requires 5Vs from Arduino Uno

Answers: 2

body:
The answer lies in the [FAQ for that display](https://www.waveshare.com/wiki/1.54inch_e-Paper_Module_(C)#FAQ):

> Why the e-Paper cant work with Arduino?
>
> Answer:
>
> The I/O level of Arduino is 5V, and the e-Paper should be driven with 3V3. If your Arduino cant drive the e-Paper successfully, please try to convert the level to 3.3V
>
> You can also try to connect the Vcc pin to the 5V of Arduino to see whether the e-Paper works, but we recommend you not to use 5V for a long time.

So while you *can* run it from 5V, you really shouldn't, since you run the risk of breaking it.

Instead, you should employ proper logic level shifting to reduce the Arduino's outgoing signals to 3.3V and, more importantly, boost the incoming signals from the display to 5V.

body:
Update to those who have bought the display module recently (doesn't apply to bare displays). There has been a change and the new modules support 5V. From the display's [user manual][1]:

> 9. For raw panel, its working voltage is 3.3V, note that when you designed you own driver board, level convert circuit is required if
> the working voltage of your board is 5V. Module/HAT version can
> support 5V voltage if the Module you buy is the new version which has
> been integrated convert circuit.

  [1]: https://www.waveshare.com/wiki/1.54inch_e-Paper_Module_(C)#Documentation


body:
is there any way to rename a file in sd card without using **SdFat**? Thank you
im getting error when inclung the

        #include <SPI.h>
        //#include <SD.h>
        #include <SdFat.h>
        extern SdFat SD;

the error msg was "Error compiling for board Arduino/Genuino Uno.
"

    Local\Temp\ccZn9IeW.ltrans2.ltrans.o: In function FatVolume::init(unsigned char) [clone .constprop.18]': \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:439: undefined reference to SD' \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:440: undefined reference to `SD'

title: "undefined reference to SD" with SdFat library

Answers: 1

body: Remove the `extern` keyword from `SdFat SD;` because it tels the compiler that the variable is defined elsewhere and it is not and the linker then can't find it.


body:
Code below is to read 4 thermometers and use values to turn on or off the heaters (I'm stuck at reading).

I'm reading and displaying temperature very well, but it comes to the problem, where I want to set the limit of heating, a value of 37 degrees. It comes to the problem, when I want to read the value of "tempa", but the Arduino doesn't respond properly: it somehow reads the value as char or I get the output in hex instead of integer (although I never declared a character in whole program).

It can be seen in last 2 lines before "CHANNEL_2".

Lines are:

    lcd.setCursor(10, 0);    //termometer
    lcd.write(tempa);    //termometer

absoluta, absolutb, absolutc and absolutd are variables, which are technically values of temperature in Kelvin.

tempa, temb, tempc and tempd are variables, the temperature in celsius.

    #include <LiquidCrystal.h>
    #define  LM335_pin  0                          // LM335 output pin is connected to Arduino A0 pin
    #define  LM335_pio  1                          // LM335 output pin is connected to Arduino A0 pin
    #define  LM335_pip  2                          // LM335 output pin is connected to Arduino A0 pin
    #define  LM335_pir  3                          // LM335 output pin is connected to Arduino A0 pin

    const int rs = 7, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // LCD module connections (RS, E, D4, D5, D6, D7)
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

      //-----------------------HEATERS----------------------------------------
    //int grelea = 11;  //heater_1
    //int greleb = 10;  //heater_2
    //int grelec = 9;   //heater_3

    void setup() {
      lcd.begin(20, 4);

    //  pinMode(grelea, OUTPUT);
    //  pinMode(greleb, OUTPUT);
    //  pinMode(grelec, OUTPUT);

    }
    int  absoluta, tempa; //sensor_1
    int  absolutb, tempb; //sensor_2
    int  absolutc, tempc; //sensor_3
    int  absolutd, tempd; //sensor_4

    void loop() {

      delay(1000);

      //-----------------------CHANNEL_1----------------------------------------
      absoluta = analogRead(LM335_pin) * 0.489;
      tempa = absoluta - 273;

      lcd.setCursor(0, 0);    //termometer

      lcd.setCursor(0, 0);    //termometer
      lcd.write("Temp1=");    //termometer

      lcd.setCursor(8, 0);    //termometer
      lcd.write((tempa / 10)% 10  + 48);    //termometer

      lcd.setCursor(9, 0);    //termometer
      lcd.write(tempa % 10  + 48);    //termometer

      lcd.setCursor(10, 0);    //termometer
      lcd.write(char(223));    //termometer

      lcd.setCursor(11, 0);    //termometer
      lcd.write("C");    //termometer

      lcd.setCursor(15, 0);    //termometer
      lcd.write(tempa);    //termometer

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

      //-----------------------CHANNEL_2----------------------------------------
      absolutb = analogRead(LM335_pio) * 0.489;
      tempb = absolutb - 273;

      lcd.setCursor(0, 1);    //termometer
      lcd.write("Temp2=");    //termometer

      lcd.setCursor(8, 1);    //termometer
      lcd.write((tempb / 10) % 10  + 48);    //termometer

      lcd.setCursor(9, 1);    //termometer
      lcd.write(tempb % 10  + 48);    //termometer

      lcd.setCursor(10, 1);    //termometer
      lcd.write(char(223));    //termometer

      lcd.setCursor(11, 1);    //termometer
      lcd.write("C");    //termometer
      //---------------------------------------------------------------

      //-----------------------CHANNEL_3----------------------------------------
      absolutc = analogRead(LM335_pip) * 0.489;
      tempc = absolutc - 273;

      lcd.setCursor(0, 2);    //termometer
      lcd.write("Temp3=");    //termometer

      lcd.setCursor(8, 2);    //termometer
      lcd.write((tempc / 10) % 10  + 48);    //termometer

      lcd.setCursor(9, 2);    //termometer
      lcd.write(tempc % 10  + 48);    //termometer

      lcd.setCursor(10, 2);    //termometer
      lcd.write(char(223));    //termometer

      lcd.setCursor(11, 2);    //termometer
      lcd.write("C");    //termometer
      //---------------------------------------------------------------

      //-----------------------CHANNEL_4----------------------------------------
      absolutd = analogRead(LM335_pir) * 0.489;
      tempd = absolutd - 273;

      lcd.setCursor(0, 3);    //termometer
      lcd.write("Temp4=");    //termometer

      lcd.setCursor(8, 3);    //termometer
      lcd.write((tempd / 10) % 10  + 48);    //termometer

      lcd.setCursor(9, 3);    //termometer
      lcd.write(tempd % 10  + 48);    //termometer

      lcd.setCursor(10, 3);    //termometer
      lcd.write(char(223));    //termometer

      lcd.setCursor(11, 3);    //termometer
      lcd.write("C");    //termometer
      //---------------------------------------------------------------
    }

title: Hex output although I always define integer

Answers: 1

body:
`lcd.write()` will write one byte to the LCD. It makes no attempt to try to interpret the data type of the input parameter. You can think of it like sending "raw data" to the LCD.

`lcd.print()` can be called with many types as input and will interpret that the user wishes to print a human-readable expression of the data. Also, it can print more than one byte.

As an example, the `char` variable with content `'A'` is represented in RAM by the byte with value 65 (the ASCII code for 'A'). If you call `lcd.print('A')`, it will see that `'A'` is a `char` and will send whatever raw data to the LCD to get an "A" on the screen. It just so happens that sending a raw byte 65 will accomplish this, but that is a coincidence; the LCD driver understands ASCII for getting characters to print on the screen.

If you call `lcd.write(125)`, then the actual byte `125` (in binary, `01111101`) is sent to the LCD. If you wanted to actually print the 3-digit number 125, `lcd.print(125)` would end up sending 3 bytes to the LCD: The ASCII values for `'1'`, `'2'`, and `'5'` (which are 49, 50, and 53). The `print()` function takes care of this interpretation for you.


body: ok, Good morning, guys, with a data acquisition project, in this, I get data every 12 hours, even if it's only 12 hours, the arduino gets connected directly, and it's being powered by a 9v battery, for longer life of this battery, to try to hibernate the arduino with real time, using the real time clock 1302, you could help me to make a code for this clock, for I have never used it before! thank you

title: Hibernate Arduino for 12hrs with rtc1302 module

Answers: 1

body:
You need 3 pieces of code and one replacement:

1) Ditch ds1302 and get yourself an RTC with an interrupt pin (like DS3231 which Jot suggests). It will make your life easier.

2) Setup your RTC to fire an interrupt every 12 hours.

3) Since you have successfully implemented a sleep mode, try to wake your Arduino up using a hardware interrupt. See [Nick Gammon's guide for interrupts][1], and read carefully about waking your micro with an external interrupt. You can prototype it using a pushbutton, which will either connect your interrupt pin to GND or Vcc. Use an appropriate resistor as well. [This guide][2] has good information for starters.

To sum up: you'll have your Arduino sleep at all times and your RTC set to fire a hardware interrupt. When fired, the interrupt wakes Arduino, and the interrupt code will handle your measurements.

  [1]: http://www.gammon.com.au/interrupts
  [2]: https://www.instructables.com/id/External-Interrupt-in-arduino/


body:
I am new to Arduino

Let me ask you about IOT(internet of things).

I want to connect ESP-01S Relay v1.0

Where does the NC port goes on Arduino? Is it TX or RX?

Also, where does the NO goes on Arduino? Is it TX or RX?

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

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

title: ESP-01S Relay V1.0 connection with Arduino

Answers: 2

body:
Common, Normally Connected and Normally Open are terminals switched by the relay. There you connect what should be switched. Common is input and the two other terminals are connected, one if the coil is powered and the other when the coils is without power. The relay is controlled by the esp-01. No Arduino should be connected to this.

Disconnect the esp-01 from the relay board and use an 3.3 V USB-to-TTL Serial adapter [to program the esp-01 with Arduino IDE][1]

Add Over The Air support to your esp8266 sketch with ArduinoOTA library and then you can upload new versions of your sketch over WiFi. To debug the sketch with `print` use Telnet server or my [TelnetStream library][2].

  [1]: https://tttapa.github.io/ESP8266/Chap01 - ESP8266.html
  [2]: https://github.com/jandrassy/TelnetStream

body:
The 2 connections you refer to (NC and NO) are connections to the relay switch.

* **NO** stands for *normally open*
* **NC** stands for *normally closed*
* **C** or **COM** stands for *common*

[![basic relay diagram][1]][1]

When the relay is unenergised, the common is connected to the NC terminal. When power is applied to the relay, the coil energises and switches, so now common is connected to the NO terminal.

From my reading of the usage document located on the [GitHub repository][2], you are supposed to program the ESP module before plugging it into the relay board. There are no terminals broken out for you to connect to the Tx and Rx on the relay board.

However, the following board from [AUS-eParts][3] has a header to connect a 3V TTL cable. This can be used to program the ESP module.

[![Relay board with TTL header][4]][4]

  [1]: https://i.stack.imgur.com/RPglA.gif
  [2]: https://github.com/IOT-MCU/ESP-01S-Relay-v1.0
  [3]: http://auseparts.com.au/index.php?route=product/product&product_id=377
  [4]: https://i.stack.imgur.com/Qky4Y.jpg


body:
I am trying to create something that will allow me to control an individually adressable LED strip using an electric piano using its midi output.

Some things to note:

 - The piano can output midi either via USB or via standard midi connectors.
 - I have an Arduino Uno and an Arduino Mega available
 - I'm using a WS2812B strip with +ve, ground and data cables

I don't believe there's a way to read midi from my piano direct to the arduinos without reflashing the USB controller. For this reason I'm connecting via USB to my mac.  On my mac I've written a program which reads the midi input and can understand it and send it on to somewhere else.

The arduino for the light strip I think I can program pretty easily but I have some questions:

 - If I need to power the LED strip, should I be powering it from the arduino power or giving it its own power source with common ground?
 - Is splitting it up into midi -> computer, computer -> arduino, arduino -> LED strip sensible? If not how should I be going about it?
 - Am I making life difficult by going the USB route for Midi or should I switch to midi connectors and connect direct to the arduino somehow?

title: Midi controlled LED by USB

Answers: 1

body:
I did some time ago something very similar, except not using USB, and on an STM32 (Arduino compatible STM32F103C8T6), but the principle is similar.

Regarding another MIDI test I did on an Arduino, I used the 47 Effects library and for the WS2813 (software-compatible with WS2812B) the FastLed library.

One MIDI port is easy to use (supported by 47 Effects), which uses the single UART of the Arduino UNO.

You have to write a small program to convert the MIDI notes to WS2812 LED data, which is not much more than filling in a structure. Mapping 61 or 88 notes to 30, 60 or 144 LED notes is not so easy, just clip the notes, or use some mapping factor.

You cannot use the Arduino for powering the LED strip, use a separate adapter for that. Only the line signal comes from the Arduino, and connect GNDs together.

The Arduino should be fast enough to both read MIDI, translate it to LED data (unless you make some very time consuming algorithm) and send the data.


body:
Hi I have a Beetle BLE (https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339) and I am trying to connect an Adafruit MicroSD card breakout board+ (https://www.adafruit.com/product/254) via SPI connections. I am trying the following code, but I am having trouble selecting the CS pin using D4 since the Beetle has no D10. Does anyone know if I am selecting D4 correctly, while keeping pin 10 as an output. I keep getting initialization failed! My setup is on the ICSP 6 pin configuration:

5V --> 5V

MISO --> DO

SCK -->CLK

GND --> GND

MOSI --> DI

D4 --> CS

RST is left out

Here is my code:

    #include <SPI.h>

    #include <SD.h>

    File myFile;

    void setup()
    {
      Serial.begin(9600);
      Serial.print("Initializing SD card...");
      // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
      // Note that even if it's not used as the CS pin, the hardware SS pin
      // (10 on most Arduino boards, 53 on the Mega) must be left as an output
      // or the SD library functions will not work.
    //   pinMode(4, OUTPUT);
       pinMode(10, OUTPUT);
    //   digitalWrite(4, HIGH); // Add this line

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.

      myFile = SD.open("test.txt", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.print("Writing to test.txt...");
        myFile.println("testing 1, 2, 3.");
      // close the file:
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
    }

    void loop()
    {
      // nothing happens after setup
    }

title: How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed!

Answers: 3

body:
The ICSP header **labels on the Wiki page are wrong**. In the schematic [here][1] the ICSP header has the same pinout as other Arduinos. The legend doesn't match the picture on the Wiki page but is true:

 - ICSP1: Atmega 328P
 - ICSP2: CC2540

The ICSP header is the inner one. Is right on the pictures.
At pin 1 on board the corner of the white square around pins is skewed. The pins are from left to right first row Eeset, CLK, MISO, second row Ground, MOSI, 5 V.

[pdf schematic for the board][2]

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

  [1]: https://www.dfrobot.com/product-1259.html
  [2]: https://github.com/Arduinolibrary/DFRobot_Bluno_Bettle/blob/master/DFR0339-Bluno beetle V1.0.pdf?raw=true
  [3]: https://i.stack.imgur.com/5oa1X.gif
  [4]: https://i.stack.imgur.com/fM5a9.jpg
  [5]: https://i.stack.imgur.com/sJqHm.jpg
  [6]: https://i.stack.imgur.com/hrJOs.jpg

body:
The correct ICSP was on the right, ICSP1. However, the orientation of those pins were from left to right on the TOP: SCK, 5V, MISO; left to right on the BOTTOM: MOSI, RESET, GND. In the Wiki they had the ICSP labels 1 and 2 reversed, but correct in the text below. https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339

Therefore, there was nothing wrong with the code, only the wiring to the correct pins!

body:
This is what I'm seeing with my multitester:

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

The cc2540 is the SMD chip on the same side as the ICSP pads. The atmega328p is on the opposite side of the PCB

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