text:
Why do you need to shift bits when reading from an analog sensor?
I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go - this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val[1]) << 8) | int(val[2])" before getting the result.
Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

... Because you read one byte at a time.

Can you be more specific? When Read() is called, my array of bytes is filled right away, why do I need this operation afterwards?

Because now you need a number. 123 = 100 + 20 + 3

Alright, but why are we not using the first 4 bytes?

This seems to be a good documentation of the protocol; https://www.dexterindustries.com/GrovePi/programming/grovepi-protocol-adding-custom-sensors/

with color sensor nothing is skiped. it is sensor device specific. if the first 4 bytes from the device are not useful they are skipped. ask an arduino question.

It's about reconstructing the bytes of an int into the int itself. If you Google be read about "big endian", "little endian" and "network byte order" it may help you to understand what's going on.

what sensor it is? "analog"? it is i2c protocol in the link. is it an ADC sensor or why do you call it "analog".

You read bytes in the order:

Most significant byte   (let's call this msb)
Least significant byte  (let's call this lsb)

The formula to get to real value is msb * 256 + lsb
256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).
However, a CPU is normally faster in bit operations than in arithmetic operations.
Assume msb is 10101010
and lsb is    11001100

Now below is the table with the calculation order
sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.

Great, thanks! But why is this only for the analog read? It doesn't seem like they do it for the digital one

I don't know ... it depends on the order in which the bytes are received.

I still think you do not know what you do. You write about analog, but there is nothing analog in that sensor's interface.

@Juraj Thank you for your contribution, however I believe this community was created for people who do not know what they're doing. If I did I would have written a blog post instead of asking a question.

but I could explain if you would disclose the type of the sensor

"why...only for the analog read?" It is due to the design of the device's interface, regardless of what kind of data is being passed. An 8-bit MCU can only pass 1 byte at a time so any quantity larger than that must be transmitted to it byte-by-byte and reassembled by it once it has been received. Shifting is part of the reassembly - it puts each byte back in into its proper place within the larger (16-bits / 2 bytes in your case) number.


text:
How to fix Arduino restarting when two servos are powered by an external power?

Can anyone help me fix this? It always restarts when I power the servos with an external battery. I connected one battery to Arduino and one battery to servos, each 5V, but my Arduino keeps restarting.

Where is the supply for your Arduino board coming from?

I connect two batteries for Arduino and for the servo but  the Arduino keep restarting after few seconds

You are using same power supply for UNO and servo I guess.

The first thing I saw was a cartoon where apparently a schematic should be.  I'm not even going to look at the rest.  Automatic -1 and closing.

Are both those black wires connected together?

As @NickGammon says: are you sharing ground, or, as it looks like on the schematics, you have two grounds?

You will need to fix this on your own but I can suggest some things that you will likely need to investigate.

Evaluate what exactly causes the AVR to get reset. It is highly likely that long wires and current surges as loads are applied is causing either the GND or the VCC to the AVR to be compromised and initiating a brown out reset in the MCU.
Driving inductive loads without proper design may be putting high voltage spikes into your design that create havoc with proper software execution and/or risking serious damage to the silicon components. Make sure you take steps to eliminating such with clamp diodes, filter caps or zener diodes.
You will have to check your exact MCU data sheet but many parts have a reset reason register that your software can read to see what particular thing initiated the reset.
Lastly the most important thing is to make sure you have the proper tools for debugging problems like this. It is very common that you should have access to an oscilloscope so you can find the problems and learn how to fix them. The best way to learn how to design in a way that you avoid problems like this on the next project is to see first hand what went wrong and learn from it.

The reason here is, you are not able to provide enough current required for the servo. There are multiple ways to work around.

Change the code: Just try to rotate only one servo at a time. Rotate the second servo after servo1 finished rotation.
Use a 9V battery and connect it to the power socket of arduino [this could solve the issue if you are using normal servos]
Use separate power supplies for servo and Arduino. Use two different 5V supplies to power servo and arduino. Please don't forget to connect the grounds of both supplies together.

source: Stack Exchange

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

sort: votes


text:
Controlling DC motor with Pololu shield Arduino
I'm trying to power 2 DC motors with my Pololu DRV8835. I'm using the code found in this library. It works as expected BUT ONLY if the whole thing is powered via USB. When I try to power it through the shield with an external battery, the motors only beep. So the program AND the wiring have been tested.
PS.: I've also measured the voltage across the shield (M1A-M1B, M2A-M2B) and they only get like .01 V when powered via external battery. Also I'm using and Arduino Due.

We are going to need some sort of schematic or wiring diagram before anyone can help you. You can use the built-in schematic tool, or something like a screenshot from http://fritzing.org/download/ or drawn by hand.

the ESCs are driving 2 seperate BLDC motors (those work) -- https://imgur.com/a/v3P0W

My guess is that the ESCs are causing you a problem. The Arduino, for sure, is not made to be run off a modulated power supply. The ESCs are going to do very bad things to this circuit.

In our setup, the arduino only gives the signal to the ESC not power nor does the ESC give power to arduino. The only connection between the arduino and the ESC (apart from the signal) is that they run off of the same lipo battery

What's the battery pack voltage?

7.8V (measured with a multimeter), the package says 7.4

I think the best thing for you to do at this point is to go through the Arduino Due schematic and make sure your voltages (particularly in the power section) match when you are using battery vs USB power.

in both cases, when we measured the power pins on the shield, we got 7.8 V (if that's what you meant)

Don't connect your motors in series.

It didn't work when we connected only one motor either

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


text:
Check if servo is connected to arduino
#include <Servo.h>

Servo esc;

void setup(void) {
  esc.attach(7, 1000, 2000);

  if (esc.attached()) {
    // this always runs
    // even if there's no servo connected to pin 7
  }
}

I've written code kind of like the above.
The problem is that after using Servo.attach the method Servo.attached always returns true, even if there's nothing in the pin that I've attached to.
How can I check if the pin, in this case 7, actually has a wire in it?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.
To solve your problem you have 2 possibilities:

Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.


text:
Motor shield not providing enough current to 2 12V DC fans
I have 2 fans and they require up to 3A current, but my motor shield (Arduino Motor Shield Rev3) on my Arduino MEGA can only provide 2A per channel (4A max).  Is it ok to run the fans at a lower speed or are there other options to run (H-bridge)? Thanks.
Fans:
https://www.amazon.com/HIGHFINE-4000RPM-Cooling-FFC1212DE-Computer/dp/B01LLYQ2VE/ref=sr_1_1?ie=UTF8&qid=1523596613&sr=8-1&keywords=12V+dc+fan+200+cfm

The fan you linked is marked as being a Brushless DC motor.  Looks like the Motor shield you have is not designed to drive that kind of motor.

What sort of shield would you recommend in that case?

I kinda doubt that that fan will actually draw 3A. You could probably get away with using your shield--just measure the fan current draw by directly connecting it up to a 12V supply and measuring with a multimeter.
If it actually draws 3A, any of these sounds like a decent idea:
https://www.amazon.com/WGCD-Controller-Module-Stepper-Arduino/dp/B06X9D1PR9/ref=sr_1_4?s=electronics&ie=UTF8&qid=1523692716&sr=1-4&keywords=arduino+h+bridge
https://www.amazon.com/Diymall-Module-Stepper-Modules-Arduino/dp/B00NJOTBOK/ref=sr_1_8?s=electronics&ie=UTF8&qid=1523692716&sr=1-8&keywords=arduino+h+bridge
https://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr_1_11?s=electronics&ie=UTF8&qid=1523692716&sr=1-11&keywords=arduino+h+bridge


text:
I have the error: expected unqualified-id before 'if'
This is my Sketch or code:
const int EchoPin = 5;
const int TriggerPin = 6;
const int LedPin = 13;

void setup() {
 Serial.begin(9600);
 pinMode(LedPin, OUTPUT);
 pinMode(TriggerPin, OUTPUT);
 pinMode(EchoPin, INPUT);
 pinMode(13, OUTPUT);
}

void loop() {
 int cm = ping(TriggerPin, EchoPin);
 Serial.print("Distancia: ");
 Serial.println(cm);
 delay(1000);
}

int ping(int TriggerPin, int EchoPin) {
 long duration, distanceCm;
 digitalWrite(TriggerPin, LOW);
 delayMicroseconds(4);
 digitalWrite(TriggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(TriggerPin, LOW);
 duration = pulseIn(EchoPin, HIGH);
 distanceCm = duration * 10 / 292/ 2;
 return distanceCm;
}

if (distanceCm <= 20) {
 digitalWrite(13, HIGH);
}

if (distanceCm >= 20) {
 digitalWrite(13, LOW);
}

The error appears in the second if.

Lean C syntax. Code goes in functions!

The error is occurring because you have 2 if statements outside of a function. You could move them into the ping() function which would fix the error but there seems to be a logic error with the 2 if statements as well.
If distanceCm is 20, both if statements execute one right after another, so I doubt you'll see the LED turn on. Perhaps an if/else might work.
if(distanceCm < 21){
  digitalWrite(13, HIGH);
}
else{
  digitalWrite(13, LOW);
}

Error is because you close your ping method  before the "if (distanceCm >= 20)" clausule. This is a correct code:
const int EchoPin = 5;
const int TriggerPin = 6;
const int LedPin = 13;

void setup() {
 Serial.begin(9600);
 pinMode(LedPin, OUTPUT);
 pinMode(TriggerPin, OUTPUT);
 pinMode(EchoPin, INPUT);
 pinMode(13, OUTPUT);
}

void loop() {
 int cm = ping(TriggerPin, EchoPin);
 Serial.print("Distancia: ");
 Serial.println(cm);
 delay(1000);
}

int ping(int TriggerPin, int EchoPin) {
 long duration, distanceCm;
 digitalWrite(TriggerPin, LOW);
 delayMicroseconds(4);
 digitalWrite(TriggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(TriggerPin, LOW);
 duration = pulseIn(EchoPin, HIGH);
 distanceCm = duration * 10 / 292/ 2;
  if (distanceCm <= 20) {
 digitalWrite(13, HIGH);
}

if (distanceCm >= 20) {
 digitalWrite(13, LOW);
}
 return distanceCm;
}

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


text:
Program an Arduino Uno with an Atmel ICE
When I connected my atmel ice to my arduino uno everything went okay.
Then I tried debugWIRE and since then I can't connect to my ATMEGA328p.
I get the error
Failed to enter programming mode. ispEnterProgMode: Error status received: Got 0xc0, expected 0x00 (Command has failed to execute on the tool)
I think one of the fuse bits is wrong but can't connect to the ATMEGA328p to change them. Does anyone have a idea what to do?

I can't connect to my ATMEGA328p - connect using what? If you try to connect it using the "regular" USB, then it won't work until you flash the bootloader using ICE. You have probably overwritten it.

Have you looked up the problem with Atmel? It's like I always tell people on here... You're not discovering new problems when you encounter a problem. The chances of an error happening to you and someone else having the same problem is extremely high... But this looks like a physical connection problem (i.e. a lose wire, bad connection between components, clock frequencies etc).

@EugeneSh. The poster is asking how to program the Arduino with the Atmel Ice programmer after debugging with debugWIRE. No bootloader required.

Your Ardunino is stuck in debugWIRE (The debug wire fuse is set). Here is a tutorial on how to get it back to programming mode.
In the tutorial I am using the AVR Dragon with AS6, but the process is the same with Atmel ICE and AS7.
You have to be in Debug Mode to disable debugWIRE. While in debug, Click Debug>Disable Debug Wire and Close.

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


text:
Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno
I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?

At the very least for questions like this provide hot-links for the part's circuit diagrams. Most engineers who answer questions here would just design what is needed and so mentioning shields is probably not helpful without links.

https://store.arduino.cc/usa/arduino-wifi-shield

I am using below 3 parts: https://store.arduino.cc/usa/arduino-wifi-shield, http://wiki.seeedstudio.com/Seeeduino_v4.2/ https://github.com/Protocentral/ADS1292rShield_Breakout

As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).
Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.
In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the tops of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.
I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).


text:
How to get separate BPM readings from two pulse sensors using one Arduino
Here is the code I used to get BPM from pulse sensor.
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most
acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground
Library.

//  Variables
const int PULSE_SENSOR_COUNT = 2;
const int PulseWire = A0;
const int PulseWire2 = A1;
const int LED13 = 13;
int Threshold = 550;

void setup() {
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire, 0);
  pulseSensor.analogInput(PulseWire2, 1);
  pulseSensor.blinkOnPulse(LED13);
  pulseSensor.setThreshold(Threshold);
  if (pulseSensor.begin()) {
  }

  void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
      //Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
      Serial.print("BPM1: ");                        // Print phrase "BPM: "
      Serial.println(myBPM);                        // Print the value inside of myBPM.
    }
    delay(20);                    // considered best practice in a simple sketch.
  }

I wish to separate display the BPM that get from A0 wire and A1 wire. Serial could print something like this: BPM1(A0):75, BPM2(A1):80.
I don't know how to do that, can anyone help me with it?

Your sketch does not compile. What libraries are you using?

I am using PulseSensorPlayground Library. And I just added the library code on top

Could you please make it clearer what you are trying to achieve. I suggest you reword your last paragraph. Perhaps a picture would help.

Change "#define USE_ARDUINO_INTERRUPTS true" to "#define USE_ARDUINO_INTERRUPTS false".

If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
#define USE_ARDUINO_INTERRUPTS false
#include <PulseSensorPlayground.h>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h

thank you, but I am still struggling on how to print different BPM

The next line of code you are missing is on line number 146: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h. Please read all the comments in PulseSensorPlayground.h. Let's make sure we are looking identical libraries.

Have a look at this sketch: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/examples/TwoPulseSensors_On_OneArduino/TwoPulseSensors_On_OneArduino.ino

Thank you very much! I solved the problem now. And thanks for being patient with me, I am really new to Arduino.


text:
USB host shield help

Hello, I apologise for being such a noob but can someone help with this.
I am having trouble working with this. When I insert the arduino's pins into my new usb host shield , there is no indication light and when I plugged my Xbox receiver into the shield it does not turn on as it would with my desktop. Any thoughts? Please post below

We need more information. See https://arduino.stackexchange.com/help/how-to-ask E.g. What have you tried? Do other devices work? Can your program access the shield at all? What makes you think it should light up?

Posting the clear photo is helpful because it shows the USB host board has the following problem.

Thank you very much, google wasn't producing many results. I guess budget-chinese parts are a bit dodgy.

Please include the relevant information in your answer. Once the link breaks, there will be nothing in your post to give readers even a slightest hint about the problem.


text:
Library to send large amount of data over 433 MHz
I am trying to communicate between two Arduinos using two RF 433 MHz modules (transmitter receiver). I found that the library Wildewire.h allows a maximum of 77 bytes so is there any another library that allows to send a more than that?

Send many packets of 77

That's too abvious but I want to send the message all at once or at least if I can't to know what's the maximum possible I can send at once

Edit a link into your question to the source for this library so the someone can look at it to understand why it is limited to 77 bytes. [][][][] You do realize that with the small RAM size of almost all of the AVR processors used on Arduino boards that the idea of sending huge packets of data around between these limited resource devices makes little sense. Even the "big" ATMEGA2560 part used on the Arduino Mega board has only 8K bytes if RAM.

433 MHz isn't really suited for moving large amounts of data, but if you want to make the most of it, send multiple packets as previously suggested.

@MichaelKaras - you seem to be overlooking that packet sizes on limited bandwidth links are kept small for a good reason - and doubly so if they need to be retransmitted in the likely case of failure.  The answer is not to muck about with that, but to send multiple packets as previously suggested.

@ChrisStratton - I am not overlooking what you are saying at all. I am just ALSO pointing out that that the small RAM size of a typical AVR would play into packet size limitations just due to implementation restrictions. Another factor that also has to be considered here are legal limitations of how long you can be in active transmit mode on the unlicensed low power device (LPD) 433MHz band. This article provides some detail:  https://www.edn.com/electronics-blogs/eye-on-iot-/4437311/Using-433-MHz-for-wireless-connectivity-in-the-Internet-of-Things. Packet sizes play into this in a big way!

The small RAM has nothing to do with it, because it's much larger than the sizes contemplated and because that usage is easily configurable to fit the tradeoffs of an application need.  As for your 2nd point, that would be just a re-interpretation of the fact that narrow bandwidth leads to small packets, except that you are largely misinterpreting the regs, which are more about duty cycle than duration.  The actual reason for brief duration is that you want a chance to move a useful chunk before interference ruins the whole packet.

Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.
I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

As being a full message
As being a start of message (message overruns 64 bytes)
As being a mid message
As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.
You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).

Thank you for your respond but at least if I can know what's the maximum possible I can send in one transmission

Well your question stated that 77 bytes was the maximum and that is reasonable for radio transmission packets. I'm not sure I've addressed your concern so maybe you can elaborate?

Even Ethernet can only send 1522 bytes at once. Packets are everywhere. You need bigger than one packet, then send multiple packets. Simple fact of life.


text:
Adafruit Feather unable to upload code
I am using Adafruit Feather RFM69HCW Microcontroller. I am having difficulty uploading code in any Adafruit Feather boards. We have a project that is live on the field and it needs code changes. I have tried everything from holding the reset button while uploading, uploading the basic Blink function, changing USB micro cables, using different Adafruit Feather Boards.
However, I am assuming it has something to do with the Adafruit drivers.
I would really appreciate it if anybody can help me figure out the problem here.

Doesn't adafruit have a pretty good support forum?

You don't say which board you have (M0 or 32u4) and you don't tell us what error you are getting.

difficulty uploading code ... this is useless information


text:
Wait for ALL serial data to be received
Is there a way to make the Arduino wait until all the serial data has been received? Say I send a 32 byte long string over serial (the length is actually random), how would I make my Arduino wait till all 32 bytes have been received?
If I execute Serial.readBytes straight away, it only reads one char. At the moment I'm using delay, but I'm worried that it is wasting time on the Arduino, as I would like it to be processed straight away. What I want to happen is I plug in my Arduino, type in the name of an input and output file, and it will start copying the input file into the output file. I don't want to re-upload every time I want to change files, so I would like to select over serial which ones to use. However, sometimes there will be no \r or \n sent at the end, which cuts off some of the file name.
Here is my code:
#include <SoftReset.h>
#include <SPI.h>
#include <SdFat.h>
#define csPin 4

SdFat SD;
File sourceFile;
File outputFile;

int bufSize;
uint32_t lastPos = 0, timeLast, timeNow;
//fix this (error: deprecated conversion from string constant to 'char*')
//char *outputFileName = "output.wav";
#define outputFileName "output.wav"
byte avail;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
  }
  Serial.print(F("Initializing SD card..."));

  // see if the card is present and can be initialized:
  if (!SD.begin(csPin, SPI_FULL_SPEED)) {
    Serial.println(F("Card failed, or not present"));
    soft_restart();
  }
  Serial.println("Card initialized.");
enterInputFileName:
  Serial.println(F("Enter input file name:"));
  while (!Serial.available()); // wait till serial available
  delay(100);
  avail = Serial.available() - 2; // extra '\n' & '\r' that we dont want
  char inbuf[avail];
  Serial.readBytes(inbuf, avail);
  Serial.read(); // remove '\n' from buffer
  Serial.read(); //remove '\r' from buffer
  inbuf[avail] = '\0';

  char inputFileName[avail];
  strcpy(inputFileName, inbuf);
confirmInputFileName:
  Serial.print(F("Select file '"));
  Serial.print(inputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  delay(100); //wait for all chars to be recieved
  avail = Serial.available() - 2;
  if (avail > 1) {
    Serial.println(F("Enter 1 character"));
    while (Serial.available()) { //clear serial buffer
      Serial.read();
    }
    goto confirmInputFileName;
  }
  char confirm = Serial.read();
  Serial.read();
  Serial.read();
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterInputFileName; break;
    case 'n': goto enterInputFileName; break;
    default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
  }
  //up to here works
  Serial.println(SD.exists(inputFileName));

  SD.remove(outputFileName);
  outputFile = SD.open(outputFileName, FILE_WRITE);
  outputFile.close();
  //read source and write to output
  sourceFile = SD.open(inputFileName);
  timeLast = micros();
  if (sourceFile) {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(F("Copying"));
    while (sourceFile.available()) {
      //make buffer size 50% of free ram, or amount of bytes left if smaller
      bufSize = min((freeRam() * 0.5 ), sourceFile.available());
      byte data[bufSize];
      sourceFile.readBytes(data, bufSize);
      lastPos = sourceFile.position();
      sourceFile.close();
      outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
      outputFile.write(data, bufSize);
      printStats();
      outputFile.close();
      sourceFile = SD.open(inputFileName);
      sourceFile.seek(lastPos);
    }
    sourceFile.close();
    outputFile.close();
    Serial.println(F("Finished"));
    unsigned int sec = millis() / 1000;
    unsigned int mins = sec / 60;
    sec -= mins * 60;
    Serial.print(F("Time taken: "));
    Serial.print(mins);
    Serial.print(':');
    Serial.print(sec);
    Serial.print(F("Speed: "));
    Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
    Serial.print(F(" KB/s"));
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.print("error opening files");
    SD.initErrorHalt();
  }
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);
}

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

void printStats() {
  timeNow = micros();
  uint32_t timeTaken = timeNow - timeLast;
  float sent = sourceFile.position() / 1000.0;
  float fileSize = sourceFile.size() / 1000.0;
  float left = fileSize - sent;
  float speed;
  speed = 1000000UL / timeTaken * bufSize;
  speed /= 1000;
  unsigned int sec = millis() / 1000;
  unsigned int mins = sec / 60;
  sec -= mins * 60;
  int estSec = (left / speed);
  int estMin = estSec / 60;
  estSec -= estMin * 60;
  Serial.print(F("\tSent (KB): ")); Serial.print(sent);
  Serial.print(F("\tLeft (KB): ")); Serial.print(left);
  Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
  Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
  Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
  Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
  Serial.print(F("\tBuf: "));       Serial.print(bufSize);
  Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
  //todo fix this line
  //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
  Serial.print('\n');
  timeLast = micros();
}

... Count them.

I did say that the amount would be random

Then you need to be sending the length too, or terminating the data somehow.

https://majenko.co.uk/blog/reading-serial-arduino

Please show the code you tried for reading the incoming data, and describe the data, especially how the Arduino can be able to tell how much data to read / when to stop reading & start processing.

You need to format the message so that the receiver knows where the message ends and a new one begins.
Then on he receiving end you fill a buffer until a full message is received and then handle the message.
A more advanced tactic is to process the bytes as you receive them. This requires that you build a statemachine but means you don't have to store a copy of the entire message.

I decided to use a loop to read into a buffer until it got to a newline or carriage return char, or it has waited longer than it takes to receive a char.

after source code was add to the question:
you use the readBytes function wrong. if you set the size parameter to count of available bytes it will read the count of available bytes.
allocate a buffer and set the second parameter as the buffer size. the readBytes will try to fill the buffer, waiting max one second for the next character, which is enough to read the complete line sent from Serial Monitor.
if (Serial.available()) {
  char buff[50];
  int length = Serial.readBytes(buff, sizeof(buff) - 1);
  buff[length] = 0; // terminating zero of c-string
  Serial.println(buff);
}

note: readBytes will wait one second after the last character received. better is to use readBytesUntil with expected terminator. or you can set smaller timeout on Serial with Serial.setTimeout(200)

I was concerned about the same thing recently when I worked on a project that would read serial data (received on a Bluetooth HC-05).
My loop() does a lot of work for my project (Never Type A Password Again (Arduino-driven Touchscreen Device @ CodeProject.com ) but reading the serial data is a big part of the work to do also.
I implemented the following code and it has been literally running for weeks now with no problems.
if (Serial1.available() > 0) {
    incomingByte = Serial1.read();
    while (incomingByte > 0){
      if (incomingByte == 0x01){
        Keyboard.press(KEY_LEFT_CTRL);
        Keyboard.press(KEY_LEFT_ALT);
        Keyboard.write(KEY_DELETE);
        Keyboard.release(KEY_LEFT_ALT);
        Keyboard.release(KEY_LEFT_CTRL);
      }
      else{
         Keyboard.write(incomingByte);
      }
      incomingByte = Serial1.read();
    }
  }

You can see that it reads bytes while they are available which might lead you to think it might lock up, but it handles it very well.
Quite A Bit Of Work
It does quite a bit of work because it is capturing any bytes that come across Bluetooth (and then it types them on the connected computer -- that's a long story, check out the article for more).
Quite A Few Bytes
It also reads at least 64 bytes (password length + special Control char bytes) but it handles it quite well.

while (Serial1.available > 0), without the while (incomingByte > 0) and second read would do the same. but the concept read byte handle byte is good, but not for this question

@Juraj  I checked and that is a good point.  I will look more closely at that.  thanks. I think the answer still helps the OP get closer to an answer since it was somewhat of a open-ended question.


text:
Why is my esp8266 still visible under "available connections" when connecting to WiFi?
I wrote a "Hello world" type of sketch using the Arduino IDE and uploaded it to an esp8266. I used no libraries, or any kind of WiFi commands. However, when I powered up the esp8266, it was visible under "available connections" when I connected to WiFi using a Windows laptop. I was told that the firmware on an esp8266 (which has the AT commands) is being flashed when the Arduino IDE uploads a sketch. Why do I still see the esp8266 when my laptop connects to WiFi?

It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch.  The WiFi code is always included and always running regardless of what you include or don't include in your sketch.
Uploading a sketch doesn't replace those settings, and so they remain.
To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.
If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools  menu in the IDE to Erase Flash.

I would add that, esp8266 basic libraries (SDK) are always part of the sketch and handle WiFi with setting remembered on flash. Erasing the flash or choosing "Sketch + WiFi settings" in IDE Tools menu "Erase flash" clears this settings

The  "TOOLS" menu in the Arduino IDE has grown since I last used it, I'm pretty sure that the "Erase Flash:" option is new. Either way (option is new or not), that makes my post a low quality question; and for that I apologize.  Nonetheless, I would like to see this menu option specifically mentioned as part of an answer. Just something mentioning navigation, like Tools>Erase Flash  I would then happily and thankfully accept the answer.


text:
OpenOCD with FT2232H on Arduino Mega (ATmega2560)
I want to do on-chip-debugging on an Arduino Mega.
According to its datasheet, the ATmega2560 chip supports JTAG. (IEEE 1149.1 compliant)
Can I use a generic FT2232H interface to do on-chip-debugging on this?
How would a OpenOCD config file look like for this purpose?
Thanks in advance!

The chip seems to support it:

Multi-Protocol Synchronous Serial Engine (MPSSE) to simplify synchronous serial protocol (USB to JTAG, I2C, SPI or bit-bang) design.

You'll have to play with the drivers,
and check to see that Arduino brought all the JTAG pins out to header pins.


text:
Serial.print changes serial output before it is called
I'm making a project with an sd card where the user enters a file name over the serial port, and then the aduino does thing to that file. Right now i'm working on getting the serial input to work, but one Serial.print() is somehow changing a variable/output of another Serial.print(), but before it is even called.
Here is my code:
char input, output;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Ready\nEnter input text");
  while (!Serial.available()); // wait till serial available
  delay(2000);
  byte avail = Serial.available() - 1;//extra newline char at end that we don't want
  char inBuf[avail];
  //Serial.println(avail);
  Serial.readBytes(inBuf, avail);
  Serial.read();
  Serial.print("'");
  Serial.print(inBuf);
  Serial.println("'");
  delay(1000);
  Serial.println(avail);//problematic line
}

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

}

When i have the line uncommented, the output is:
Ready
Enter input text
'asd&.'
4

When all i have typed is 'asd' (no quotes).
With the line commented out, the output is as expected:
Ready
Enter input text
'asd'

I have no clue how it is happening, and should be physically impossible, since it is changing code before it is called.

Your string needs to end with a null character '\0'.  I think yours does not because of the way that you filled the buffer, so you're getting whatever junk is in memory next to your array printed in addition to the array itself.


text:
How would I include Arduino libraries using AVR-gcc without the IDE?
I am writing my own code for the Arduino Uno. I compile my code with AVR-gcc, and then upload it with AVRdude. I am not using the Arduino software, but I do have it installed and working on my PC. I want to include some of the Arduino libraries in my project, like Wire.h for example.
I realise that I could either copy the source file to my current working directory or include the entire path, like: #include "/usr/share/arduino/libraries/Wire/Wire.h" but the issue with that is Wire.h includes Stream.h which includes Print.h which includes...you get the idea. These different libraries are not kept in the same place either. I would have to hunt up and down chains of files, copy them and then use them locally. This does not seem like a good option to me.
Including them like I normally would using the IDE doesn't work at all, which is not surprising.
So, how can I use these libraries in my project without all the pain of finding them manually?

the 'core' is independent from IDE https://github.com/arduino/ArduinoCore-avr

@Juraj: I should have clarified, I am writing my own code, compiling with AVR-gcc and uploading using AVRdude. I am not using the Arduino software at all.

Juraj's comment is still valid. You can include and compile the Arduino AVR Core without ever having to install or open the Arduino IDE. These are just C/C++ header and implementation files. Just delete the ones you don't need, and add it to your include path. Finally, just add the folder to your build system as an external library, and link it against your final executable. If you don't want to add all the extra code for Print and Stream, you'll have to modify or rewrite the Wire library yourself.

@Jǝssǝ You could have a look at the Cosa command line build (https://github.com/mikaelpatel/Cosa/tree/master/build). It is a modification of Arduino-Makefile with a few shell script wrappers to make it easy to use (e.g. do not need to write makefiles). It supports build, upload, serial monitor, etc.

Since you will end up using a significant portion of the Arduino core
library, the easiest path is to accept the idea that you are now writing
“Arduino sketches” rather than plain C++ code. Don't resist, be
assimilated, fire the IDE and write setup() and loop(). ;-)
Once you have something working, the next step is to get rid of the IDE,
which is admittedly not very nice. A couple of ways to do that:

Use Arduino Builder, the command-line tool for building
Arduino sketches. The internals of this are the same as for the
Arduino IDE, but it works on the command line.
Use a Makefile, like Sudar Muthu's Arduino-Makefile. This
is a generic Makefile for building Arduino programs. It is not 100%
compatible with the IDE or Aduino builder, as it does not add function
declarations for you, but it may suit you better if you are used to a
more standard toolchain (it's just make + avr-gcc + avrdude).


text:
FIle not being found on sd card
I have some quite long code to copy a file from an SD to the same card, but under a different name. I have one version where the file names are built-in to the sketch, but to make it more portable, i have implemented a serial file selection system. There are 3 phases; choosing the input file, choosing the output file, and the copying. I have included checks to see if the files exist, confirmation for the names and so on. However, in the middle of my code, just before the copying phase, the input file disappears, and the arduino does not find it. It finds it in the first phase, finds the output file, but can't find the input file in the copying phase. SD.exists() and SD.open() both confirm this, but if i remove the sd card and put it into a computer, the file is there.
My code:
#include <SoftReset.h>
#include <SPI.h>
#include <SdFat.h>
#define csPin 4
#define roundTo 64

SdFat SD;
File sourceFile;
File outputFile;

int bufSize;
uint32_t lastPos = 0, timeLast, timeNow;
#define BAUD 115200
//make timeBetweenChars the time it takes (in milliseconds) between each char being transferred over serial, and make it at least one
unsigned long timeBetweenChars = max(1000 / (BAUD / 8), 1);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(BAUD);
  while (!Serial) {
  }
  Serial.print(F("Initializing SD card..."));
  /******************************************************************************/
  // see if the card is present and can be initialized:
  if (!SD.begin(csPin, SPI_FULL_SPEED)) {
    Serial.println(F("Card failed, or not present"));
    soft_restart();
  }
  Serial.println("Card initialized.");

  Serial.println(F("Files on card:"));
  SD.ls();
  //******************************************************************************
  //START OF INPUT FILE NAME
  //******************************************************************************
enterInputFileName:
  Serial.println(F("Enter input file name:"));
  while (!Serial.available()); // wait till serial available
  char inbuf[64];
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  byte pos = 0;
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    inbuf[pos] = Serial.read();
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for input file name
  char inputFileName[pos];
  //copy data from inbuf to inputFileName
  strcpy(inputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmInputFileName:
  Serial.print(F("Select file '"));
  Serial.print(inputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  char confirm = Serial.read();
  bool tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmInputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterInputFileName; break;
    case 'n': goto enterInputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(inputFileName);
  Serial.println("' as input file");
  if (SD.exists(inputFileName)) {
    Serial.println(F("File exists"));
  }
  else {
    Serial.println(F("Error, file does not exist. Please choose another file"));
    goto enterInputFileName;
  }
  //******************************************************************************
  //END OF INPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF OUTPUT FILE NAME
  //******************************************************************************
enterOutputFileName:
  //clear input buffer
  for (byte w = 0; w < (sizeof(inbuf) / sizeof(inbuf[0])); w++) {
    inbuf[w] = '\0';
  }
  Serial.println(F("Enter output file name:"));
  //wait for some chars to arrive
  while (!Serial.available());
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  pos = 0;
  //found here Serial.print(SD.exists(inputFileName));
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    //file found on first loop, but not after that
    // found here Serial.println(SD.exists(inputFileName));
    inbuf[pos] = Serial.read();
    //not found here Serial.println(SD.exists(inputFileName));
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  //input file not found here
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for output file name
  char outputFileName[pos];
  //copy data from inbuf to outputFileName
  strcpy(outputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmOutputFileName:
  Serial.print(F("Select file '"));
  Serial.print(outputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  confirm = Serial.read();
  tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmOutputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterOutputFileName; break;
    case 'n': goto enterOutputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmOutputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(outputFileName);
  Serial.println("' as output file");

  if (SD.exists(outputFileName)) {
    Serial.println(F("File already exists. Overwrite? Y/N"));
confirmOverwrite:
    while (!Serial.available()); // wait till serial available
    confirm = Serial.read();
    tooManyChars = 0;
    // wait for the next chars
    delay(timeBetweenChars);
    while (Serial.available()) {
      //read next char
      char extra = Serial.read();
      //if it isn't a newline or carriage return
      if (extra != '\n' && extra != '\r') {
        //too many characters entered
        tooManyChars = 1;
      }
      //wait for next char
      delay(timeBetweenChars);
    }
    /******************************************************************************/
    if (tooManyChars) {
      Serial.println(F("Enter 1 char"));
      goto confirmOverwrite;
    }

    //if only 1 char entered
    bool overwrite = 0;
    switch (confirm) {
      case 'Y': overwrite = 1; break;
      case 'y': overwrite = 1; break;
      case 'N': goto enterOutputFileName; break;
      case 'n': goto enterOutputFileName; break;
      //invalid char entered
      default: Serial.println(F("Enter Y/N")); goto confirmOverwrite; break;
    }
    if (overwrite) {
      Serial.println(F("Removing output file"));
      SD.remove(outputFileName);
    }
  }
  Serial.println(F("Creating output file"));
  outputFile = SD.open(outputFileName, FILE_WRITE);
  outputFile.close();
  //******************************************************************************
  //END OF OUTPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF COPYING
  //******************************************************************************
  //read source and write to output
  sourceFile = SD.open(inputFileName);
  timeLast = micros();
  //debug line
  Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
  if (sourceFile) {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(F("Copying"));
    while (sourceFile.available()) {
      //make buffer size 50% of free ram, or amount of bytes left if smaller
      int ram = round((freeRam() * 0.5) / roundTo) * roundTo;
      bufSize = min(ram, sourceFile.available());
      //round to nearest value of roundTo
      bufSize = round(bufSize / roundTo) * roundTo;
      byte data[bufSize];
      sourceFile.readBytes(data, bufSize);
      lastPos = sourceFile.position();
      sourceFile.close();
      outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
      outputFile.write(data, bufSize);
      outputFile.close();
      sourceFile = SD.open(inputFileName);
      sourceFile.seek(lastPos);
      //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
      printStats();
    }
    sourceFile.close();
    outputFile.close();
    Serial.println(F("Finished"));
    unsigned int sec = millis() / 1000;
    unsigned int mins = sec / 60;
    sec -= mins * 60;
    Serial.print(F("Time taken: "));
    Serial.print(mins);
    Serial.print(':');
    Serial.print(sec);
    Serial.print(F("Speed: "));
    Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
    Serial.print(F(" KB/s"));
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening files");
    Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
    SD.initErrorHalt();
  }
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);
}

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

void printStats() {
  timeNow = micros();
  uint32_t timeTaken = timeNow - timeLast;
  float sent = sourceFile.position() / 1000.0;
  float fileSize = sourceFile.size() / 1000.0;
  float left = fileSize - sent;
  float speed;
  speed = 1000000UL / timeTaken * bufSize;
  speed /= 1000;
  unsigned int sec = millis() / 1000;
  unsigned int mins = sec / 60;
  sec -= mins * 60;
  int estSec = (left / speed);
  int estMin = estSec / 60;
  estSec -= estMin * 60;
  Serial.print(F("\tSent (KB): ")); Serial.print(sent);
  Serial.print(F("\tLeft (KB): ")); Serial.print(left);
  Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
  Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
  Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
  Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
  Serial.print(F("\tBuf: "));       Serial.print(bufSize);
  Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
  //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
  Serial.print('\n');
  timeLast = micros();
}

My serial output(I chose Nova.mp3 as input file and output.mp3 as output file):
Initializing SD card...Card initialized.
Files on card:
output.mp3
Nova.mp3
Eclipse.wav
Enter input file name:
Select file 'Nova.mp3'? Y/N
Using file 'Nova.mp3' as input file
File exists
Enter output file name:
Select file 'output.mp3'? Y/N
Using file 'output.mp3' as output file
File already exists. Overwrite? Y/N
Removing output file
Creating output file
Exists(I,O): 01
error opening files
Exists(I,O): 01
No error found.

I know i am not running out of memory, and have no compiler errors, but i have no clue what is going wrong. Is it possible I have put in some unnecessary code? Also, if it was possible to have multiple files open at a time, would i spped up my read/write speed?

you char array for inputFileName is one char shorter then needed. if 0 is at pos you need to allocate and copy pos + 1 chars because the indexing starts at 0. (btw: your code is very ineffective)

I know indexing starts at 0, and if you didn't notice, i actually add 1 to pos at the end of the loop, so the array should be long enough. And how is it ineffective? do you mean inefficient?
Edit: this actually made my code start copying, will update if it finishes successfully.

too much code for the task

How should i compress it? i can't do the copy loop as simply as i'd like, because only 1 file can be opened at a time, and i put the file selection confirms in because sometimes people make typos. what can i make smaller

"As of version 1.0, the library supports opening multiple files." https://www.arduino.cc/en/Reference/SD

the code for filename input is repeated

I'm using SDFat not SD

The problem is that you have the char arrays for zero terminated c-string one char shorter then needed. I see you assign the terminating zero to inbuf[pos] and then you allocate pos chars for the filename and copy pos count of characters. That leaves out the terminating zero and the c-string of the filename is not terminated by 0 and continues in memory with random content.


text:
Serial.begin(9600); in Arduino
I want to know what Serial.begin(9600); does and if it is necessary to write it in the code.

Have you done any research yourself? Like googling?

It enables the UART port and sets it to 9600 baud.  Without it you can't use Serial.print etc.

Will the bot work without this?

Does "the bot" use Serial.print, Serial.read, or Serial.anythingelseatall?

I'm making an obstacle avoiding bot. I'm not debugging it or using the serial monitor. So, can I exclude it from the code?

The probably. If you're not using Serial.print, Serial.println or Serial.write then it should be doing nothing.


text:
Do I need an external power supply for the SG90 micro servo?
I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?
I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.

I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA. You may want to test your servo under this condition before deciding to power it with an Uno.

Does your servo have to push or pull anything? Or is this just to practice writing code for an unattached SG90 and see it move? If it's the former, the servo will draw more current than an Arduino can deliver so you'd need a separate power supply. If it's the latter, you can get away with it. The SG90 is about the least demanding (of current) servo available and you can drive an unloaded one directly off the Arduino. It's current-peaks should be short enough to limit thermal damage to the Arduino pin driver. Just make short test runs and don't leave it see-sawing for any length of time.


text:
Connecting Arduino and Processing, how do I know what COM to read?
I'm using Processing to read data from the serial port that the Arduino sends. When I go to device manager it shows that the Arduino is in COM 4, but in order for Processing to read from the Arduino the COM I need to type in is 2:
String portName = Serial.list()[2]

Why do the numbers not match?
Thanks!

Because the two numbers are completely different types of numbers.
The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.
The number 2 in Serial.list()[2] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.
In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.
You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.


text:
How to change the default Slave Select pin (Digital pin 10) on Arduino UNO R3 for SPI communication?
Currently I am working on an Arduino based project. My project require interfacing 6 servo motors and an SD card module to my Arduino UNO.
The problem is that I need all the six PWM pins for six servos (Including pin 10) which happen to be the default Slave Select Pin for SPI communication. I don't want to use software based PWM on a digital pin. I could not find any resource on how to change the default SS pin to any other pin. Any help in this regard will be highly appreciated. Thanks!

Other than passing a different argument to SD::begin()?

Hmm, I though any GPIO pins could be used for slave selecting.

pin 10 is CS if Atmega 328 is a SPI slave. if Atmega is master pin 10 must be output otherwise the chip switches to slave. pwm is output

Just declare it and use it:
byte ssPin = 7; // or any other pin, stay away from 0,1, leave those for Serial()
byte defaultSS = 10; // 53 on a 2560

pinMode (ssPin, OUTPUT);
digitalWrite (ssPIN, HIGH); // typical slave select OFF state
pinMode (defaultSS, OUTPUT);  // 10 MUST be an output for device to be SPI master (328P)
SPI.begin(); // default is 4 MHz speed, MSBFIRST
// takes care of SCK, MISO, MOSI, don't need define/declare those

digitalWrite (ssPin, LOW);
SPI.transfer (ledData, 0xAA); // example data going to a device
digitalWrite (ssPin,  HIGH);

" The problem is that I need all the six PWM pins for six servos" The Servo.h library can drive 12 Servos on an Uno, and on any pin,not just PWM pins. Check it out. Servos need a 1-2mS (1000 to 2000  uS) wide pulse occurring every 20mS (50 Hz), which is not really PWM. (1mS =  full turn one direction, 1.5mS = centered, 2mS =  full turn the other direction, give or take a few uS).  I bet that could be created using Blink without Delay technique even, 50 Hz is pretty slow.


text:
exit status 1 'Time' does not name a type
#include <DS3231.h>
#include <Wire.h>  // i2C Conection Library

// Init DS3231
DS3231  rtc;
// Init a Time-data structure
Time  t;
uint32_t targetTime = 0;

uint8_t hh = 0, mm = 0, ss = 0, dd = 0, bb = 0; //variable Unsignet int 0-255
int yy = 0; //variable integer
String Day = "  "; //variable string

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

void loop() {
  t = rtc.getTime(); // gate all data time & date from RTC
  Day = rtc.getDOWStr(); //get name of day
  hh = t.hour,DEC; //pengambilan data jam
  mm = t.min,DEC; //pengambilan data menit
  ss = t.sec,DEC; //pengambilan data detik
  dd = t.date,DEC; //pengambilan data hari
  bb = t.mon,DEC; //pengambilan data bulan (dalam desimal)
  yy = t.year,DEC; //pengambilan data tahun
  //Buka Serial Monitor Arduino untuk melihat hasilnya
  Serial.print (Day);
  Serial.print (F(" Time = "));
  Serial.print (hh); Serial.print (F(" : "));
  Serial.print (mm); Serial.print (F(" : "));
  Serial.print (ss); Serial.print (F("  Date = "));
  Serial.print (dd); Serial.print (F(" . "));
  Serial.print (bb); Serial.print (F(" . "));
  Serial.println (yy);
  delay (1000);
}

When I verify the code, this error appears:

exit status 1
  'Time' does not name a type

What does it mean?

Welcome to EE.SE. Please format your code properly using the {} code button (or add >= 4 spaces on the start of each line). Make sure it is indented properly. Use the preview to check it before submitting.

Have you included the library that defines the "Time" type?

isn't it already in the library wire.h?

@Hanatsuki No - see http://playground.arduino.cc/Code/Time

You don't mention which library you are using (which library does #include <DS3231.h> refer to?)
The DS3231 library here https://github.com/NorthernWidget/DS3231 defines a DateTime object which appears to have similar elements to what you are trying to access in 't' (hour, min, sec etc).
I would try defining 't' as a DateTime object.


text:
How can I power a NeoPixel ring and strip through Arduino MKR1000?
I currently have a MKR1000 which is connected to 1 ring with 8 neopixels, 1 strip with 20 neopixels, 1 microwave sensor, 1 speaker, 1 rotary encoder. I am running the NeoPixel positive and negatives through a 220 µF capacitor, and the data pins through 220 Ω resistor.
I am soldering these components onto a board, but currently, when I plug the MKR1000 into my USB it says it's drawing too much power, the Arduino also smokes and I can smell burning, so disconnected straight away.
What am I doing wrong?

A schematic diagram would help the understanding your setup

The on-board regulator of an Arduino can supply a maximum of 500 mA when connected to USB, and up to 1000 mA when connected to an external power supply (see Maximum current from Arduino 5V power pins).
If your components are drawing more current than that, then you will need to use an additional separate power supply for the NeoPixel ring - ensuring that the ground lines of the Arduino's supply and the NeoPixel's supply  are connected.
If the Arduino has been smoking then it may already be damaged. Did you see which part was smoking? If it was a capacitor as shown in Is my Arduino dead?, then this answer may help.


text:
NOT realtime MP3 decoder
I know that MP3 is the most popular audio format out there, but I need to be able to convert them to wav files for bother project I'm working on. It can be done with a PC but I would like to know if there is a way of decoding a MP3 file and turning it into a pcm wav file on an Arduino. I don't want to use an extra chip, as I do not plan on playing the MP3s, just converting them.

The mp3 audio coding is not just one mathematical calculation. To decode every mp3 file you need a complete package and enough memory. That is not something for a simple arduino board.
There are libraries to decode for example a jpg file or a mp3 file. They have restrictions and you need a faster processor.
Adafruit has made a start: https://learn.adafruit.com/native-mp3-decoding-on-arduino/, but you need a powerful non-standaard arduino-compatible board. That library does not use I2S yet.
I suggest to use a Raspberry Pi.

It's something I made a start on too. Porting the Microchip code. However, it will not, and will never, run on a little Arduino. It's intended for chipKIT boards with hundreds of kB of RAM.

Isn't there a way to decode a segment at a time? I would like to read a sector, decode it, write it to a file, then repeat. If necessary, would it be possible to use a temporary file on an sd card as spare memory?


text:
How can I power MKR1000 and 25 NeoPixels 24hrs or longer?
I have an arduino MKR1000 which I would like to run off battery power for a few days with 1-3 dimly lit NeoPixels active. Every day for an hour there will be 10 NeoPixels active. Brightness for both set to 15. I'm having 2 issues. The NeoPixels start to morph into another color after an hour or thereabouts, and the MKR seems to lose track of time, as the Leds don't turn on and off on the right hour. I have also noticed that if I have the usb and battery both plugged into the MKR, the serial monitor stops working. What should I do?

What size and type of battery?

Neopixels need 5V which you won't have if you are using the lipo battery input.

It's a LiPo battery 3.7V and 2000mAh

I have followed Adafruits guide for these NeoPixels, and they write that a LiPo is ok for smaller strips of LEDs, is this incorrect?

Yes, you can feed the neopixel with 3.3~3.7V... just be sure that the pin that controll this ledstrip work with also 3.3V logic (I don't know if the MK3 work with 5V or 3.3V logic)

It's 3.3V but now I am thinking, should I have connected the battery to the white charger instead of VIN?


text:
Shutdown the LED of my GY-85 sensor
I would like to shutdown the LED of my GY-85 (gyroscope) component. Is it possible?

use black paint

it's about energy, not visual comfort

next time you ask a question, please include that kind of information in your question

According to this schematic, no. The LED is connected directly to power.
You will need to physically remove the LED to turn it off.


text:
Arduino IDE 1.8.6 not starting.
My Arduino IDE is not getting started. It just crashes before opening up. I don't know what the problem is. It was working well enough before without any issues.
This is what I see after running the arduino_debug.exe in the command line

Note: I added a library (DHT) to work with my humidity and temperature sensor and since after then, this issue comes up. I tried to reinstall it like more than 7 times, but the issue still persists.
Please help me with it. Thanks.

The cause of the problem is that you have a corrupted library index file. The solution is to delete the file, which will force the Arduino IDE to download a (hopefully) uncorrupted fresh version from the Internet:

Open the C:\Users\JK\AppData\Local\Arduino15 folder
Delete the file library_index.json
Try starting the Arduino IDE again

For anyone encountering this problem who is using an operating system other than Windows, the location of library_index.json is different:
On Linux:
/home/{username}/.arduino15 (a.k.a. ~/.arduino15)
On macOS:
/Users/{username}/Library/Arduino15
If using the Arduino IDE in portable mode:
{Arduino IDE installation folder}/portable

The issue of a corrupted library index file preventing the Arduino IDE from starting has been reported to the Arduino developers and they are already working on a fix:
https://github.com/arduino/Arduino/issues/7937

Had same issue when migrating from Arduino IDE 1.8.2 to 1.8.9
In my case, deleting just the library_index.json was not enough but a good hint.
I did also delete the subdirectories of "packages" directory (boards which I downloaded- the ESP32 board and the ESP8266 board), and all files (not folders) in C:\Users\%username%\AppData\Local\Arduino15\ except the preferences.txt
This solved the issue for me.

I had the same problem this morning when trying to launch the IDE (1.8.3).
I'm running Linux Mint 18.
Running the IDE from the command line showed the following errors:

The output hints at a problem with 'packages' so I renamed ~/.arduino15/package_index.json to package_index.json.old. The IDE was then able to be launched. 'package_index.json' can then be rebuilt by starting your boards manager through 'Tools->Board'.


text:
Arduino log file directly to file
I have problem because I need to read values and then save them in a .txt file, but Arduino doesn't have a physical connection with my computer. It only has a connection with a computer using Ubuntu without Arduino IDE or other programs. Also, I don't have an ethernet connection and SD card. I need only to have this data stored. The best way is to send them at the end of cycle to a special text file. Has anybody faced that before?

I'm thinking about writing a bash script for reading all values sent by serial and then save them, but how do I get that information from serial?

Also, it’s unclear what you mean when you say “Arduino doesn’t have physical connection with my computer” and then “it only has connection with computer using Ubuntu”. The two statements contradict each other.

There are many examples you can find online of simple serial capture to a file.  Bash may not really be the best choice as serial ports aren't just simple files (typically needing at minimum configuration), but something like python with pyserial can work well.

How much data is it? Perhaps it can be stored in eeprom, and retrieved later via the serial.

Any serial terminal emulator application can connect to the Arduino. Select one that has log-to-file capability and open its log file after you've connected it to your Arduino's /dev/tty... device.
Start the Arduino and let it collect & send the data to your terminal program. Close the terminal app's log file (easy step to forget - ask me how I know :) and there's your data.

Like what Chris mentioned in the comment, you can use pyserial to do it. You can even add timestamp to your data and append them to the same log file.

The Arduino IDE provides a built-in serial monitor functionality, which emulates a serial port over USB. There are many tutorials available for its use.
However, as best I recall the Arduino serial monitor does not allow you to save a log file. If you don't want to write your own code to do this you can use a different terminal emulator, such as putty.

No, serial port emulation is not a function of the Arduino IDE.  It is a function of drivers in (or for various older versions and clones) added to, the host operating system.


text:
How to read data directly from lcd display
Referring to post: LCD data read and show on computer
It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?
My problem:
I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.
For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.
This is the schematic I'm using:

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.
With this code:

The problem is that I'm having these results in reading:

No matter what appears on the screen, they are always invalid characters.
If someone identifies where my problem is, I'll be very grateful.

No final code was posted as far as I can see, just pseudo-code that could be adapted to suit.

Stack Exchange is not a forum, and your "question" is not answerable.

I edited my question, I think it became clearer.

The display shown in your picture is 16x2 display LM016L. Why do you think that your "a 20x4 display" has the same control method as the LM016L display?

Serial.print() will be too slow for this.  Also your 1K resistors are potentially too stiff, if you want a keeper for undriven lines try 10K or larger.   Ultimately, you need to either write code informed by actual understanding of the operations described in the LCD data sheet (including details of clock-data timing), or if you just want to do a general capture to analyze, you should instead use a cheap USB-based logic analyzer ala sigrok/pulseview which has a chance of having sufficient sampling rate to capture the operations asynchronously.

I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow.
As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins.
Those are

PORTB = Digital Pins 8 through 13 plus the crystal pins
PORTC = Analog Input 0 through 5, reset pin
PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.
I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C).
RW goes to Pin 7, RS to Pin 6, E to Pin 5.
The code you would then use to read the data would be this:
    uint8_t byte_displaydata = 0x00;
    uint8_t RW = 7;
    uint8_t RS = 6;
    uint8_t E = 5;
void setup() {
  Serial.begin(1200); //perhaps increase this a bit
  pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
  pinMode(RS, INPUT);
  pinMode(E,INPUT);
  DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
  DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
  PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
  PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

}

void loop() {
  if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
    byte_displaydata = 0x00; //reset byte_displaydata
    byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
    byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
    Serial.println(byte_displaydata,BIN);
  }
}

Please note that I have not tested this, and only recently have gotten started in AVR / Arduino.
If anyone can look this over, I'd greatly appreciate it.
Source: Microchip ATmega328P datasheet, Arduino pin mapping

It is probably too late for the OP but there is a protocol sniffer for such LCD screens which use the HD44780 series LCD driver as, for example, the common LCD1602 does.
The code is published here:
https://forum.arduino.cc/t/lcd-1602-and-similar-databus-sniffer/675769/11
The data rate would be too fast for Serial.print() to print each character received in real time so a queue is used to consolidate the data.


text:
How can I read the serial output of STM32F103C8T6 from USB to Serial TTL?
I recently bought a STM32F103C8T6 board (blue pill)
I programming to it using the USB to Serial TTL I bought (CP2102).
I'm still taking very first steps and trying to figure out how to operate the component.
I was able to burn a basic script to STM32F103C8T6 that causes the P13(LED) to blink.
Now I'm trying to add basic printing that I can see over the serial interface
Which I am already connected to (CP2102).
Here's what my code looks like:
void setup() {
// initialize digital pin PC13 as an output.
pinMode(PC13, OUTPUT);
Serial.print("finish setup function \r\n"); // try to print something using serial
}

void loop() {
digitalWrite(PC13, HIGH);
delay(500);

digitalWrite(PC13, LOW);
delay(500);

Serial.print("loop throgh loop function \r\n"); // try to print something using serial
}

Everything is compiled and loaded fine (I work through ARDUINO IDE), but it is not clear to me where I can see these prints.
I tried to see them in Tools-> serial monitor (in the arduino ide tool)
But I didn't see any printing ...
(I know that my code got loaded successfully because I play with the speed of the LED blinks and I see that it is responding to the change at the speed of the flicker).
It feels like it's a really stupid question but where can I see my prints?

Do you need to initialize the serial interface? That's normally done for Arduino sketches.

You miss-spelled the word 'throgh'. It should be 'through'. If it is a command it MUST have correct spelling.

thank you @Sparky256 it's not a command , i simply try to print this sentence

thank you @ElliotAlderson what i need to initialized and how? can you please give me some basics examples of this?

Look for some sample code that uses the serial interface. There are many, many examples available and some are included with the Arduino IDE. I'll admit it's not clear to me what programming environment you are using.

First you must study the documentation of the Arduino port you are using to find out which hardware UART/pins Serial refers to, or if it actually refers to a virtual channel through the stm32's USB port.  Only you know which port of Arduino to the stm32 you are using, so only you can do that.


text:
Are there any Wi-Fi modules for the Arduino Uno that may connect to an external Wi-Fi Antenna?
I have an Arduino Uno I need to connect to Wi-Fi to make HTTP POST Requests to a Raspberry Pi Web Server.
The Arduino is located only about 30 feet from the AP, but there is a brick wall in the line of sight, and it is in a metal outdoor enclosure. For that reason, I wanted to attach an external Wi-Fi Antenna which would stick out a sealed hole in the enclosure.
I was contemplating using an ESP8266 Wi-Fi module, but it does not look like there is an easy way to attach the antenna.
What would be the best Wi-Fi module to which I could attach an external antenna for an Arduino Uno?

https://robotdyn.com/wifi-d1-mini-esp8266-dev-board-usb-cp2104.html do you see the antenna connector?

@Juraj Thanks. That might be a better option. It's a lot more self-contained, it's cleaner, and I won't need a load level converter.

the same in Uno format https://robotdyn.com/wifi-d1-r2-esp8266-dev-board-32m-flash.html. but I can't recommend it. both, the on-board antenna and the connector are connected. I think, it causes problems and there are no instructions how to cut connection to one of them

on the mini version the external antenna connector is not connected. you would need to re-solder the 0 ohm 'resistor' that connects the on-board antenna to soldering points connecting the external antenna connector

There are variants of ESP8266-based modules which include a connection for an external antenna. The ESP-02, ESP-05 and ESP-07 modules all feature a U.FL socket.
Effectively, they are an ESP8266 mounted on a carrier board with a U.FL socket.
If you already have some code to suit an ESP8266-based module, this will avoid having to rewrite for a different unit.


text:
ESP8266 is not responding to AT commands and showing mem_failed on every code
I was using Arduino Uno with ESP8266-12E. Today I was reading an article to blink LED using Webpage. The code wasn't uploading so I connected all the pins connected to 3.3V to 5V. Then the code was uploaded successfully. After that I switched off my laptop and Arduino. After 2-3 hours when I got back to work, the module wasn't responding to AT commands even after reconnecting it to 3.3V. The wifi is working fine since it automatically connects to the WiFi I have configured earlier. I used same settings and connections prior to that messing up. Also on every code upload it shows mem_failed. So, how can I get my WiFi to work?

The code wasn't uploading so I connected all the pins connected to 3.3V to 5V. What on earth made you do that?

I don't know. I thought I should give it a try. And I don't know why it was uploaded then.

@jsotola The pins were Vcc, RST, CH_PD.

I'd suggest you go and buy a new ESP8266 - and this time keep it away from 5V.

Buy a little development board and learn how to use the ESP8266. Either a NodeMCU or a WEMOS board. They have a USB to serial adapter on the board and a proper regulator.
The initial problem you encountered was most likely caused by insufficient power for the ESP8266. The power supply must be capable of supplying a minimum of 400mA. It needs to have close short wires to the Vcc and ground on the ESP module. It helps to also have a capacitor across Vcc and ground of the ESP module with short leads.
There are some horrible examples on the internet that show the ESP being powered from and Uno's 3.3v power connection. This will never be reliable if it does even work. There is not enough power.
The ESP8266 typically uses about 80mA. This is an average value. When transmitting the peak current is a lot hight. The worst case happens to be when the ESP starts after a reset. I then does an analog power calibration. (for the RF section) Expressif states this, plus the digital power requirements, will equal above 500mA.
The GPIO pins are not 5 volt compatible. A lot of internet examples show the ESP rx and tx lines connected to the rx and tx of a 5 volt Arduino board, without level converters. This is not acceptable. The RX line of the ESP8266 can be damaged.
Powering the ESP module with 5 volts can damage all or parts of the two chips on the module. (the CPU and the external Flash memory chip) Other sections may still work. That is likely what you are seeing.


text:
Does SoftwareSerial and the servo library produce interrupt conflicts?
I'm planning a project that will involve multiple serial ports and the Arduino servo library. I have heard that this may cause interrupt conflicts. Are there any simple solutions to this

I have heard that this may cause interrupt conflicts.

Indeed. The Arduino can only run one interrupt routine at a time, and:

Servos use rapidly firing interrupts
SoftwareSerial both turns off interrupts while sending (for relatively long periods)
SoftwareSerial uses an interrupt for receiving that runs for an extended period

So really you can't use both together.
Options?

Use hardware PWM to drive the servos (There is a library for this somewhere)
Use an external servo PWM driving board (Adafruit do one IIRC)
Don't use SoftwareSerial.  IIRC AltSoftSerial is better, though no software serial implementation will ever be particularly good.

The underlying problem is that the low-end Arduinos only have on serial port. If you need to use more than one serial port then you really need to be looking at using a different Arduino - one with multiple serial ports.


text:
How do I make a stepper motor compass cross 360° to 0°?
I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.
My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?
The simulator feeds a float val that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the AccelStepper library.

void ProgOut(byte id, float val) {
switch (1) {
case 1:

if (val)
        { stepper1.moveTo(val * 11.3222222);         }

        stepper1.run();

break; }}

I have tried something like this:
void ProgOut(byte id, float val) {
switch (1) {
case 1:
if ( stepper1.distanceToGo () >= 4064){
          stepper1.moveTo(4076);
          stepper1.setCurrentPosition(0);
}
    else if (val)
        {

                stepper1.moveTo(val * 11.3222222);
        }

        stepper1.run();

break; }}

Your library doesn't understand that your stepper goes in a full circle.  See if it has some more primitive moves, like "home" and "move by n steps".  If it does you're in business, but you'll have to write your own "go to" function.  Alternately, dig through the documentation and see if it can be TOLD that it's dealing with a stepper that goes in a circle.  Again, if it does, you're in business.

have you tried to go to 361?

@TimWescott thanks Tim for the suggestion. I’ll go through it again to see what I have available

@jsotola the Val is feeding from the simulator software. So the maximum is actually 359.99. The Val after that would be 0

why are you involving data from the simulator during debugging? .... figure out how to step from 359 to 0 without moving a full circle ..... once that works, then use the simulator data again

Two options (for starters):

Use the move() class rather than the moveTo() class. This will allow you to do relative moves rather than absolute.
Use setCurrentPosition() (which sets the current position to zero) followed by moveTo() with a destination which is newPos - prevPos.

For either to work you will need to keep track of the current position of the needle.
To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.
// delta is the angular adjustment required.
delta = (currHeading + 180 - prevHeading) % 360 - 180;
setCurrentPosition();        // Zero the motor.
moveTo(delta);               // Move absolute from the new zero.
prevHeading = currHeading;   // Keep track.

The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.

Also working on making a compass for flight simulator.
Hopefully the following code will help answer the question.
This is a working code that I have tested using serial monitor...
Note: For Flight Sim use, I did find that to get enough speed and smooth movement for the X27-168 gauge motor you need to use a stepper driver with microstepping rather than driving the X27-168 directly from the Nano I/O pins. You will have to adjust Max speed & acceleration and also edit the firmware for micro-stepping with using a stepper driver. Note: When using a stepper driver chip, you need to use the correct type for 6 step coil energising that the X27-168 stepper uses eg. AX1201728SG. Polulu (A4988) type stepper drivers use 8 steps coil energisation which will not move the gauge motor correctly - while it will move the gauge motor it creates a lot of noise and is not ideal.
I did have to add the following to get both left and right movements through North.
I used Movement rather than delta -
        if(Movement( < -180){Movement = Movement + 360;}
A single movement of 180 degrees defaults to CCW direction. however with Flight simulator data extraction, you shouldn't get a single movement of that amount.

/*Analog Compass Gauge.**
This uses an Arduino Nano processor that has four of its I/O's directly connected to an X27-168 geared stepper motor(Gauge indicator motor).
While it works, there should really be four sets of protection diodes across each of the I/O pins - diode to +5V & diode to 0V to eliminate spikes over 5v and below 0v on each I/O pin.
The X27-168 geared stepper motor has had the internal stop cut off on the main output shaft gear to allow full 360 degree movement.
A 55mm dia plastic round plate has been fitted to the X27-168 geared stepper motor 1mm diameter drive shaft and a printed label attached to the plate to show compass direction.
The plastic plate has a small Neodymium magnet (1mm dia x 2mm long) which can pass near a Hall Effect sensor (A3144)to provide a homing reference signal.
+5v,0v and I/O signal pin is connected directly to the Hall Effect sensor. The Nano internal I/O resistor is used to provide a pullup voltage for the Hall effect sensor signal.  The firmware uses the AccelStepper library.
PC Serial Monitor is used to enter new compass headings.
The X27-168 geared stepper motor is referred to as "stepper1" in the firmware.
*/
    #include "AccelStepper.h"
        AccelStepper Stepper1(AccelStepper::FULL4WIRE, 3, 4, 5, 6);   // Define stepper I/O pins (Using I/O pins connected directly to X27-168 Geared Stepper Motor)
       //AccelStepper Stepper1(AccelStepper::DRIVER, 2, 5); // Defines I/O pins when using a stepper driver e.g. AX1201728SG Quad driver chip -  Dir pin - Stepper pin
       #define Home_Sensor      2   // Pin 2 - Connected to Home Sensor - Hall Effect A3144- (0v when sensed)
       int Offset = -67;   // ****** Adjust this setting to ensure North facing when at Home Position(0)  ******
       int MaxSpeed = 80;   // ****** Adjust this setting for Max Speed of Stepper as to not miss steps    ******
       int Acceleration = 25   // ****** Adjust this setting for Acceleration of Stepper as to not miss steps ******
       int    Move_finished =   1;   // Used to check if move is completed
       long   Initial_Homing = -1;   // Used to Home Stepper at startup
       String InputString =    "";   // String to hold incoming data from serial monitor
       bool   StringComplete = false;   // Whether the string is complete
       int    LastHeading = 0;   // Register for Last heading
       int    NewHeading  = 0;   // Register for New heading
       int    Movement;   // Register for difference between Last and New heading
       void setup() {
       Serial.begin(9600);   // Start the Serial monitor at 9600 Baud
       pinMode(Home_Sensor, INPUT_PULLUP);   // Using internal pullup for Hall Effect sensor
       delay(5);   // Wait for stepper Driver wake up (if used)
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Max Speed of Stepper (Slower to get better accuracy)
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Acceleration of Stepper
       Serial.println("........ Homing Stepper ........");

       while (digitalRead(Home_Sensor)) {   // Make the Stepper1 move CW until the sensor is activated
       Stepper1.moveTo(Initial_Homing);   // Set the position to move to
       Initial_Homing--;   // Decrease by 1 for next move if needed
       Stepper1.run();   // Start moving stepper1
       delay(5);
       }
       Stepper1.setCurrentPosition(0);   // Set the current position as zero for now
       Initial_Homing=1;
       while (!digitalRead(Home_Sensor)) {   // Make the Stepper1 move CCW until the sensor is deactivated
       Stepper1.moveTo(Initial_Homing);
       Stepper1.run();
       Initial_Homing++;
       }
       //**** Should now be Homed to Magnet position which may not be North as per label. Below allows tuning to correct position of label ****
       Stepper1.setCurrentPosition(0);
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Correction Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Correction Acceleration of Stepper1

       Stepper1.moveTo(Offset);   // To correct to have North as Home position
       while(Stepper1.distanceToGo() != 0){Stepper1.run();}   // Step to adjusted home position
       Stepper1.setCurrentPosition(0);   // Set Home position that will be used for all further movements..
       Serial.println("........ Homing Completed ........");
       Serial.println(" *** Enter Compass Heading 0 - 259 Degrees ***");
       // ---------   End of intial Homing Setup  ------------
       }
       void loop() {
       while (Serial.available() > 0) {   // Read serial input:
       int InChar = Serial.read();
       if (isDigit(InChar)) {InputString += (char)InChar;}   // Convert the incoming byte to a char and add it to the string
       if (InChar == '\n') {   // If you get a newline,
       NewHeading = (InputString.toInt());   // Convert input heading string to int value heading
       NewHeading = (NewHeading/2)*2;   // Eliminates 1 degree movements. Reduces movement errors with small movements
       Serial.print(NewHeading);

       if(NewHeading > 359 ||NewHeading < 0) {   // Displays error message if input is out of range
       NewHeading = LastHeading;   // No change due to incorrect data entered
       Serial.println("Input Error. Enter value between 0 - 259 Degrees ");
       }
       else { Serial.print("Heading "); Serial.print(NewHeading); Serial.println("...  Enter New Heading");

       }
       InputString = "";   // Clear the string for new input:
       Movement = ((NewHeading + 180 - LastHeading) % 360) - 180;   // Allows movement from North East to North West
       if(Movement < -180){Movement = Movement + 360;}   // Allows movement from North West to North East
       Stepper1.setCurrentPosition(0);   // Zero the motor.
       Stepper1.setMaxSpeed(MaxSpeed);   // Set Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Set Acceleration of Stepper1

       Stepper1.move(Movement*2);   // Set new move to position of Stepper1
       LastHeading = NewHeading;   // New heading now becomes last heading
       }
       }
       while(Stepper1.distanceToGo() != 0){Stepper1.run();   // Keep updating AccelStepper for current movement
       int XInChar = Serial.read();XInChar = Serial.read();}   // Keep clearing serial buffer- Only allow new heading input once movement finished.
       }


text:
What is the best serial communication method between an Arduino and a spectral sensor?
I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.

The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.
You will have no issues using the I2C interface - in fact Adafruit uses it for their own software library.
Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.

Arduino will serve as the Master controller and will send the call to the slaves. AS7262 is a sensor device, Arduino will send the call commmand then receive the data from its sensors.  Sometime confusion arrises because developers are accustomed to the desktop computer as the Master, but in this case, Arduino receives data and engage a forward action like sending info to USB or WiFi connected computer or just do a feedback control to another digital or analog device.
You will find further reading on this subject at Arduino community here
Also


text:
controll intigers from webserver on nodeMCU esp8266
I would like to controll neopixel leds from over wifi with my nodeMCU but i dont know how to controll values over wifi, through a web interface would be perferable over url, but that also works.
usinf arduinoIDE for all code.

did you see the WebServer example of the ESP8266WiFi library?

yes i di but that shows just on and off when it detects a webpage loading and not seting a value in a forfum in a forum

and ESP8266WebServer library?

what do you mean by that?

there is a ESP8266WebServer library in the esp8266 Arduino package

ive taken a look at the web server and advanced web server examples but saw nothing, i can look at the direct .h file if thats what you mean?


text:
Arduino esp8266 EEPROM lag
Trying to save my LED-State to EEPROM.
After every 5 seconds my EEPROM saves the value of white in this example (didn't put in RGB yet)
When the EEPROM gets commited and the value changes the LED is dark for a few milliseconds
what can I do?
int xInt = wVal.toInt();
white_val = xInt;
controlLed(whitePin, xInt);

Triggers LED:
void controlLed(int pin, int integer) {
  analogWrite(pin, integer);
  return;
}

Loop Saving Data every five seconds:
void loop() {
  static unsigned long startTemp = 0;
  unsigned long msTime = millis();

  if (msTime - startTemp >= 5000) {
    startTemp = msTime;
    writeEeprom(white_address, white_val);
  }
}

Writes Data to EEPROM:
void writeEeprom(int address, int value) {
  EEPROM.put(address, value);
  Serial.println("WRITTEN  TO EEPROM:");
  Serial.println(address);
  Serial.print("\n");
  Serial.println(value);
  Serial.print("\n");
  EEPROM.commit();

  EEPROM.get(address,value);
  Serial.println("READ  FROM EEPROM:");
  Serial.println(address);
  Serial.print("\n");
  Serial.println(value);
  Serial.print("\n");
  return;
}

What's the GPIO number of the pin you're using to control the LED?

const int whitePin = 14;
It's a esp8266 ESP-07

the first snippet is from setup()? which version of esp8226 Arduino core you use?

No the first snippet gets triggered when the value changes
`
if(text.startsWith("w")){
        String wVal=(text.substring(text.indexOf("w")+1,text.length()));
        int wInt = wVal.toInt();
        white_val = wInt;
        controlLed(whitePin, wInt);
        webSocket.sendTXT(num, "white changed", lenght);
       }

`
Latest Stable:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
And Arduino 1.8.7
esp8266 has version 2.4.2