text:
DFPlayer Noise: Researched, Tried, and Bep Bep Bep Bep Bep
Spent an entire day researching and attempting to fix the DFPlayer noise problem. The amp works as expected, so it is not the problem. I have made a video to help you better understand the sound produced: https://www.youtube.com/watch?v=uK2kkR0XjFs&feature=youtu.be
This is the amp/speaker used: https://sites.google.com/site/wayneholder/chiptunes

The amp with speaker works as expected using another similar mp3 player like from a computer or possibly a phone.

Here we get the bep bep bep bep bep... as the amp/speaker has its own battery power.

Here I made everything as one power source. Bep bep bep bep bep...
I think I exhausted my research and made the following attempts:
> -Electrolytic Capacitor at the power terminals
> -Electrolytic Capacitor parallel with ceramic capacitor from negative terminal to VCC in DFPlayer
> -Diode from positive terminal to VCC in DFPlayer
> -Battery Power source; USB power source; Power Supply power source; 5V USB plug regulator power source
> -1k Resistor from TX RX; Rx Tx
> -1-10k resistor from Rx Tx
> -1k between channel to GND
> -Separate power source for each the Arduino, amp, and DFPlayer
> -Tried multiple DFPlayers

Keep note that the amp/speaker works well. The files are the same both on the computer and in the SD card.
Here is my code:

#include <DFRobotDFPlayerMini.h>

/***************************************************
DFPlayer - A Mini MP3 Player For Arduino
 <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

 ***************************************************
 This example shows the basic function of library for DFPlayer.

 Created 2016-12-07
 By [Angelo qiao](Angelo.qiao@dfrobot.com)

 GNU Lesser General Public License.
 See <http://www.gnu.org/licenses/> for details.
 All above must be included in any redistribution
 ****************************************************/

/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here
 <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
 2.This code is tested on Arduino Uno, Leonardo, Mega boards.
 ****************************************************/

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
int counter = 0;
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

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

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(15);  //Set volume value. From 0 to 30
  delay(1000);
myDFPlayer.enableDAC();  //Enable On-chip DAC
}

void loop()
{
  static unsigned long timer = millis();
  if(millis() - timer > 1000 && counter == 0)
  {
   myDFPlayer.play(1);
   Serial.println(F("Music Started"));
   delay(1000);
   Serial.println(F("1 second later..."));
   delay(6000);
   Serial.println(F("7 seconds later..."));
   delay(1000);
   counter =1;
  }

delay(7000);

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

Comments are not for extended discussion; this conversation has been moved to chat.

The "bep bep bep" you are hearing is power supply noise introduced by the SD card. Every time the SD card reads the power supply dips and the ground raises.  This is because these boards have really terrible grounding in their design. There is no coherent ground plane, and the analog audio sections and noisy digital sections both share the same ground with no isolation or filtering between them.
To reduce the impedance of the ground plane you must connect both the GND pins together, and do it with a short wire.  Better would be to modify the board itself and solder a wire directly between the two ground pins.
There are also strategic ground points around the place you could also solder directly to one of those ground pins - such as the ground side of the SD card's decoupling capacitors, and the GND pin of the SD card itself (if your soldering skills are up to it - those pins are pretty fine pitch).
The whole issue stems from trying to fit too much into too small a space. The board really should have been made as a 4-layer board with a (near) solid ground and power plane to reduce the power impedance. Better decoupling and filtering on the SD card's power pin (such as a "PI" filter with two capacitors and a ferrite bead, or two capacitors and a small resistor) would have been a big benefit as well.

Today I had similar issues. Sometimes it used to play correctly for around 10 seconds and then noise used to come. Finally reduced the length of the Rx wire and it worked. How communication wire length can cause this noise? Communication may not happen if at all there are such problems I thought. But communication does happen correctly, but after that the problem starts.

Thanks for all the investigative work.
Throwing in my 2 cents :
I was also experiencing random cutoffs and wierd noises.
I was using the Servo class in combination with the DFPlayer on an Arduino UNO board.
It turns our that the Servo class uses the timers that are related to pin 9 and 10. When attaching a servo, signals will be outputted on those ports.
So don't hook up your DFPlayer or anything else on those ports.
Probably because the Servo class was sending all kinds of data over the serial connection to the DFPlayer, the module would stop playing and start making a lot of random noise for the remaining duration of the mp3.
Other things that I came across and might help other people :
The DFPlayer needs MP3's of a certain length. MP3's of just 1~2 seconds don't play. +5 seconds seems to be fine.
Any fancy MP3 encoding also prevents the MP3s from playing.
The led will light up but no sound will be outputted.
Depending on the library used for the DFPlayer, the filenames and folder names do matter. The mp3's have to be in the MP3 folder and be named like 0001.mp3, 0002.mp3
According to 1 of the many datasheets out there, the DFPlayer requires 3.3v levels for the RX and TX port, regardless of the operating voltage.
So do put those 1K resistors there. It won't hurt the module.
Motors and servo's do cause a lot of noise on the power source if you run the board off the 5v USB port.
Even small motors can generate spikes of +2A when turned on.
Signals from other cables and devices can also interfere with the serial connection so ideally use shielded wires for the TX/RX cables.
According to the SD card specs of some manufacturers, power usage for an SD card can go up to 100mA.
The module itself can produce 3W output so that would also add up to 600mA @ 5V. And add something like 150mA for the microcontroller onboard.
So even a standard 5v@500mA USB port won't have enough power to drive just the Arduino and DFPlayer in some cases.
Someone took a look at the clicks and plops on pause or power on/off :
http://work-now-dammit.blogspot.com/2016/08/dfplayer-mp3-module-power-onoff-clicks.html
Remove the 0-ohm resistor next to the 8002 amp. Connect pin 1 of the 8002 amp to the BUSY pin (16) of the module.

this is so helpful! thank you

I found that noise was due to three issues,

Forgetting to ground BOTH GND pins on the DFPlayer chip
Forgetting to put 1k resistors in the Tx and Rx lines
Power fluctuations

Power is the big issue. When I powered my Arduino with a 9v 2A supply all the noise went away. Switching to USB power (5v) caused the noise to return.

My Problem & Solution:  I recently attempted to control the DFPlayer with an Arduino Pro Mini and also experienced loud pulsing noises during playback (along with the music file). The pulsing could be seen on a scope on one of the speaker leads. Unloading the speaker did not help, using different power supplies did not help. Also, with regard to tying the two DFPlayer GND pins together, that's not necessary on my board since they are already connected together via the metal shell of the micro SD connector.
However, I noticed that when I attempted to re-program the Mini (or even when I pressed the reset button), there was a short period of time when the pulsing stopped and the music file played as it should. In my case the problem was the data line from the Mini to the Rx pin on the DFPlayer (there was no connection to the Tx pin). I verified this by starting playback (with the pulsing noise) and then disconnecting the Rx connection. That stopped the pulsing and the music file played as expected.
The software solution was to force the transmit pin on the Mini (I'm using soft serial) to a LOW state immediately after sending the Play command. Works fine now.
Update: I had previously connected the Mini serial output directly to the DFPlayer Rx pin without a 1K limiting resistor. Now, with the resistor in place I no longer get the pulsing noise during playback and there is no longer a need to pull the control line low.

Thanks Bob.  I just ran into this same problem and adding a 1k limiting resistor in series worked a treat!

I had the same problem. It was solved with a separate power supply to the DFPlayer. I also grounded both sides of the player but that alone was insufficient.

I've had loads of crazy little issues like this with the dfplayer and tried lots of solutions with very inconsistent results. Sometimes a technique like extra grounding or a resistor to the tx/rx pins will work the magic and then on making another copy of the circuit, the problem is inexplicably back! Here's a important clue that I haven't seen anywhere on forums yet, so I wanted to add it into the mix. Though the dfplayer is claimed to work from 3.3V to 5V, I've found it is much better behaved at 3.3V! Running it at 5V gives me odd noise and stability problems that vanish at 3.3V. You can get very cheap and efficient 3.3V regulators that are no bother to use. Try running it at the lower voltage and see if those issues clear up!


text:
How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor
I would like to make an alarm system using ultrasonic sensor.
My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.
But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.
I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.
int echoPin = 10; // pin 10 for the echo

int trigPin = 9; // pin 9 for trigger
int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
#include <NewPing.h> // Library for improved ultrasonic sensor readings

#include <SoftwareSerial.h>

NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

int ledpin=7;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 250;           // interval at which to blink (milliseconds

void setup() {
    pinMode(ledpin,OUTPUT);
    Serial.begin(9600); //sets up serial monitor
}

void loop() {

    delay(50);

    Serial.print("Ping: ");
    Serial.print(sonar.ping_cm());
    Serial.println("cm");

    //warning
    Serial.println("cm");

    //warning
    if(sonar.ping_cm()>=30)
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledpin, ledState);
      }

    }
}

You are initiating the NewPing library with NewPing sonar(trigPin, echoPin,30);. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says

sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from
if(sonar.ping_cm()>=30)

to
if(sonar.ping_cm()==0)

I follow your suggestion its working but when placing the hand near about 10 cm led some time blinking and some time not although when placing the hand more than 10 cm its blinking.But I want when object is 0 to 29 cm away led should not blink and when object is 30+ cm away led should blink and once led start to blink it continue to blink even when object comes near of it.

Can you confirm, that the distance is read correctly from the sensor (e.g. using the serial monitor)?

yes the distance is correctly showing.

I'm not sure, if that is the error, but on the site it also says "Ping sensors consistently and reliably at up to 30 times per second. " You use two consecutive calls to the ´ping_cm()´ function, which follow up on each other very quickly. Try to use it only once and save it in the cm variable.

Led is blinking but when an object is away more than 10 cm from the ultrasonic sensor led is blinking fast and hence when object come closer led is blinking slowly and even some time did not blink.But I want when object is 0 to 29 cm away led should not blink and when object is 30+ cm away led should blink and once led start to blink it continue to blink even when object comes near of it.

Mhh, I don't see any possibility in your code, that the blinking frequency of the LED may change. For that I'm out of ideas. When you want the LED to stay blinking, whatever happens, you can set a boolean variable, that makes your if-statement always true (you can combine it the with ping value check trough the || (boolean or))

source: Stack Exchange

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

sort: votes


text:
Adafruit IO example won't compile, library required is correct version
I have Arduino IDE 1.8.5 installed, and also Adafruit IO Arduino 2.6.0 and Adafruit MQTT Library 0.20.0.
With the Adafruit IO lib comes a set of examples, and I wanted to use example adafruitio_07_digital_out as a starting point for a project on an Adafruit HUZZAH ESP8266.
It won't compile. I get
#error "This sketch requires Adafruit MQTT Library v0.17.0 or higher. Please install or upgrade using the Library Manager."

which I find strange. I've tried installing 0.17.0 instead of 0.20.0, but that doesn't help.
Is there anything I can do to get this to work? The suggested solution of using the Library Manager to install the required package is obviously not working.

can you double check and confirm that the library you have installed is actually installed and is higher than the required version?

@EngrAbbas I don't know how to check that other than using Sketch->Include Library->Manage Libraries and I've been through there many many times by now. Anywhere else I should look?

@gibson - On Stack Exchange sites such as this answers are not to be edited into questions.  Remove that and post it instead in the answer form below.

It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.

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


text:
Arduino tone frequency isn't always precise
I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.
It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.
The code itself is good, because I use a constant in the tone() function call for specifying the frequency.
Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

Post your code and schematic. Without that info your question is unanswerable. How do you know beep is half-tone higher?

As far as I know, tone() implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.
Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.

Half-tone, that's a lot of change.  I would expect a lowering of frequency if anything from other resources being active.  An increase in frequency suggests perhaps something is changing the internal counter values that is used for the toggling.
2.5KHz is 400microseconds, toggling every 200us. You might consider using Arduino "blink without delay" to monitor the passing microseconds and toggling based on that. I've created up to 20KHz signal that way, but not with anything else running.


text:
Does a delay in a loop save energy?
I've noticed most example snippets always have a delay in the loop even if it's not needed for proper execution of the program.
I can only assume this is added because people copy and paste without understanding what's going on but it got me thinking if adding a delay could possible save power too.
If I have a loop that checks some inputs for changes could it be possible that adding a delay(10) saves some cycles and thus power?

No. Even a delay "uses" cycles.

Obligatory Nick Gammon reference: https://www.gammon.com.au/forum/?id=11497. All about energy.

@MarkLakata. What about yield()

@MarkLakata Multithreaded? In Arduino? 99.99% of the time there is no real scheduler, and in any case in the other 0.01% of cases the delay function does not "free" the calling thread (the delay implementation is just like a for loop doing nothing)

No, it burns energy by doing nothing.
You definitively should send your MCU to sleep and wake up on events or use the watchdog timer to wake up after a predefined period of time.

The delay function doesn't do anything special. It basically just counts down milliseconds inside a while loop and times it with micros().
void delay(unsigned long ms)
{
    uint32_t start = micros();

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Calling yield() is somewhat special, but yeah it's still a busy wait that spends most of the time running instructions.

@PeterCordes Calling yield() is nothing special.  That is just a (weakly defined) function that does nothing. It's there to allow other libraries or code to override it and implement some kind of cooperative threads, but the default code doesn't, so it does nothing. It's not like calling yield() in something like VB where it releases the program flow back to the OS...

@Majenko: Thanks, I assumed that yield implied a multi-tasking OS, not just a stub in case there was multi-tasking.  (And yeah, I was thinking it literally was POSIX sched_yield(2), and that this implied Arduino ran a full OS like Linux.  Hard to keep track of which dev boards (RPi / Arduino / whatever) run what when I don't use any of them myself. >.<)

No, a short delay (up to 100 millis) is usually inserted in a void loop() when you are attached to an external sensor, in order to stabilize the readings. But it has nothing to do with power consumption. As an example, here are lines 49-52 from the example sketch "AnalogInSerialOut":
      // wait 2 milliseconds before the next loop
      // for the analog-to-digital converter to settle
      // after the last reading:
      delay(2);

The answers above are wrong, at least for NodeMCU 0.9 (ESP-12 board) ESP8266 and I also tested with Firebeetle ESP8266 board. Since I have a USB tester I can check that if the loop method is empty, the boards consume about 70mA-80mA but during delay(ms) they consume about 20mA-30mA.
This is the delay function for the boards commented:
void __delay(unsigned long ms) {
    if(ms) {
        os_timer_setfn(&delay_timer, (os_timer_func_t*) &delay_end, 0);
        os_timer_arm(&delay_timer, ms, ONCE);
    } else {
        esp_schedule();
    }
    esp_yield();
    if(ms) {
        os_timer_disarm(&delay_timer);
    }
}

I have not investigate further why delay function saves so much power consumption.

could it be possible that adding a delay(10) saves some cycles and thus power?

No, the delay() function just pauses the code for the time specified. It's stil running and consuming energy for counting the time and waiting it to finish.
If you need to conserve power, you could adjust your circuit components in a fashion that will save energy, or if you want to save energy on your Arduino, you could use a breadboard setup(Instructions here and here) or make use of the internal watchdog timer to sleep and wake at certain time intervals. More tutorial about watchdog timer is explained here.
Cheers!

I suspect the answer depends on the kind of Arduino you're using.
The ESP8266 is ARM based, and I believe ARM chips include power management circuits, where subsystems are automatically put in low power state when they are not being used. An ARM-based Arduino will likely use a lot less power while executing a delay than while doing other things.
I don't think AVR chips have any sort of power management, so they have all their silicon "lit up" at all times. That said, CMOS logic circuits do use more power when switching states than when idle, so even an AVR-based Arduino will probably use slightly less power while in a delay() function that it will when it's running instructions that use the arithmetic unit, UARTs, and other subsystems of the chip.
You'll get much better power savings by putting your Arduino into sleep mode.

On AVR delay() uses the ALU.

Yeah, I guess it would use the ALU to see if enough time had passed. I meant that more as an example of the different subsystems of the chip than an accurate list, but point taken.

As stated in previous answers, at least on the AVR version of the
Arduino core, delay() is a busy wait that keeps the CPU running. In
his answer, Duncan C correctly states that “CMOS logic circuits do use
more power when switching states than when idle”. It is then expected
that instructions that switch a large number of gates or flip-flops
consume more power than instructions that only switch a few ones.
Out of curiosity, I disassembled a call to delay() to see what kind of
instructions it executes. I found that the “hot path” is a loop that
executes 44 instructions per iteration:

23 of them do arithmetic or logic (add, subtract, compare, XOR)
13 move data around (register load, register copy, I/O, read RAM)
7 alter the program flow (function call, return, jump, conditional
branches, conditional skip)
1 alters a bit in a status register

I do not know how this compares with “typical” code, but the large
proportion of instructions that do arithmetic and logic computations
suggests that delay() should be way more energy hungry than, say, a
long sequence of nop instructions. In the end, the only way to
know for sure whether delay() changes anything to the power
consumption of a specific program would be to measure it.
As a side note, an easy way to save some power on AVR boards is to
#include <avr/sleep.h> and insert a call to sleep_mode() at the end
of loop(). The sleep with not last for long though, as the Arduino
core sets Timer 0 to interrupt the CPU every 1024 µs.

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


text:
Send SMS Arduino Uno + SIM900A shield
I am working on a module to send messages. I write the message on the serial monitor + phone number and I have to send the message to the line.
Question:
How to send messages through the SIM900A shield?
Problem:
What am I doing wrong in my code? Because I do not get an error but it does not send the SMS using the shield.
Try:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600); // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  if (Serial.available()>0)
    switch(Serial.read()) {
      mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
      delay(1000); // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
      delay(1000);
      mySerial.println("sim900a sms");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
    }
  if (mySerial.available()>0) Serial.write(mySerial.read());
}

This is my shield

Other try:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600);  // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
  delay(1000);
  mySerial.println("sim900a sms");// The SMS text you want to send
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

And the question/problem is?

There is still no question.

now? help me please

There was not really a question, but I do notice there is no case's in your switch statement..
example from here
// do something different depending on the range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability

a need send message to shield

Are you wanted to send all those commands when ANY byte is received from Serial.read()?

the switch is to see if there is data or not in the serial, the question is. How to send an SMS with the shield?

@R.Fernandez That's not how switch statement works.

println() also adds a newline ( \n ) to the end of what you are sending, not sure if your module expects that or not, but you also have a return ( \r ) in one of your messages,   need to check to see exactly what the module expects


text:
Why is there a third connection to the host in this 3 wire current output sensor diagram?
I've got a 3 wire 4-20mA current output sensor, externally powered by 12V, which I want to read from an Arduino Uno (5V). The sensor connection diagram is below, but I don't understand why it says to connect the sensor power out (12V) to the host as well?
Below that is how I think I should connect it (i.e. with the power out from the sensor simply connected back to itself). Will this work? Could I damage my board or, far worse, the sensor itself this way?
Thanks alot!

If the sensor outputs 12V I wouldn't advice connecting it directly to an Arduino GPIO.

where did the diagram come from? Try it with a DMM and see what your ranges are

@dandavis Hi, try what with a DMM? The voltage across +UB and ground on the sensor? The diagram came from the datasheet for the sensor

@MichelKeijzers Hi, I know. I thought 3 wire sensors you can simply connect a 250Ohm shunt resistor to the current output, and measure the voltage drop across that, which should then only be 0-5V. But I don't understand why the diagram says connect the power supply to the host as well?

Digital Multi Meter; you can use it to tell if your setup works w/o frying your uno

The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.
All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

simulate this circuit – Schematic created using CircuitLab
In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good.  RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does).  D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.


text:
Use Wii Remote and Arduino to emulate a keyboard for Windows 10?
Is it possible to use an Arduino to communicate with a Wii Remote, connect the Arduino to a Windows 10 computer, and have the Wii Remote inputs be translated into keyboard keys for Windows 10?
I've used several Wii Remote Windows 10 apps, such as WiiUSoft, but I find such programs very unreliable.
Thanks for any help.

¿What is the purpose of that?

To use a Wii Remote as a simulated keyboard for Windows 10.

Not easily with an Uno. It can be done if you change the USB interface firmware. A Leonardo would be better.

The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard.  There are examples in the IDE that show how to do this.
It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible.  So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.
There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including a library), so couple that with the examples in the IDE and a suitable board and you are good to go.  From then on it's just a Simple Matter of Programming...


text:
Hold all "millis()" values in an array?
I'm working on a project where I could have up to six devices connected to an arduino, it might be the case that not all of them will be attached at the same time, and all of them need to be able to receive PWM signals but without using delay().
There are a number of different PWM patterns already programmed into the code, what I'd like to do is be able to assign more than one device to a single pattern, and start/stop the patterns at different times to different devices.
I have a python script (and soon an Android app) that sends a message in the following format to the device:
<int(pin_number), string(pattern_name), int(highest_pwm_value 0 - 255), int(delay_between_pulses_in_seconds)>
Is there some way of coding something like the following, and if so, how would I go about it?
array timings[];

void fade(unsigned long thisMillis, int fadeInterval, int maxPWM, int motor_pin) {
  if (thisMillis - timings[motor_pin] >= fadeInterval) {
    // yup, it's time!
    if (fadeDirection == 1) {
      fadeValue = fadeValue + fadeIncrement;
      if (fadeValue >= maxPWM) {
        // At max, limit and change direction
        fadeValue = maxPWM;
        fadeDirection = 0;
      }
    } else {
      //if we aren't going up, we're going down
      fadeValue = fadeValue - fadeIncrement;
      if (fadeValue <= minPWM) {
        // At min, limit and change direction
        fadeValue = minPWM;
        fadeDirection = 1;
      }
    }
    // Only need to update when it changes
    analogWrite(motor_pin, fadeValue);

    // reset millis for the next iteration (fade timer only)
    timings[motor_pin] = thisMillis;
  }
}

The bit that I'm unsure about is how the array should be defined etc, as I'm primarily a python developer so it's rare I have to explicitly set the type of an item in an array!

unsigned long timings[SOME_VALUE];

that actually already looks about right.

The answer given at https://forum.arduino.cc/index.php?topic=529364.msg3608306#msg3608306 is as follows:
struct motor_data {
   int id;
   unsigned long start_time;   //store time stamp here
   unsigned long duration;      //time ends    ...
};

motor_data motors[6] //declaration
motors[0].start_time = millis(); //accessing

Thoughts on this approach?

This is a classic example where you want to create a class.  A class will contain all the control logic for dealing with one pin - all the functions, all the variables, etc.
Then you just create as many instances of the class as you need for your different pins. Each one is completely separate from the other, and each one can be controlled at will.
For instance, you might make something like this (untested):
class FaderPin {

    private:
        uint32_t timestamp;
        int motor_pin;
        int fadeInterval;
        int minPWM;
        int maxPWM;
        int fadeDirection;
        int fadeValue;

    public:
        FaderPin(int pin, int minp, int maxp, int interval) {
            motor_pin = pin;
            minPWM = minp;
            maxPWM = maxp;
            fadeInterval = interval;
            fadeDirection = 1;
            fadeValue = minp;
            timestamp = millis();
        }

        void fade() {
            uint32_t thisMillis = millis();
            if (thisMillis - timestamp >= fadeInterval) {
                // yup, it's time!
                if (fadeDirection == 1) {
                    fadeValue = fadeValue + fadeIncrement;
                    if (fadeValue >= maxPWM) {
                        // At max, limit and change direction
                        fadeValue = maxPWM;
                        fadeDirection = 0;
                    }
                } else {
                    //if we aren't going up, we're going down
                    fadeValue = fadeValue - fadeIncrement;
                    if (fadeValue <= minPWM) {
                        // At min, limit and change direction
                        fadeValue = minPWM;
                        fadeDirection = 1;
                    }
               }
               // Only need to update when it changes
               analogWrite(motor_pin, fadeValue);
               // reset millis for the next iteration (fade timer only)
               timestamp = thisMillis;
           }
       }

};

Then you can:
FadePin motorOne(5, 0, 255, 10);
FadePin motorTwo(6, 0, 255, 10);

And regularly call:
motorOne.fade();
motorTwo.fade();

Divide and conquer.


text:
Why am I getting only around 40% the range of my ADS1115 using an Arduino Uno?
I've connected my ADS1115 to an Arduino Uno as in the diagram (Vdd - 5V, Gnd - Gnd, SDA/SCL - SDA/SCL), all powered from the USB on a PC, with A0-3 unconnected, and am getting readings of around 3000 (i.e. 3000/65535 on 5V supply = 0.23V) from all four analog pins. Then if I connect them to 3.3V output on the arduino they give me only 17625 (i.e. 1.34V) i.e. about 40% of the full range I expected. If I try with a seperate 5V supply, it's still the same problem. Why is this?
P.S. sorry the code format below isn't very good, but basically it reads the four pins by
int16_t V1 = ads.readADC_SingleEnded(PIN).

#define THERMISTORPIN1 0
#define THERMISTORPIN2 1
#define SHELLPTPIN 2
#define SPAREPIN 3
#include < Wire.h >
#include < Adafruit_ADS1015.h >

Adafruit_ADS1115 ads(0x48);  //16 bit ADC add-on for arduino for better temperature resolution
float Voltage = 0.0;

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

void loop(void)
{
    int16_t V1;
    int16_t V2;
    int16_t V3;
    int16_t V4;
    long cumV1;
    long cumV2;
    long cumV3;
    long cumV4;
    float avgV1;
    float avgV2;
    float avgV3;
    float avgV4;

    //take readings of voltages between resistor and thermsitor
    int i=0;

    while(i<6) {
        V1 = ads.readADC_SingleEnded(THERMISTORPIN1); //5 readings to allow the arduino capacitors to equalize with the pin voltage, to increase accuracy
        V2 = ads.readADC_SingleEnded(THERMISTORPIN2);
        V3 = ads.readADC_SingleEnded(SHELLPTPIN);
        V4 = ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    while(6<=i && i<16) {
        cumV1+= ads.readADC_SingleEnded(THERMISTORPIN1);  //multiple measurements from which to take an average, to increase precision
        cumV2+= ads.readADC_SingleEnded(THERMISTORPIN2);
        cumV3+= ads.readADC_SingleEnded(SHELLPTPIN);
        cumV4+= ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    avgV1=cumV1/10;
    avgV2=cumV2/10;
    avgV3=cumV3/10;
    avgV4=cumV4/10;

    //print out information to serial monitor on laptop
    Serial.print(V1);
    Serial.print(" ");
    Serial.print(V2);
    Serial.print(" ");
    Serial.print(V3);
    Serial.print(" ");
    Serial.println(V4);
    Serial.print(" ");
    Serial.print(avgV1);
    Serial.print(" ");
    Serial.print(avgV2);
    Serial.print(" ");
    Serial.print(avgV3);
    Serial.print(" ");
    Serial.println(avgV4);
    //Serial.println();
    delay(1000);
}

first off, single ended readings are only 15 bit. secondly, providing 3.3v will limit the measurement to 3.3v; 66% of 5v.

Your readings are correct because you have the default gain set. You have incorrectly assumed that you can convert the ADC reading from your 16-bit ADC to Volts by dividing by 2^16 - 1. Your ADC has gain settings to have more accurate readings for certain voltage intervals. If we look at the example sketch, we see
 void setup(void)
{
  Serial.begin(9600);
  Serial.println("Hello!");

  Serial.println("Getting single-ended readings from AIN0..3");
  Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

  // The ADC input range (or gain) can be changed via the following
  // functions, but be careful never to exceed VDD +0.3V max, or to
  // exceed the upper and lower limits if you adjust the input range!
  // Setting these values incorrectly may destroy your ADC!
  //                                                                ADS1015  ADS1115
  //                                                                -------  -------
  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
  // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
  // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
  // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

  ads.begin();
}

Your ADC has a default gain of 2/3, or 0.1875mV per count. You say when you connect 3.3V to the pin, you get a reading of 17625. Thus we have
17625 * 0.1875 / 1000.0 [V]
= 3.3046875 [V]

Which is a correct reading. A reading on a floating pin (nothing attached) is irrelevant. Use the correct factors from above to convert your read ADC value to voltage.
Side note: In line
avgV1=cumV1/10;

You have the float avgV1 on the left and cumV1 (a long) divided by 10 on the right; this will do a integer division. Make sure to divide by 10.0f if you want a floating point average.
Side note 2:
These factors do make sense. If you apply positive 6.144V on the 2/3rd gain setting, you will read the maximum positive value of a int16_t, i.e. 2^15-1 = 32767 (solve above formula for the count). If you apply -6.144V, you get -32768; thus the full 16-bit number space is used. On differnt gain settings it analogous.


text:
writing very long function
I'm writing an Arduino program, and I need to write a function to input some numbers trough a computer connected to it trough the serial interface.
This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.

What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:
class GetNumbers {
    public:
        //using the constructor as what I called "main" function
        GetNumbers(int arg1, char arg2) {
            performFirstAction();
            performSecondAction();
            ...
        }
    private:
        performFirstAction() {...};
        performSecondAction() {...};
        ...

        bool aSharedVariable;
        int anotherVariable;
        ...
};

And where I actually need to input those numbers from the computer:
GetNumbers uselessName (x,y);

Making the "main" function a normal class method (and not the constructor) seems to be even worse:
GetNumbers myClass;
myClass.getNumbers(x,y);
...
//somewhere else in the same scope
myClass.getNumbers(r,s);

And what is wrong with just using one big function? It sounds like, in this case, splitting it into multiple functions won't make it easier to read/understand. Just add plenty of comments, and add some extra newline between different sections.

Maybe it's my background of old C programmer but... I would just write
plain functions, no classes, like in C. And I would keep all this stuff
in a single file, to provide some form of encapsulation:
my_parser.h:
some_type get_numbers(int arg1, char arg2);

my_parser.cpp:
static int performFirstAction(float arg1, int arg2, char arg3)
{...}

static bool performSecondAction(long arg1, void *arg2, int arg3)
{...}

some_type get_numbers(int arg1, char arg2)
{...}

Note that there is only one function declared in the .h: this is the
“interface” to your module. Note also that all the other functions are
defined as static. This tells the compiler to keep them hidden from
the linking phase, so they do not pollute the global namespace. And
finally, note that there is no global shared variable: everything is
passed as arguments to the functions.
The rationale for the last point is that this helps the compiler
optimize things. A static function that is called only once is almost
guaranteed to be inlined by the compiler. Which means there is no
overhead in passing the arguments. On the other hand, if you use global
variables and the compiler doesn't manage to optimize them away, you
will incur the cost of RAM access.

I second that. Classes are for things that have data+methods. For a bunch of unrelated random functions, old style C functions are good enough. Try written a callback using C++ class method ...


text:
Initialization of function pointer array
I have an array of function pointers:
unsigned int dimension = 8;
void (* myFunctions [dimension])();

This array is a member of a class:
class myClass {

    static const unsigned int dimension;

    void (* myFunctions [dimension])();
}

and in a cpp file:
const unsigned int dimension = 8;

It's size is known at compile time, but it's values will be added through a public method in unknown parts of the code. I need to be able to find out at any time whether there is a valid pointer at some index in that array at any time, and my idea was to do that by comparing the pointer against nullptr: if it doesn't equals it then I'll assume that it holds a valid function pointer.
I was wondering if I need to initialize the array before making that kind of speculation. How is this array initialized if I only write the above two lines of code? Can I assume something like myFunctions[x] ==  nullptr is true in that case? Or do I need to do an explicit initialization like the following one?
for(int i = 0; i < dimension; i++)
    myFunctions[i] = nullptr;

Is this a global variable or within a class that is constructed or what? Could you provide a simple example of the source code in which this is used?

see also https://stackoverflow.com/questions/14071378/c-initialize-an-array-of-pointers-to-functions

@RichardChambers of course, I'll edit

You should actively zero-initialize your pointers in the constructor of your class.
The "zero-initialization" of the C++ language only applies in certain cases defined here. In certain configurations, e.g., when the object of the class has an explicit constructor which does not initialize the array, or when the class has no constructor and an object is function-locally created by typing myClass myObject;, the pointers are not initialized to nullptr.
They do get automatically zero-initialized via the C++ standard without you doing anything if an object of this class is declared and defined as a global variable, though. Then you have a "static storage location", and your object is zero-init'ed by zero-init'ing every data member. Your array of function pointers gets then member-wise zero-init'ed to the zero-value of a pointer, i.e., nullptr.
But you should write robust code which is always correct regardless of which kind of method is used to instantiate the object. Thus, the for loop in the constructor as you have it is correct.
See the analogous question I asked here (which I asked because I gave an initially wrong answer and felt responsible).

It's seem like the array is initialized with nullptr. I got to read the 1,600 pages C++17 specification to be sure. Meanwhile, I test.
You can always initialize explicitly the array, in the constructor.
Here a brief proof of concept for you to try. (I made public the class member to keep things short).
//  An empty function, do nothing
void someFunction()
{

}

class MyClass
{
public:
    MyClass()
    {
        for(int i = 0; i < dimension; i++) {
            myFunctions[i] = someFunction; // Replace with nullptr to test.
        }
    }

static const unsigned int dimension = 5;
void (*myFunctions[dimension])();
};

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

    while(!Serial);

    MyClass test;

    for(auto x : test.myFunctions) {
        if(x == nullptr) {
            Serial.println("null");
        } else {
            if(x == someFunction) {
                Serial.println("some function");
            } else {
                Serial.println("????");
            }
        }
    }
}

void loop()
{

}

I have a contra-example for when "It's seem like the array is initialized with nullptr" is not true: Class has no constructor, object is instantiated on the stack with MyClass test; will have non-nullptr (random) values. https://pastebin.com/h12NKNxg

@MaximilianGerhardt. C++, a language with both "&&" and "and".


text:
Is an Arduino Uno required to send any sort of command to a NodeMCU?
I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.
Actually I did not send commands the first time I bought it. I flashed it with a deauther program made by spacehuhn then I erased the chip using the esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash command multiple times. Then I heard that you can send commands to the NodeMCU using the Serial Monitor using Arduino. So I tried it but no output. So my question is whether I need an Arduino Uno or has the command which I used to erase the factory code of the NodeMCU broken something?
PS. I am a newbie so I don't know much of this stuff.

With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with Flash Download Tool (Windows only).
AT firmware download page
Addresses for 4 megabyte flash (more in readme.md of AT firmware):
esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin

Thanks for your help I just needed to edit your command like this esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x3fe000 blank.bin Now the commands work fine.

I have another question. If I flash another program on my nodemcu will the original firmware be overwritten?

you did that with deauther .. do you not learn from your actions?

@jsotola I can't understand what you're saying.

the AT firmware is nothing special in esp8266. other firmwares exist or you can create your own programs with espressif SDK or with Arduino esp8266 core package

Like 99.999% of all MCUs the ESP8266 can only hold one program in flash at a time - be that "deuther", the "AT" firmware, or your own custom program. As soon as you install one the last one is removed.


text:
Arduino MQTT Bluetooth
Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?

MQTT is TCP/IP native. If you want to access it via Bluetooth, you need a gateway; a device that translate protocols. You need one for the specific protocols involved: MQTT, TCP/IP and Bluetooth.
Google "MQTT Bluetooth gateway" to find alternatives like this one:

The iGS01 gateway listens for beacons, gets their advertising data and
  forwards it on to your server or an IoT server via TCP, HTTP(S) or
  MQTT. It can be used to feed back-end systems that report on the
  presence or absence of iBeacon or Eddystone beacons or act on beacon
  sensor (e.g. accelerometer, temperature, light, humidity) data.

The gateway connects to your local 2.4GHz frequency band WiFi access
  point and is managed via a web browser interface. It can  be connected
  via WPS (press button on both the gateway and the WiFi access point).
  It can also be managed via Telnet commands from other hardware (or a
  human).
For MQTT/MQTTS, the host, port, username, password and a root CA cert
  can be provided.

There are also software only solutions available, but I didn't found a generic one, only specific for certain vendors.


text:
Can I support all these sensors?
I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
a Gyro Sensor
an Accelerometer
and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

Did you check what kind of interface they have? And an ESC is not a sensor.

@gre_gor It is... it "senses" a PWM signal from some external source and sets the speed of the motor proportionally ;)

Thanks for the responses! I just included the ESC case it takes up some ports on the Arduino as well. Here is some information on each sensor: The load amp i'm using is a HX711 which outputs VDD to 5v, DAT to port 3, CLK  to port 3 and GND to GND respectively, but I have two separate amplifiers. I'm using a Gyro and Accelerometer in one (MPU6050) which outputs VCC to 5v, GND to GND, SCL to A5, SDA to A4 and INT to port 2 respectivly. The ESC connects to the 5v, GND and port 9.

@Gian.Pit it would be best to edit that info into your question. Comments are ephemeral.

Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.
All in all this needs 7 pins, way less than an Arduino UNO has.
Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.

you are always only "reading" one at a time in linear programing. But given the list that was provided I do not see any reason that anything would need to be "disabled"   Like, the ESC may only be updated so often, or the gyro/accelerometer might only be read from every so often, but they are still enabled and functioning.

It really depends on how many pins each sensor uses. The signal pins of all the sensors used would have to be equal to or less than the total number of I/O pins on the arduino, which would be 20. So you can control 20 sensors if they each have one signal pin.
However, to control more sensors (or use a lower pin count on arduino) you can use multiplexing. See Two sensors on one input or MULTIPLEXING WITH ARDUINO AND THE 74HC595.
Theoretically, you can control an infinite number of sensors with the use of multiplexing.

You are not taking into account the type of signals produced by your "Sensors"  If you were talking single pin digital sensor("Switch") then you are kinda correct,  there still is no way (even theoretically) you can say you can support infinite number of sensors since you have to be able to address them some how.   But most sensors (like the ones listed in the question) use some sort of protocol, (I2C, SPI, UART) and that greatly effects the number(and method) that can be used by a single uno.


text:
Failed to initialise SD card on Leonardo
I'm trying to connect SD card reader to my Arduino. For testing i'm running CardInfo example.
It seems like it runs ok when I'm running it on my Arduino UNO, but it fails to initialise SD Card while i'm running it on any Arduino with Atmega32U4 chip. I tried on two Leonardo's and Micro Pro.
This is my pinout:
CardReader       Arduino

CS          <->     4
SCK         <->    13
MISO        <->    12
MOSI        <->    11
VCC         <->    5V
GND         <->    GND

I'm using Library in version 1.2.1 if that's make difference.
Does anyone have any suggestions?

A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

And a Pro Micro has the SPI pins on 14, 15, 16.

I remember i used different pins on pro micro, but i really thought i used exactly same on Leonardo and Uno. I bit panicked after suddenly my card stopped working on both boards.


text:
Uniform timing when using Arduino for data acquisition
I am using Arduino UNO together with a SPI ADC (LTC1859) and SRAM (23CL1024) to record a series of data points at approx 2 kHz sampling rate (let's say a few thousand data points).
I have some questions about how to ensure the data points are sampled at uniform time intervals, down to the precision of a clock cycle.
What are the limitations of Arduino macros in respect to this?  Can I replace SPI.transfer() with some lower-level code that will make an improvement?
Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?
The time-critical part of my code is as follows, and I'd appreciate suggestions:
**RE-EDIT.  As has been requested, the ADC is LTC1859 and triggers on the slave select falling edge active high of input on the CONVST pin, which is the same time that I make ADC SS low (first line inside the for loop).
Digital outputs:
CONVST  = Port B, bit 2
SS ADC  = Port B, bit 1
SS SRAM = Port B, bit 0
      for(unsigned int i=0;i<DATA_LENGTH;i++){
        PORTB=B11000101;                     // ADC Slave select
        __builtin_avr_delay_cycles(112);     // ADC conversion time
        DATA_MSB=SPI.transfer(ADCbyte1);     // Get 16-bit ADC value as 2 bytes
        DATA_LSB=SPI.transfer(ADCbyte2);
        PORTB=B11000010;                     // SRAM Slave select
        SPI.transfer(WRITE);                 // Write data value to SRAM as 2 bytes
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 16)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 8)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS));
        SPI.transfer(DATA_MSB);
        SPI.transfer(DATA_LSB);
        PORTB=B11000011;                     // Deselect both ADC and SRAM slaves
        DATA_ADDRESS++;
        DATA_ADDRESS++;
        __builtin_avr_delay_cycles(7600);    // Delay makes 1/sampling rate.  7600 = 2 kHz
      }                                      // Repeat for number of data points

**EDIT.  Also, I have done some further tests and replaced occurrences of SPI.transfer(data);  with SPDR = data; followed by waiting a constant number of clock cycles to ensure the data clears.  I checked out the timing accuracy by measuring a sine wave voltage input and analyzing the FFT of the recorded data.  Overall timing accuracy was improved but I do not see evidence that this part of code limits how uniformly the data are sampled.  I have not tried Nick Gammon's suggestion yet to use timer interrupts.
Below is an example of the real-world data that I am recording.  The ADC is digitizing data at 16 bit, 2 KHz from a magnetometer with around 10-15 T/Hz1/2 sensitivity, then passing to a PC running Qt where I plot the time-domain data and frequency-domain data after FFT.
The signal is laboratory magnetic background and contains harmonics of the 50 Hz line frequency from mains cables etc.  The point of showing the data is that I am not stuck getting the data acquisition to work. I want to improve the data acquisition code as far as possible within the limits of Arduino.

SOLUTION: I modified Edgar Bonet's code in the accepted answer to use timer1 for PWM control of ADC trigger (CONVST, OC1B = Arduino pin 10).  This worked successfully.
Learning points for me were:
(1) much greater accuracy in ADC sampling rate. The resonator frequency is accurate enough for my purposes at kHz sampling that I don't need fiddly calibrations of for loop duration;
(2) much better way of programming a DAQ.  Using the state machine concept, I can run other processes in parallel with the DAQ without penalties in timing accuracy.
void loop(){

switch (statemachine){

// other cases, including reading serial data from PC

case 2: // Initialize data acquisition
cli();
data_address=0;
data_counter=0;
statemachine=3;
TCCR1A=0;
TCCR1B=0;
OCR1A=124; // 16 MHz / (64 * 125) = 2000 Hz
OCR1B=1;
TCCR1A = _BV(COM1B1)  // Clear pin OC1B on compare match, set at BOTTOM, noninverting
| _BV(WGM10)          // fast PWM mode 15, TOP = OCR1A
| _BV(WGM11) ;        // fast PWM mode 15.
TCCR1B = _BV(WGM12)   // fast PWM mode 15
| _BV(WGM13)          // fast PWM mode 15
| _BV(CS11)           // Set timer prescaler to 64.
| _BV(CS10) ;         // Set timer prescaler to 64.
TCNT1=0x03;
TIFR1 |= _BV(OCF1A); // Clear match flag
break;

case 3: // Acquire data and store.
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= _BV(OCF1A);              // Clear match flag
PORTB=B11000101;                  // ADC SS
__builtin_avr_delay_cycles(160);  // 10 us
msb=SPI.transfer(ADCbyte1);
lsb=SPI.transfer(ADCbyte2);
PORTB=B11000010;                  // SRAM SS
SPI.transfer(WRITE);
SPI.transfer((uint8_t)(data_address >> 16) & 0xFF);
SPI.transfer((uint8_t)(data_address >> 8)  & 0xFF);
SPI.transfer((uint8_t)(data_address));
SPI.transfer(msb);
SPI.transfer(lsb);
PORTB=B11000011;
data_address++;
data_address++;
data_counter++;
if(data_counter==data_length){statemachine=4;} // Data capture complete
break;

// other cases, including data transfer to PC
}
}

You should consider triggering the most time-critical part of your code using a hardware timer rather than delay loops.

You think the for() loop is the most likely source of error?  I have considered hardware timing but thought that each SPI.transfer() waits for an interrupt to conclude the transaction.  If I did do hardware timing, what timer of the AVR is best to use?  Note that I care most about uniform timing and not absolute accuracy.

First thing you need to do is look at the chip data sheet and see exactly what triggers a conversion.  Is it a particular part of the SPI cycle, like a given clock or deassertion of the select?   Is there an option to use a distinct signal to trigger it after priming it with the SPI?   Or is this one of the ADCs where the a successive-approximation conversion is directly clocked by the SPI, and any jitter in the SPI clock contaminates your measurement?  If you do keep software in the critical loop, you'll want to disable the interrupt that advances the Arduino millis()

The way I am triggering the ADC should not be an issue as it is rated to 100 ksps.
My question was specifically about the Arduino code and how to improve it.  For example, if SPI.transfer() (and there are 8 of them to handle each data point acquisition) has the potential to add a few microseconds here/there.

DATA_ADDRESS++; - as a convention, don't use all capitals for variables. All capitals are usually used for constants.

Again, you need to read the data sheet and determine what actually governs the timing of the ADC.  It's not a question of speed but of which specific action (or actions) causes the ADC to take a reading.  Whatever that is, it is what you need to remove jitter from.

Please, edit the question to provide the missing information you have been asked for: what specific action triggers your ADC? We cannot provide any meaningful answer without this. If you cannot find it, then provide a link to your ADC's datasheet. In the meantime, I'm voting to close the question, and I will retract my vote if you provide the info.

Since pretty much the same code is called every cycle, the timing should be pretty uniform. Do you measure how long it takes to do a few thousand acquisitions? If you do that, you can calculate the sampling rate, and see if you can get close to 2kHz by tweaking the delay at the end __builtin_avr_delay_cycles(7600);.

Edgar Bonet: I have provided info about the ADC, which triggers on slave select falling edge.

@Gerben - measuring across a lot of samples averages the timing - that's important for things like buffer usage, but it doesn't reveal if there is jitter to the samples or the clock which may be used to measure them.

the ADC is LTC1859 and triggers on the slave select falling edge.

No, it doesn't. Here is a link to its datasheet. It has a pin
labeled CONVST, for “conversion start”. According to the section Pin
functions, “This active high signal starts a conversion on its rising
edge.”
If you want your sampling to be at 2 kHz with cycle-accurate
timings, you have to send to this pin a train of pulses which are at
least 40 ns wide and have a period of 500 µs, i.e.
8,000 CPU cycles. This can be done with any of the three timers of
the Uno. For example, you can set Timer 2 to repeatedly count from
0 to 124 with a prescaler of 64. Your initialization would have
something like this:
// Initial transfer to configure the ADC.
PORTB &= ~_BV(SS_ADC);
SPI.transfer(ADCbyte1);
SPI.transfer(ADCbyte2);
PORTB |= _BV(SS_ADC);

// Configure Timer 2 for PWM on pin OC2B = PD3 = digital 3.
DDRD  |= _BV(PD3);    // pin PD3 as output
TCCR2A = 0;           // undo the Arduino core's configuration
TCCR2B = 0;           // ditto
OCR2A  = 125 - 1;     // period = 64 * 125 CPU cycles = 500 us
OCR2B  =   2 - 1;     // high for 64 *   2 CPU cycles =   8 us
TCNT2  = 122;         // first pulse in 8 to 12 us
TIFR2 |= _BV(OCF2B);  // clear the output compare flag
TCCR2A = _BV(COM2B1)  // non-inverting PWM on pin OC2B
       | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
       | _BV(WGM21);  // ditto
TCCR2B = _BV(WGM22)   // ditto
       | _BV(CS22);   // clock at F_CPU/64

Note that the timer will also set a flag when the pulse is done, at
which time you can start the data transfer. You would then start your
data-taking loop with:
// Wait for the output compare flag.
loop_until_bit_is_set(TIFR2, OCF2B);

// Clear the flag.
TIFR2 |= _BV(OCF2B);

// Now transfer the data.
...

Edit 1: I would just want to add that cycle accurate timing does
not mean perfectly uniform timing. The Arduino Uno is clocked off a
ceramic resonator. This kind of resonator, in addition to having bad
accuracy, has poor frequency stability. To get an idea of how bad it can
be, see the Allan deviation plots on the article Arduino clock
frequency accuracy, by Joris van Rantwijk.
Edit 2: After some tests, I wrote a more complete initialization:

An initial SPI transaction is used to prime the ADC, as suggested by
Chris Stratton
the PWM pin is configured as an output
the Arduino core's Timer setup is undone before applying the new
configuration
the very first pulse on CONVST is scheduled to happen not too long
after the initialization, yet after tACQ
the output compare flag is cleared during the initialization.

Yes, though to clarify, the conversion must be primed by an SPI operation, then the actual measurement triggered by CONVST.  Typically the way to get regular spacing is to have software prime early, and then as wisely shown here have a hardware timer trigger the actual conversion at more evenly spaced intervals than software will normally achieve.  Then software claims the data and prime for the next.

You are right, and that was sloppy of me.  The conversion is triggered by CONVST which happens to be the same time that I slave-select the ADC.  Thanks for the info on hardware timer interrupt, I'll investigate that.

@MichaelT: I think you misread my answer. I am not suggesting you use a timer interrupt, I am suggesting you use a timer to generate a low-jitter trigger signal for your ADC. Then you can use an interrupt flag (namely OCF2B) to know when it is safe to do the data transfer. Note that the interrupt flag is independent from the actual interrupt mechanism: it can be used when the interrupt is disabled, which is the case here. I am suggesting a polling, rather than interrupt based, approach. Of course, you can do interrupts if you prefer, but you don't have to.

OK, got it.  I will try that approach and append the findings to my original posted question.  I think it will be interesting to compare with the code I have been using so far and see if there is much difference.

Thanks, in the end I used timer1 not timer2.  While I don't need the 16-bit timer resolution, timer1 controls PWM on Arduino pin 10 and that saves me making a new circuit board/"shield" for the ADC, for the time being.  I'll post the code in the main question

I did a project generating VGA signals that required highly precise timing for the sync pulses.
The technique that worked for me was:

Use the hardware timers to generate the required pulse interval
Put the processor to sleep (set_sleep_mode (SLEEP_MODE_IDLE);) to remove jitter caused by whether the interrupt occurred while an instruction was executing (interrupts can't interrupt half-way through a multi-cycle instruction).

So in your case I would set up the timer (eg. Timer 1) to generate the appropriate interrupts. Then go to sleep waiting for the interrupt. The ISR doesn't have to do anything in particular, you just want to pause until the interrupt happens. For example you could do this:
EMPTY_INTERRUPT (TIMER1_COMPA_vect);

That will generate a "do nothing" interrupt handler for Timer 1 compare-A vector.
Once the interrupt happens you will pass the sleep instruction and then you can do your ADC sample and send the results. You may want to scale back the ADC clock a bit (eg. a prescaler of 64) to speed up the ADC sample a bit.
See my page about the ADC and my page about interrupts.

Automatic mode
Another possibility is to use the automatic ADC conversion, as in this example from my page about the ADC:
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

The code above will take 256 samples at 50 kHz frequency. You could modify the ISR to send the results by SPI (SPI transfers should be OK inside an ISR) if you needed to take more samples and save them elsewhere.

Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?

No, I don't think so.


text:
'import' does not name type ERROR
I am working with a group of people on an arduino controlled BB8 robot. We are using an IMU unit (accelerometer+gyroscope). I found a processing example for the IMU unit we are using. The code is shown below. I am getting an error "'import' does not name type". I know programming but I am not very familiar with arduino. Can anyone help me?
import processing.serial.*;

Serial myPort;  // Create object from Serial class

final String serialPort = "/dev/tty.usbmodem621"; // replace this with your serial port. On windows you will need something like "COM1".

float [] q = new float [4];
float [] hq = null;
float [] Euler = new float [3]; // psi, theta, phi

int lf = 10; // 10 is '\n' in ASCII
byte[] inBuffer = new byte[22]; // this is the number of chars on each line from the Arduino (including /r/n)

PFont font;

void setup()
{
  size(800, 600, P3D);
  myPort = new Serial(this, serialPort, 115200);

  font = createFont("Courier", 32);

  /*
  float [] axis = new float[3];
   axis[0] = 0.0;
   axis[1] = 0.0;
   axis[2] = 1.0;
   float angle = PI/2.0;

   hq = quatAxisAngle(axis, angle);

   hq = new float[4];
   hq[0] = 0.0;
   hq[1] = 0.0;
   hq[2] = 0.0;
   hq[3] = 1.0;
   */

  delay(100);
  myPort.clear();
  myPort.write("1");
}

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  if (inString.length() == 8) {
    inData[0] = (byte) unhex(inString.substring(0, 2));
    inData[1] = (byte) unhex(inString.substring(2, 4));
    inData[2] = (byte) unhex(inString.substring(4, 6));
    inData[3] = (byte) unhex(inString.substring(6, 8));
  }

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  return Float.intBitsToFloat(intbits);
}

void readQ() {
  if (myPort.available() >= 18) {
    String inputString = myPort.readStringUntil(lf);
    //print(inputString);
    if (inputString != null && inputString.length() > 0) {
      String [] inputStringArr = split(inputString, ",");
      if (inputStringArr.length >= 5) { // q1,q2,q3,q4,\r\n so we have 5 elements
        q[0] = decodeFloat(inputStringArr[0]);
        q[1] = decodeFloat(inputStringArr[1]);
        q[2] = decodeFloat(inputStringArr[2]);
        q[3] = decodeFloat(inputStringArr[3]);
      }
    }
  }
}

void buildBoxShape() {
  //box(60, 10, 40);
  noStroke();
  beginShape(QUADS);

  //Z+ (to the drawing area)
  fill(0,255,0);
  vertex(-30, -5, 20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  //Z-
  fill(0,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, 5, -20);
  vertex(-30, 5, -20);

  //X-
  fill(255,0,0);
  vertex(-30, -5, -20);
  vertex(-30, -5, 20);
  vertex(-30, 5, 20);
  vertex(-30, 5, -20);

  //X+
  fill(255,255,0);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(30, 5, -20);

  //Y-
  fill(255,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(-30, -5, 20);

  //Y+
  fill(0,255,255);
  vertex(-30, 5, -20);
  vertex(30, 5, -20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  endShape();
}

void drawCube() {
  pushMatrix();
  translate(800/2, 600/2 + 50, 0);
  scale(5, 5, 5);

  // a demonstration of the following is at
  // http://www.varesano.net/blog/fabio/ahrs-sensor-fusion-orientation-filter-3d-graphical-rotating-cube
  rotateZ(-Euler[2]);
  rotateX(-Euler[1]);
  rotateY(-Euler[0]);

  buildBoxShape();

  popMatrix();
}

void draw() {
  background(0,0,0);
  fill(255,255,255);

  readQ();

  if (hq != null) { // use home quaternion
    quaternionToEuler(quatProd(hq, q), Euler);
    text("Disable home position by pressing \"n\"", 20, 600 - 30);
  }
  else {
    quaternionToEuler(q, Euler);
    text("Point FreeIMU's X axis to your monitor then press \"h\"", 20, 600 - 30);
  }

  textFont(font, 20);
  textAlign(LEFT, TOP);
  text("Q:\n" + q[0] + "\n" + q[1] + "\n" + q[2] + "\n" + q[3], 20, 20);
  text("Euler Angles:\nYaw (psi)  : " + degrees(Euler[0]) + "\nPitch (theta): " + degrees(Euler[1]) + "\nRoll (phi)  : " + degrees(Euler[2]), 200, 20);

  drawCube();
}

void keyPressed() {
  if (key == 'h') {
    println("pressed h");

    // set hq the home quaternion as the quatnion conjugate coming from the sensor fusion
    hq = quatConjugate(q);
  }
  else if (key == 'n') {
    println("pressed n");
    hq = null;
  }
}

// See Sebastian O.H. Madwick report
// "An efficient orientation filter for inertial and intertial/magnetic sensor arrays" Chapter 2 Quaternion representation

void quaternionToEuler(float [] q, float [] euler) {
  euler[0] = atan2(2 * q[1] * q[2] - 2 * q[0] * q[3], 2 * q[0]*q[0] + 2 * q[1] * q[1] - 1); // psi
  euler[1] = -asin(2 * q[1] * q[3] + 2 * q[0] * q[2]); // theta
  euler[2] = atan2(2 * q[2] * q[3] - 2 * q[0] * q[1], 2 * q[0] * q[0] + 2 * q[3] * q[3] - 1); // phi
}

float [] quatProd(float [] a, float [] b) {
  float [] q = new float[4];

  q[0] = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3];
  q[1] = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2];
  q[2] = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1];
  q[3] = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0];

  return q;
}

// returns a quaternion from an axis angle representation
float [] quatAxisAngle(float [] axis, float angle) {
  float [] q = new float[4];

  float halfAngle = angle / 2.0;
  float sinHalfAngle = sin(halfAngle);
  q[0] = cos(halfAngle);
  q[1] = -axis[0] * sinHalfAngle;
  q[2] = -axis[1] * sinHalfAngle;
  q[3] = -axis[2] * sinHalfAngle;

  return q;
}

// return the quaternion conjugate of quat
float [] quatConjugate(float [] quat) {
  float [] conj = new float[4];

  conj[0] = quat[0];
  conj[1] = -quat[1];
  conj[2] = -quat[2];
  conj[3] = -quat[3];

  return conj;
}

You can't put Processing code onto an Arduino.

While you could painfully translate this, what you probably want to do is find an Arduino library and/or example for the sensor chip you are using.

One of the most important things people have to realize when they program is that when an error occurs on a product, the chances of someone else having the same error and reporting that error on the internet is highly likely. Unless the product is brand new, there's no way that you would be the first one to encounter this error. Another important thing that new programmers should remember is that when they find code online, there's a tendency of the code not working. Henceforth, you need to debug and evaluate the code yourself.

Frankly this seems a rather harsh response to a relatively innocent and simple to explain mistake which could nonetheless be quite perplexing when encountered.  Let's not forget that Arduino has shared heritage with Processing and that they are sometimes spoken of together, despite having different syntax and targets.

Processing code is intended to be run on a computer. You would use the Processing IDE to run this code.
The Arduino IDE is used to write, compile, and upload code to a microcontroller that you might have on an Arduino board. This is the cause of the error.


text:
Outputs/inputs to Multiple Arduinos in Arduino IDE at once
I apologize if this information could be easily accessed, but I'm new to Arduino and did multiple searches.  I'm currently able to write to one Arduino Trinket in Arduino IDE using digitalWrite. However, I'll have to be reading from two different Arduino Trinkets with analogRead.  An important part of this is that I must be able to access both devices at the same time.  I saw during research that other people were able to use two different Arduino IDE instances, but I don't think this will work for me.  I'll more than likely soon be purchasing 2 Arduino ItsyBitsy's or nano's for the serial USB communication.  Let me know if this would make the issue easier.  I appreciate any help!

Thanks for the response, Juraj!  I have a better idea of the theory and terminology now, but I'm still not sure how to go about doing the operations I mentioned in Arduino IDE or any other IDE.  Would PlatformIO work better?

To collect data from multiple Arduinos at the same time you will likely have to use the Arduino IDE only for writing and uploading code one at a time, but something else for collecting data from both at once.  If you need to graph it you might look into Processing or Numpy or Matlab or whatever strikes your fancy.

Use UECIDE (http://uecide.org). You can have multiple instances running out of the box and debug (via Serial Monitor) several boards at the same time.

Also asked at: http://forum.arduino.cc/index.php?topic=530546 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

I'm currently attempting to do what I described in platformio with 2 Uno Arduinos following this https://xcorr.net/2016/12/13/multi-arduino-projects-with-platformio/ vaguely.

Arduino IDE is editor and builder. Your sketch runs on microcontroller and the microcotroller doesn't need the IDE to run it. The Serial prints from microcontroller go to com port from which any Terminal app can show them, not only the Serial Monitor build-in in IDE.
Connect both arduinos of same type to computer. They will have different ports. Upload your sketch to the first one, then change the port setting in IDE and upload to second arduino.
Serial Monitor can show you the output of arduino connected to the selected port. Switch port in Tools menu and reopen Serial Monitor to see the output of the second arduino.
To display booth at once, there are some options with different difficulty level:

use two instances of a terminal program like PuTTY Terminal Emulator to show the output
connect the TX pins of arduinos together
send data from one arduino to the second and let the second process them

Once again thanks for the response.  Following this there's still an issue of having to change the port in the IDE.  I should've been clearer about this in my questionm but I need to be comparing the voltages from the arduinos at the same time as they are read in.

and why two arduinos for that? one arduino can read two voltages

Thanks for the quick response.  I'm doing a project that involves pressure sensors on the soles of a user's feet.  It seems that the first option would be most appropriate in this case right?

it depends on the setup of the hardware. how long can be the cable between sensor and arduino? what is the end setup? only to show the values on a computer?

For now, the cable length doesn't matter.  No, there will be some comparisons and math operations to analyze posture

I would recommend to use only one arduino on a belt


text:
Serial communication between two microcontrollers w/ separate power supplies
Fair warning: I'm an electronics n00b.
I'm trying to get an Arduino Uno R3 to send data over 9600 baud serial to a Wemos D1 Mini Pro.
What worked (mostly):
Powering (5V) Arduino off a 4 AA barrel jack battery pack.  Measured voltage between Vin and GND as ~4.5V (the batteries were somewhat old).  4.5V is low enough to be safe as 5V input for the (3.3V) Wemos, which can be powered off its 5V pin (it's the input to the board's 3.3V regulator).  I tied the Arduino's GND and Wemos's, took the Arduino's Vin pin to Wemos's 5V pin (providing it ~4.5V), and connected Arduino's TX to Wemos's RX via a voltage divider (a 2.2 kΩ resistor and a 4.7 kΩ; verified <3.3V with a multimeter).
And, everything worked, for a few brief, glorious minutes.  Arduino sent 1 byte over serial every 3 seconds, alternating the builtin LED each time.  Wemos read them and served up a web page showing the latest values.  But, after a few minutes, the Wemos started to read data the Arduino shouldn't be sending (0x00 bytes; the Arduino program was only sending uppercase ascii letters).  I noticed that the Arduino builtin LED, that's supposed to be alternating every 3s, was blinking rapidly.  I think I drained the batteries too far to provide both the Wemos and the Arduino with enough power, and the Arduino got stuck in a boot cycle (and I suppose it's sending 0x00 over its TX pin while booting).
What didn't work:
Since changing batteries frequently would be a pain, I tried plugging the Wemos into a micro USB wall adaptor, and the Arduino into a 12V 1A barrel jack wall wart, and unplugging Arduino's Vin from Wemos's 5V (leaving GND tied together).  Plugged both adaptors into a single power strip, and turned it on.  Both boards powered up, and were running their programs (I could connect to the Wemos over WiFi and it would serve me a page; the Arduino builtin LED was alternating every 3 seconds as expected).  A multimeter read the voltage between Wemos RX and GND as 3.34V, but the Wemos wasn't receiving any serial data.
After that experiment, I switched back to the battery pack, wired Arduino Vin to Wemos 5V again, swapped out 2 of the 4 batteries, and everything works.
TLDR:
I powered a 5V Arduino off 12V and a 3.3V Wemos off 5V, and the Wemos couldn't read serial data being transmitted by the Arduino.  When I powered them both off a 4.8V battery pack, everything worked.  Why didn't it work when they had separate supplies and a common ground?
Sorry for the wordy question; I'm confused enough to not know which details are relevant!

wasn't the 5 V usb adapter some smart type charger with usb communication to negotiate the charging current?

power the wemos Vin (5 V) from 5 V of arduino with arduino connected to 12 V adapter

Not sure about the smartness of the USB charger... I've gotten the impression that the Arduino's 5V regulator might not be able to source enough current to power a Wemos. I found a reference earlier today to ESP8266's drawing up to 850 mA under heavy WiFi load, and https://electronics.stackexchange.com/questions/67092 says that the Arduino 5V can source less than 900 mA if Vin is above 7V. Anyway, I'm not really looking for workarounds (I plan on trying a USB power bank next) - I'm more interested in learning why it didn't work.

I do not believe that 850 mA. The 5 V pin is not a workaround, it is it's purpose. 2) You could try for wemos a simple AC/DC (USB) adapter without data lines connected. The data lines go over USB chip to Rx/Tx pins. 3) Charging power banks turn off if only small current is drawn.

Your question is interesting and useful to others, but it's tooo looong. Delete most of it, keep the TLDR (which is all we need to know) and add schematics to show the alternatives. A short question is better than a long one.


text:
Charge 14500 LiFePO4 lithium batteries from an Arduino Nano
I've recently started tinkering with Arduino, and I'm attempting to build a little 2WD robot based on an Arduino Nano.
I was thinking of powering the robot using two 14500 LiFePO4 batteries, which I understand will fit in a standard 2 x AA battery holder, and in series will give me about 6.4V, which should be ideal.
If I were instead going to use AA batteries, I think I'd need 4 of them, which will make my robot a fair bit bulkier.
I would like to be able to charge the batteries simply by plugging a standard USB cable into the Nano's USB socket.
Is there some easy way to safely do this? Do I need a separate charging module board, or is there some way to do it directly from the Nano?

No, you cannot charge a Lithium-Ion battery (of any variant) directly from an Arduino. You require a Lithium-Ion battery charge controller.
The best source for these kinds of things at a small size is retailers of model vehicle parts.

Specifically a  Lithium iron phosphate compatible charger.

Would you happen to know if something like the TP4056 might be OK?


text:
AnalogWrite only working for one pin of RGB LED
I'm working on some code for a Nerf blaster with an LED indicator light. When attempting to use analogWrite to PWM my LED pins, only one pin (blue) behaves as expected and dims down. The other two (red, green) don't light up at all. The LED is confirmed working and the Arduino.cc fade example works fine on each pin individually when testing. Here is the code:
#include <ClickButton.h>
#include <Servo.h>

Servo esc;

ClickButton rev(6, LOW, CLICKBTN_PULLUP);
ClickButton mode(7, LOW, CLICKBTN_PULLUP);
ClickButton trig(8, LOW, CLICKBTN_PULLUP);

int flyPin = 2;
int escPin = 3;
int pushPhasePin = 4;
int pushSpeedPin = 5;
int RED = 9;
int GREEN = 10;
int BLUE = 11;

int m = 1;
int singleShot = 100;

bool shot = false;

void setup() {
  pinMode(flyPin, OUTPUT);
  pinMode(pushPhasePin, OUTPUT);
  digitalWrite(pushPhasePin, HIGH);
  pinMode(pushSpeedPin, OUTPUT);

  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

  esc.attach(escPin, 1000, 2000);
  esc.write(0);

  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(500);
  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(1500);
}

void loop() {
  rev.Update();
  mode.Update();
  trig.Update();

  if (mode.clicks != 0) {
    m++;
    if (m > 3) {
      m = 1;
    }
  }

  if (m == 1) {
    digitalWrite(RED, LOW);
    digitalWrite(BLUE, LOW);
    analogWrite(GREEN, 120);
  }
  else if (m == 2) {
    digitalWrite(RED, LOW);
    analogWrite(BLUE, 120);
    digitalWrite(GREEN, LOW);
  }
  else if (m == 3) {
    analogWrite(RED, 120);
    digitalWrite(BLUE, LOW);
    digitalWrite(GREEN, LOW);
  }

  if (rev.depressed) {
    digitalWrite(flyPin, HIGH);
    esc.write(40);
  }
  else {
    digitalWrite(flyPin, LOW);
    esc.write(0);
  }

  if (trig.depressed) {
    if (m == 1) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }
    if (m == 2) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot * 3);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }

    if (m == 3) {
      digitalWrite(pushSpeedPin, HIGH);
    }
  }

  else {
    digitalWrite(pushSpeedPin, LOW);
    shot = false;
  }
}

The relevant portion that is failing is under the "if m == 1,2,3" blocks. Where m [for mode] == 2, the blue light works but the other leds do not light when cycling through the modes. Note the leds are on PWM pins (9,10,11). Thanks for any help!

Does it work to call analogWrite(color, 20) without all the other code? Does it work to turn the color on and off with digitalWrite?

It does. The below answer is correct though! I missed that bit of info.

You are trying to combine the use of the Servo library and PWM on pins 9 and 10. You can't do both. PWM on pins 9 and 10 uses the same timer as the servo library.
As it states on the Servo library web page:

The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.


text:
How to download files from a user/password protected web server (user:passw@ip:port)
I need to do a GET request in the form: user:passw@ip:port/streaming/channels/1/picture  to capture a still frame from an Ip camera.
Is there a way to do this with the ESP8266HTTPClient.h library?
The samples show a GET request as: http.begin(host,port,url);
What I need to do is get the user:passw@ put in before the host:url

You can rewrite your question as a more generic problem (file downloading, password, ports). That way more people will find it.

use the http.setAuthorization(user, passw) method.

It would depend whether it's digest or basic authentication.
If former, you have a nice example here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino
and if it's the latter, you can just do something like this: http.begin("http://user:password@example.com/test.html");