text:
Understanding why should avoid “String” and alternative solutions

Why “Strings” are bad for Arduino?
Which is the most efficient and fastest solution to read and store the data from Accelerometer and GPS?

Stings are evil for Arduino

An Uno or other ATmega328-based board only has 2048 bytes SRAM.
The SRAM is composed by three parts:

The Static
The Heap
The Stack

The Heap is where, randomly, a C++ string information is allocated.
If I add an information to my C++ String the system copies itself and deletes the old copy leaving a hole in the heap, that grows up with the cycles.
When I wrote my first sketch for reading and writing the information from an MPU6050 and stored on a SD (whithout connecting to a GPS) I noticed that the sampling time was not constant.

Thanks to the feedback obtained in this question on StackOverflow, I understood that the problem was my excessive use of strings, and now i understand why.
So I started to dig into this issue.
This was one of the first version of the code:
/******************************************************************************
  CSV_Logger_TinyGPSPlus.ino
  Log GPS data to a CSV file on a uSD card
  By Jim Lindblom @ SparkFun Electronics
  February 9, 2016
  https://github.com/sparkfun/GPS_Shield

  This example uses SoftwareSerial to communicate with the GPS module on
  pins 8 and 9, then communicates over SPI to log that data to a uSD card.

  It uses the TinyGPS++ library to parse the NMEA strings sent by the GPS module,
  and prints interesting GPS information - comma separated - to a newly created
  file on the SD card.

  Resources:
  TinyGPS++ Library  - https://github.com/mikalhart/TinyGPSPlus/releases
  SD Library (Built-in)
  SoftwareSerial Library (Built-in)

  Development/hardware environment specifics:
  Arduino IDE 1.6.7
  GPS Logger Shield v2.0 - Make sure the UART switch is set to SW-UART
  Arduino Uno, RedBoard, Pro, Mega, etc.
******************************************************************************/

#include <SPI.h>
#include <SD.h>
#include <TinyGPS++.h>
#include<Wire.h>
#define ARDUINO_USD_CS 10 // uSD card CS pin (pin 10 on SparkFun GPS Logger Shield)

/////////////////////////
// Log File Defintions //
/////////////////////////
// Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
// and a 3 char suffix.
// Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
#define LOG_FILE_PREFIX "gpslog" // Name of the log file.
#define MAX_LOG_FILES 100 // Number of log files that can be made
#define LOG_FILE_SUFFIX "csv" // Suffix of the log file
char logFileName[13]; // Char string to store the log file name
// Data to be logged:
#define LOG_COLUMN_COUNT 15
char * log_col_names[LOG_COLUMN_COUNT] = {
  "longitude", "latitude", "altitude", "speed", "course", "date", "time", "satellites","Acc.X","Acc.Y","Acc.Z","Gy.X","Gy.Y","Gy.Z","Temp"
}; // log_col_names is printed at the top of the file.

//////////////////////
// Log Rate Control //
//////////////////////
#define LOG_RATE 1000 // Log every 1 seconds
unsigned long lastLog = 0; // Global var to keep of last time we logged

/////////////////////////
// TinyGPS Definitions //
/////////////////////////
TinyGPSPlus tinyGPS; // tinyGPSPlus object to be used throughout
#define GPS_BAUD 9600 // GPS module's default baud rate

/////////////////////////////////
// GPS Serial Port Definitions //
/////////////////////////////////
// If you're using an Arduino Uno, Mega, RedBoard, or any board that uses the
// 0/1 UART for programming/Serial monitor-ing, use SoftwareSerial:
#include <SoftwareSerial.h>
#define ARDUINO_GPS_RX 9 // GPS TX, Arduino RX pin
#define ARDUINO_GPS_TX 8 // GPS RX, Arduino TX pin
SoftwareSerial ssGPS(ARDUINO_GPS_TX, ARDUINO_GPS_RX); // Create a SoftwareSerial

// Set gpsPort to either ssGPS if using SoftwareSerial or Serial1 if using an
// Arduino with a dedicated hardware serial port
#define gpsPort ssGPS  // Alternatively, use Serial1 on the Leonardo

// Define the serial monitor port. On the Uno, Mega, and Leonardo this is 'Serial'
//  on other boards this may be 'SerialUSB'
#define SerialMonitor Serial
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup()
{
   Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  SerialMonitor.begin(9600);
  gpsPort.begin(GPS_BAUD);

  SerialMonitor.println("Setting up SD card.");
  // see if the card is present and can be initialized:
  if (!SD.begin(ARDUINO_USD_CS))
  {
    SerialMonitor.println("Error initializing SD card.");
  }
  updateFileName(); // Each time we start, create a new file, increment the number
  printHeader(); // Print a header at the top of the new file
}

void loop()
{
 Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
{
  if ((lastLog + LOG_RATE) <= millis())
  { // If it's been LOG_RATE milliseconds since the last log:
    if (tinyGPS.location.isUpdated()) // If the GPS data is vaild
    {
      if (logGPSData()) // Log the GPS data
      {
        SerialMonitor.println("GPS logged."); // Print a debug message
        lastLog = millis(); // Update the lastLog variable
      }
      else // If we failed to log GPS
      { // Print an error, don't update lastLog
        SerialMonitor.println("Failed to log new GPS data.");
      }
    }
    else // If GPS data isn't valid
    {
      // Print a debug message. Maybe we don't have enough satellites yet.
      SerialMonitor.print("No GPS data. Sats: ");
      SerialMonitor.println(tinyGPS.satellites.value());
    }
  }

  // If we're not logging, continue to "feed" the tinyGPS object:
  while (gpsPort.available())
    tinyGPS.encode(gpsPort.read());
}
}

byte logGPSData()
{
  File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

  if (logFile)
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.
    logFile.print(tinyGPS.location.lng(), 6);
    logFile.print(',');
    logFile.print(tinyGPS.location.lat(), 6);
    logFile.print(',');
    logFile.print(tinyGPS.altitude.feet(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.speed.mph(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.course.deg(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.date.value());
    logFile.print(',');
    logFile.print(tinyGPS.time.value());
    logFile.print(',');
    logFile.print(tinyGPS.satellites.value());
    logFile.print(AcX);
    logFile.print(',');
    logFile.print(AcY);
    logFile.print(',');
    logFile.print(AcZ);
    logFile.print(',');
    logFile.print(GyX);
    logFile.print(',');
    logFile.print(GyY);
    logFile.print(',');
    logFile.print(GyZ);
    logFile.print(',');
    logFile.print(Tmp);
    logFile.println();
    logFile.close();

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

// printHeader() - prints our eight column names to the top of our log file
void printHeader()
{
  File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

  if (logFile) // If the log file opened, print our column names to the file
  {
    int i = 0;
    for (; i < LOG_COLUMN_COUNT; i++)
    {
      logFile.print(log_col_names[i]);
      if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
        logFile.print(','); // print a comma
      else // If it's the last column
        logFile.println(); // print a new line
    }
    logFile.close(); // close the file
  }
}

// updateFileName() - Looks through the log files already present on a card,
// and creates a new file with an incremented file index.
void updateFileName()
{
  int i = 0;
  for (; i < MAX_LOG_FILES; i++)
  {
    memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
    // Set logFileName to "gpslogXX.csv":
    sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
    if (!SD.exists(logFileName)) // If a file doesn't exist
    {
      break; // Break out of this loop. We found our index
    }
    else // Otherwise:
    {
      SerialMonitor.print(logFileName);
      SerialMonitor.println(" exists"); // Print a debug statement
    }
  }
  SerialMonitor.print("File name: ");
  SerialMonitor.println(logFileName); // Debug print the file name
}

Then I started:

Studying how  Arduino Memory works
Breaking the problem, focusing only to learn how to read and write on a SD the accelerometer information (the device is not connected to the PC)

The following code is my latest version:
 void Read_Write()
 // function that reads the MPU and writes the data to the SD.
  {
   // Local variables:
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // Variables read from MPU6050

// Read data:
Wire.beginTransmission(MPU);
Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
AcX = Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)

GyX = Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

// Data preparation for file saving:
String dataString = ""; // string for assembling the data to log:

// Add time tag:
dataString += String(Time0); dataString += ",";

// Append the MPU6050 data to the string:
dataString += String(AcX); dataString += ",";
dataString += String(AcY); dataString += ",";
dataString += String(AcZ); dataString += ",";
dataString += String(GyX); dataString += ",";
dataString += String(GyY); dataString += ",";
dataString += String(GyZ);

// Open the file in append mode:
File dataFile = SD.open("datalog.txt", FILE_WRITE);

// If the file is available, write to it:
if (dataFile)
{
dataFile.println(dataString);
dataFile.close();
if (Serial_plus_SD)
  Serial.println(dataString);
}
// if the file does not open, pop up an error:
else
errorFW();

return;
}

I recived other suggestions such as "create a Buffer", but without a technical description and motivation I am having difficulties understand how to do it.
(I don’t want to simply copy&paste the code as i have done intitially with the first version)
I have to use C Strings instead of C++ Strings?
I have a civil engineer background, so is my first time with coding.
Thank you for your patience.

First, let me point out a problem in your code, completely unrelated to
your question:
AcX = Wire.read()<<8|Wire.read();

The C++ standard does not specify in which order the two reads will be
performed. This may work well with the particular version of the
particular compiler you are using, but it can break the day you (or an
update to the Arduino IDE) changes the compiler version or a compiler
flag. You should instead do a single read per statement, e.g.:
AcX  = Wire.read() << 8;
AcX |= Wire.read();

Next, I would like to say that the simplest Arduino way of doing what
you are trying to do is to use neither a String nor a character array.
Instead, open the file first, then format and send the data on the fly
using print() or println():
dataFile.print(Time0); dataFile.print(",");
dataFile.print(AcX);   dataFile.print(",");
[...]

This way you never need to store the whole string in memory. It is then
a very memory-friendly solution.
Now, I realize this seems inconvenient if you want to print the data to
both the SD file and the serial port. In such a case you could put the
printing code inside a function that can print to any Print object
(for instance the data file and Serial), and you can then call the
function twice:
static void printImuData(Print &printer, int16_t Time0,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{
    printer.print(Time0); printer.print(",");
    printer.print(AcX);   printer.print(",");
    [...]
}

[...]

printImuData(dataFile, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);
if (Serial_plus_SD)
    printImuData(Serial, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

Alternatively, you could use a kind of tee to duplicate the data to
both streams. See for example this implementation.
Edit: A more elegant way to achieve the same would be to wrap all
the IMU data into a struct (or a class), and then make the whole
thing printable:
struct ImuData : public Printable
{
    uint16_t Time0, AcX, AcY, AcZ, GyX, GyY, GyZ;
    size_t printTo(Print& p) const;
};

size_t ImuData::printTo(Print& p) const
{
    size_t bytes = 0;
    bytes += p.print(Time0); bytes += p.write(',');
    [...]
    bytes += p.print(GyZ);
    return bytes;
}

The you can print the struct like you would print the string:
ImuData imu;
imu.Time0 = ...;
imu.AcX   = Wire.read() << 8;
imu.AcX  |= Wire.read();
[...]

dataFile.println(imu);
if (Serial_plus_SD)
    Serial.println(imu);

This is actually a good answer.

@Edgar why you use this Print &printer, int16_t Time0, [...]  (or where i can find more (specific) information about the theory behind this) ?

Please be more specific, and maybe ask a new question. As I understand it, you are asking for a tutorial on the “theory” behind the C++ language, which is a question far too broad for this site.

@EdgarBonet yes, it is a noob question,  i was trying to understand and studying the pointer, in this specific situation how  &printer works :)

@uomodellamansarda: It's a reference, similar to a pointer but safer.

Edgar answers your first question about String and printing very nicely.  Majenko also has a nice description here of the pitfalls.
Regarding your second question about GPS/efficiency/speed:

use NeoGPS,
use AltSoftSerial,
use the MPU FIFO,
use the up-to-date SdFat,
watch out for SD write delays, and
close the log file at some point.

1. NeoGPS is the smallest, fastest and most accurate GPS parser available.  The example programs are structured properly, and there is an example for SD logging.
NeoGPS has a FIFO of fixes, unlike other libraries.  This avoids "sampling" the GPS at some rate defined by millis().  The Arduino crystal is not as accurate as the atomic GPS clock, so your logging rate should be based off a fix becoming available, at exactly one per second.  Your sketch will "drift" against the GPS updates, losing a fix periodically (depending on the accuracty of the crystal).
2.  Perhaps the single greatest improvement you could achieve is NOT to use SoftwareSerial.  It is very inefficient, because it disables interrupts for long periods of time.  At 9600, it disables interrupts for 1ms while each character from the GPS device is received.  The Arduino could have executed ~10000 instructions during that time, but instead it twiddles its thumbs while waiting exclusively for each bit of a byte to arrive... -_-
Instead, you should use AltSoftSerial, as you have connected the GPS device to the required pins, 8 & 9.  If you were using two other pins, you could have used my NeoSWSerial.  Both of these libraries are much, much more efficient than SoftwareSerial.
3.  If you want evenly-spaced MPU samples, put the device in the FIFO mode.  It will write the selected registers into a FIFO at a selected sampling time.  This also gives you a little flexibility in reading the sample: you just have to read it before the 1024-byte FIFO fills up.
4.  You are using an old version of the SD library.  I strongly suggest that you use the latest SdFat library.  It has many improvements and bug fixes.
5.  Some SD cards will occasionally take a longer time to write.  The 47ms write time is not unusual.  In fact, 100ms is fairly common.  As long as the MPU FIFO does not overflow during this time, you will not lose any MPU samples.
If you find that an SD write occasionally causes the FIFO to overflow, you may have to modify the SDFat library to call a yield function while it's waiting for the write to complete.  This yield function can read from the FIFO during that time, saving the samples into an Arduino RAM area.
6.  I would recommend that you close the logFile when some event occurs.  Perhaps a button press?  You can use the LED to indicate that logging is active or inactive.  You could also watch for inactivity for some period of time (no speed, MPU zero values).

With those suggestions, here is a NeoGPS/AltSoftSerial/SdFat version of your original sketch (GPS tested, MPU/SD untested but compiles):
#include <SPI.h>
#include <SdFat.h>
#include <NMEAGPS.h>
#include <Wire.h>
#define ARDUINO_USD_CS 10 // uSD card CS pin (pin 10 on SparkFun GPS Logger Shield)

/////////////////////////
// Log File Defintions //
/////////////////////////
// Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
// and a 3 char suffix.
char logFileName[13] = "gpslogXX.csv";
// Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
#define MAX_LOG_FILES 100 // Number of log files that can be made

// Data to be logged:
#define LOG_COLUMN_HEADER \
  "longitude," "latitude," "altitude," "speed," "course," "date," "time," \
  "satellites," "Acc.X," "Acc.Y," "Acc.Z," "Gy.X," "Gy.Y," "Gy.Z," "Temp"
  // printed at the top of the file.

SdFat SD;
File  logFile;

/////////////////////////
// NeoGPS Definitions //
/////////////////////////
NMEAGPS gps; // NeoGPS object to be used throughout
gps_fix fix; // The latest GPS information received from the gpsPort
#define GPS_BAUD 9600 // GPS module's default baud rate

/////////////////////////////////
// GPS Serial Port Definitions //
/////////////////////////////////
// If you're using a Mega, Leo or Due, use Serial1 for the GPS:
//#define gpsPort Serial1

// If you're using an Arduino Uno or other ATmega328 board that uses the
// 0/1 UART for programming/Serial monitor-ing, use AltSoftSerial:
#include <AltSoftSerial.h>
AltSoftSerial gpsPort; // Always on pins 8 & 9
//If you can't use pins 8 & 9, use this:
//#include <NeoSWSerial.h>
//NeoSWSerial gpsPort( 2, 3 ).

// Define the serial monitor port. On the Uno, Mega, and Leonardo this is 'Serial'
//  on other boards this may be 'SerialUSB'
#define SerialMonitor Serial

//#define USE_MPU
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup()
{
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  SerialMonitor.begin(9600);
  gpsPort.begin(GPS_BAUD);

  SerialMonitor.println( F("Setting up SD card.") );

  updateFileName(); // Each time we start, create a new file, increment the number
  // see if the card is present and can be initialized:
  if (!SD.begin(ARDUINO_USD_CS))
  {
    SerialMonitor.println( F("Error initializing SD card.") );
  } else {
    logFile = SD.open( logFileName, FILE_WRITE );
    // Print a header at the top of the new file
    logFile.println( F(LOG_COLUMN_HEADER) );
  }

}

void loop()
{
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  while (gps.available( gpsPort )) {
    fix = gps.read();  // get the entire fix structure, once per second

    if (logGPSData()) { // Log the GPS data
      SerialMonitor.println( F("GPS logged.") ); // Print a debug message
    } else {// If we failed to log GPS
      // Print an error, don't update lastLog
      SerialMonitor.println( F("Failed to log new GPS data.") );
    }
  }
}

byte logGPSData()
{
  if (logFile.isOpen())
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.

    if (fix.valid.location)
      logFile.print(fix.longitude(), 6);
    logFile.print(',');
    if (fix.valid.location)
      logFile.print(fix.latitude(), 6);
    logFile.print(',');
    if (fix.valid.altitude)
      logFile.print(fix.altitude() * 3.2808, 1);
    logFile.print(',');
    if (fix.valid.speed)
      logFile.print(fix.speed_mph(), 1);
    logFile.print(',');
    if (fix.valid.heading)
      logFile.print(fix.heading(), 1);
    logFile.print(',');

    if (fix.valid.date) {
      logFile.print( fix.dateTime.full_year() );
      if (fix.dateTime.month < 10)
        logFile.print( '0' );
      logFile.print( fix.dateTime.month );
      if (fix.dateTime.date < 10)
        logFile.print( '0' );
      logFile.print( fix.dateTime.date );
    }
    logFile.print(',');

    if (fix.valid.time) {
      if (fix.dateTime.hours < 10)
        logFile.print( '0' );
      logFile.print( fix.dateTime.hours );
      if (fix.dateTime.minutes < 10)
        logFile.print( '0' );
      logFile.print( fix.dateTime.minutes );
      if (fix.dateTime.seconds < 10)
        logFile.print( '0' );
      logFile.print( fix.dateTime.seconds );
    }
    logFile.print(',');

    if (fix.valid.satellites)
      logFile.print(fix.satellites);
    logFile.print(',');
    logFile.print(AcX);
    logFile.print(',');
    logFile.print(AcY);
    logFile.print(',');
    logFile.print(AcZ);
    logFile.print(',');
    logFile.print(GyX);
    logFile.print(',');
    logFile.print(GyY);
    logFile.print(',');
    logFile.print(GyZ);
    logFile.print(',');
    logFile.print(Tmp);
    logFile.println();
    logFile.flush(); // make sure the file contains at least this much

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

// updateFileName() - Looks through the log files already present on a card,
// and creates a new file with an incremented file index.
void updateFileName()
{
  for (uint8_t i; i < MAX_LOG_FILES; i++)
  {
    // Set logFileName to "gpslogXX.csv":
    logFileName[6] = (i/10) + '0';
    logFileName[7] = (i%10) + '0';

    if (!SD.exists(logFileName))
      break; // We found our index

    SerialMonitor.print(logFileName);
    SerialMonitor.println( F(" exists") );
  }
  SerialMonitor.print( F("File name: ") );
  SerialMonitor.println(logFileName);
}

Your original sketch used 24114 bytes of program space and 1690 bytes of RAM.
The NeoGPS version uses 21198 bytes of program space and 1400 bytes of RAM, a significant savings.
Minor points:

It uses the F macro to save RAM
It opens the log file in setup and flushes after every GPS update.  You should investigate when to close the log file.
It reads IMU samples as fast as possible, but you should switch this to the FIFO approach
It doesn't use sprintf to compose the log filename (this saves program space)
The column header does not need to be an array of character strings.  It can be one #define. The F macro is applied when it is printed.
It only prints GPS fields if they have a valid value.
Comments in the GPS port section were wrong about using SoftwareSerial on a Mega.
Obvious comments deleted.  The else of an if statement does not deserve an // otherwise comment.  -_-

@slash-dev i am tryng to go deep, and understanding the entire code, sorry for my noob questions. 1) Why in your code you use AltSoftSerial and
SoftwareSerial.h ? 2) Why did you create two objects "gps" and "Fix"  i also read the documentation on github Thanks for your time!

@uomodellamansarda, read point 2 in my answer.  SoftwareSerial is very inefficient, so you should use something else.  Read more about it here.  The gps object is responsible for reading chars from gpsPort and creating fix structures for you to read (just like TinyGPS++).  The fix object holds on to all the GPS values that were parsed from the gpsPort.  Calling gps.read() fills out the fix object (it's a local copy for you to use anywhere in your sketch).  You can use various pieces of that object, like fix.latitude().

@slash-dev my noob mistake, thanks for sharing the link! :)

I would use sprintf, with a statically allocated buffer.
E.g.
substitute
// Data preparation for file saving:
String dataString = ""; // string for assembling the data to log:

// Add time tag:
dataString += String(Time0); dataString += ",";

// Append the MPU6050 data to the string:
dataString += String(AcX); dataString += ",";
dataString += String(AcY); dataString += ",";
dataString += String(AcZ); dataString += ",";
dataString += String(GyX); dataString += ",";
dataString += String(GyY); dataString += ",";
dataString += String(GyZ);

with
static char pippo[PIPPO_SIZE];
int ret = sprintf(pippo, "%lu,%d,%d,%d,%d,%d,%d",
                         (uint32_t) Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

// This is just for debugging purposes to test the code
if (ret < 0) {
    // failure: no byte written
} else if (ret >= PIPPO_SIZE) {
    // failure: too many bytes written, I did some mistake :(
} else {
    // ok
}

The size of the buffer pippo is computed as follows:

1 byte for each comma, you have 6
6 bytes for each int16_t variable (5 bytes for the digits plus 1 byte for the sign, which however you might not need)
10 bytes for Time0, which I assume is of type unsigned long which in Arduino is 32 bits.
1 byte for closing \0

So it should be 1 * 6 + 6 * 6 + 10 + 1 = 53 unless I did some mistake. Add the following at the top of your program:
#define PIPPO_SIZE 53

The motivation for using statically allocated memory is simple, and is already stated in your question: the concatenation of String objects results in repeated calls to new and delete with subsequent allocation and de-allocation of dynamic memory, which gets fragmented. More over, the String-based approach is intuitively slower because it requires many more steps to accomplish basically the same simple task.
String aren't bad per se, but in your application you want to squeeze every last fragment of performance that you can, so there's that.

For fixed strings (which do not change), use e.g. F("Text") ... this will place the string in flash instead of heap space. Note that the Uno has 32 KB of flash and 2 KB of SRAM (which is used for heap space among others).
If you need variable sized strings but one or few at a time, make a dedicated buffer (of e.g. 64 bytes) and use that buffer for all string operations. It will take up 64 bytes all time, but will leave no heap gaps.
You can create it as a global variable (simple):
char string_buffer[64];

and use that string_buffer for string operations.
Note that heap gaps are bad for all devices/operating systems, however since the Arduino has very little builtin SRAM, it is filledup quickly when using strings without thinking about memory management.

A chat system I used to use "back in the day" used a fixed "stack" based string buffer.
Basically a single char * buffer of a fixed size was created at the beginning of the program and initialised to 0.
Then strings were appended to that buffer using whatever functions were appropriate at that time. A pointer was kept pointing to the start of the "free" space in the buffer. This is the pointer which was used for placing new text into that buffer.
The entire buffer was then printed to the output stream in one block, the first byte cleared, and the pointer reset to the start of the buffer.
This made a very efficient and simple string buffer which didn't fragment memory in any way and still allowed the use of standard C string functions such as sprintf(), strcpy(), etc.
For example:
char strbuf[128] = { 0 };
char *strptr = strbuf;

strcpy_P(strptr, (PGM_P)F("Temp = "));
strptr += strlen(strptr);
itoa(temperature, strptr, 10);
strptr += strlen(strptr);

Serial.println(strbuf);
strbuf[0] = 0;
strptr = strbuf;

Which is the most efficient and fastest solution to read and store the data from Accelerometer and GPS?
You don't state how fast is fast enough nore how long you want to record the data for.  Particularly for the Accelerometer data.
This suggested solution will log ~800 Accelerometer samples/sec  (7 x 16bit ints) continually for 30 days.
There are two problems
i) reading and parsing the GPS and reading the Accelerometer
ii) storing the data on the SD card.
Reading/parsing the GPS data takes time.  This tutorial, Arduino Serial I/O for the Real World covers buffering serial input, parsing GPS data and buffering serial (text/debug) output.
Reading the accelerometer data is much faster, leave it in binary form.
Storing data on the SD card can be very slow.
Bill Greiman's AnalogBinLogger example in an earlier version of his SdFat Arduino library, uses a pre-allocated and erased SD file and special block writes to minimize the SD latency.
https://github.com/greiman/SdFat  (code for the earlier version with AnalogBinLogger)
This project, High Frequency, Long Duration Datalogging, uses an Uno/Mega to store 512byte blocks of data to an SD card in less then 1mS each block, continually for 30days.
It uses an interrupt to collect the ADC data and two 512byte buffers it for collecting the incoming data and writing to the SD card.
Applying these two projects to your situation you could

use on Mega2560 to read/buffer/filter/parse the GPS data and interleave it with the Accelerometer data and buffer it for binary transfer to
the second Mega2650 via Serial (115200baud) i.e. ~11.5Kbytes/sec. For 7 x int16_t accelerometer variables that would be about 800 samples/sec over the serial connection in binary format.
The standard Mega2560 64byte TX Serial buffer should be sufficient.

In the second Mega265 you need to modify the UART interrupt handler for one of the UARTs to fill the current SD buffer instead of the normal receive buffer.
When the buffer is full the interrupt swaps it for a second buffer as in the high speed logger project above.

The second Mega would also have a command and control Serial input to prepare the SD card and start/stop the storage.
A single board apporach
Since the SD write of the 512 block takes <1mS you could also look a combining these two processes into on board.
Read/buffer/parse fill the 512 block. When it is full, block for 1ms while the SD writes that buffer.  This approach will reduce accelerometer sampling frequency.  See Simple Multitasking Arduino for how to interleave the tasks for reading/parsing the GPS with sampling the accelerometer and writing the SD card

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


text:
Ethernet shield not working
I have an ethernet shield on an Arduino Mega 2560. I am running the code below. This is a slightly modified version of the DHCP ip printer example, namely I am setting a static IP instead of DHCP.
I was expecting to get:
Start Ethernet
My IP address: 192.168.178.163.

on the serial monitor. Instead I got:
Start Ethernet
My IP address: 0.237.237.237.

Any idea what the reason might be? If I am using DHCP (the unmodified example, commented lines in the code below), the code seems to freeze on the Ethernet.begin() call.The "Failed to configure ..." is not even printed.
Here is the sketch:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x10, 0xC1, 0x2C
};
byte ip[] = {192, 168, 178, 163};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Start Ethernet");
  // start the Ethernet connection:
  Ethernet.begin(mac, ip);
  /*if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }*/
  // print your local IP address:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  Serial.println();
}

The situation is similar to Ethernet shield not getting IP, but I checked that all pins are connected properly. Also setting pin 10 to high does not change anything.

Which Ethernet controller chip does your Ethernet Shield have? The common ones are W5100, W5200 and W5500.

It is the W5500

Check out the same issue here.

This happens when the network isn't bridged. You can check this link here

I found the solution in modrego's answer on Arduino Ethernet Shield 2 stuck on EthernetServer::begin(). I need the Ethernet2 library for the W5500 Ethernet controller. The Ethernet library is for W5100 only.
This library is not included with the arduino.cc library(as of IDE version 1.6.12 and older, this will likely change in future versions). I had to install it. You can do this by:

Sketch > Include Library > Manager Libraries...
Type "ethernet2" in the Filter your search... field
Click on the Ethernet2 entry.
Click the Install button.
Click the Close button.

You will need to change the line:
#include <Ethernet.h>

to:
#include <Ethernet2.h>

Other files included in example sketches for the Ethernet library will need similar modifications.

Thanks, this is what I needed to do too. Doesn't really seem to be any official docs stating this.

Note that because the W5100 and SD card share the SPI bus, only one
  can be active at a time. If you are using both peripherals in your
  program, this should be taken care of by the corresponding libraries.
  If you're not using one of the peripherals in your program, however,
  you'll need to explicitly deselect it. To do this with the SD card,
  set pin 4 as an output and write a high to it. For the W5100, set
  digital pin 10 as a high output.

Ref. https://www.arduino.cc/en/Main/ArduinoEthernetShield

I think the relevant documentation is: https://www.arduino.cc/en/Main/ArduinoEthernetShieldV2 . I tried setting 10 to LOW and 4 to HIGH, as well as the other way round, no effect. The documentation also says port 53 needs to be an output, but that does not have any influence either.

source: Stack Exchange

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

sort: votes


text:
Error in sending AT commands in esp8266 connecting to arduino IDE
I am working on esp8266 with Arduino.
I have connected pins like arduino-esp 3.3-vcc
gnd-gnd 3.3-CH_PD RX-TX TX-RX  and reset to gnd using 3k resistor.
I couldn't send AT commands in serial monitor in Arduino IDE.
Later I connected a capacitor between Vcc and Gnd. Now I could send AT commands and I am getting same commands back. Whatever I entered, I am getting the same back.
I didn't get reply as OK. And I got some random characters too. Can anyone help me with this?

I think TX needs to go to TX and RX to RX, if you are sending the command via the computer instead of the arduino-sketch. You also need to convert the 5v to 3.3v on the RX line.

You also need to convert the 5v to 3.3v on the RX line. - s/he needs to do what?

I have connected pins like arduino-esp 3.3-vcc gnd-gnd 3.3-CH_PD RX-TX TX-RX and reset to gnd using 3k resistor. - you connected what to what? This is very unclear. Please edit your question and clarify what you have done. Also try to write proper English if possible. Sentences start with a capital letter.

Looks like your connection is somewhere missing.
Connect CH_PD and reset pin to high--i.e. 3.3v.

Please do not insert advertisements into your post. You are welcome to add this to your profile page, but not into the post itself. I've edited it out. Thanks!

I made the following connection with Arduino Mega 2560 and AT commands was working perfectly well.
Connection:
ESP8266 - Arduino Mega 2560
Vcc, CH_PD, RST - 3.3V pin
GND - GND
Rx - Tx(18)
Tx - Rx(19)
Program:
void setup() {
  Serial.begin(115200);   // USB serial port of Due (PROGRAMMING)
  Serial1.begin(115200);  // ESP8266 on Serial Port 1 of Due (UART 1)
}

char rx_byte = 0;

void loop() {
  // send terminal byte to ESP8266
  if (Serial.available() > 0) {
    rx_byte = Serial.read();
    Serial1.print(rx_byte);
  }
  // send ESP8266 byte to terminal
  if (Serial1.available() > 0) {
    rx_byte = Serial1.read();
    Serial.print(rx_byte);
  }
}

Select Tools>Board> Arduino/Genuino Mega or Mega 2560. Upload the code. In serial monitor, select 115200 baud rate and Both NL & CR option.
Enter the AT command and it works!

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


text:
What device do I add in order to detect if my project is moved?
I seem to be going round in circles trying to find the answer to this question, so thought I'd ask the good folk here.
I have an Arduino pro mini 3.3v based project, using lowpower libraries. It wakes up every h hours and takes a reading.  I would now like it to still wake up every h hours but in the meantime know whether the item (the board, or its container) has actually physically been moved - like binary, did it move or not at all?
I don't need constant monitoring of position. Once triggered I'd turn off the interrupt until the next wake up event.
In my mind I see the solution as being an interrupt attached to low power device which when moved slightly triggers the event to be recorded.
pseudo code would be:
if ((hour == h_hour) && movementDetectedSinceLastWakeup){
  doStuff();
} else {
  goBackToSleep(2hrs);
}

My question is, what kind of sensor should I consider for this job?

3.3v
lowpower
can trigger interrupt

EDIT "move" as in it vibrated past some set level.

Define move: physically change location, or just receive some vibration but stay in the same location?

Ah, good point.  Move as in vibrated, hopefully the target level of vibration could be defined.  Nice one.

There's two basic ways of detecting vibration - one which is quantifiable and one which isn't (much).
The simplest way is a sprint (possibly weighted) inside a metal tube. Vibration causes the spring to move and touch the tube - the resultant circuit is just the same as using a button. Sensitivity can't be controlled (other than maybe "how many times in a given period does the spring touch the tube"), but it's very very simple to use. They are often used in simple movement alarms (for things like bikes, etc).
The second method is to use an accelerometer. These are harder to work with but they do give you the actual amount of vibration at any given time. They are far more sensitive than a simple spring+tube, but since they are an active component they need to be constantly queried (often through I2C or an analog input). That makes them harder to use in a low-power scenario.
Some accelerometers are more intelligent and can be programmed to trigger an interrupt when vibration above a certain level is detected, though again that increases the complexity of working with them.
So in short: the lowest power option is the simple spring+tube sensor - it uses zero quiescent current. The best option is a programmable accelerometer that can trigger an interrupt to wake the main MCU. Which you choose depends on how sensitive you need the device to be...

I did not know such a thing existed. Similar to this https://www.adafruit.com/product/2384 I am guessing. Vibration momentarity closes a circuit, but, can that evoke an interrupt?

Yes. It's just a button. Only instead of a finger, vibration presses it.

I would say, that a gyroscope would be perfect for physical movement. In case there is change in X, Y or Z axis, it should turn on a flag as an indicator.
The model MPU-6050 would be ok for this project.

A gyro struggles to detect lateral momentum - they only really work for angular momentum (turning). They can't detect if the device has been slid along a desk, for instance.

Can't detect sliding, but can detect start movement, which is (in this case), a key. At least that's how I got the problem.

@Jakey No it can't. Gyroscope is not an accelerometer.

@Jakey the others are right, a gyroscope is not the sensor to detect a movement, it detects a change in rotation. A accelerometer detects motions and vibrations. It is even very sensitive for vibrations, for example the vibrations of a heavy truck driving through the street. The MPU-6050 is indeed okay (the accelerometer part). I prefer the newer MPU-9250.

Yeah, I was thinking about the right thing but my words came out wrong; I understand the difference between gyroscope and accelerometer. Sorry again.


text:
Error opening serial port 'COM1'. (Port busy)
Im using the arduino Micro pro to read the data out of a temperature sensor (lm35). The program is compiling and NOT uploading, but when I try and open the serial monitor is says: Error opening serial port 'COM1'. (Port busy)

To be able to help you it would really help to know your development environment (what OS are you working on, how are you connecting to the serial port, etc.). The message suggests that another process using the serial port, it could be as simple as need to close and reopen your terminal emulator.

Im using windows 8.1, and im connecting to the serial port via usb.

How are you connecting to the serial port (what software are you using to received the serial data)? I don't do much with Windows, but I think the problem that you're having is that your terminal emulator is expecting to see the data on your COM1 port but you're actually transmitting the data over USB and a virtual serial port. The serial monitor in the Arduino IDE picks up the serial port from the setting in the menu Tools > Port (which is also used for your upload), but other programs will need it to be explicitly set.

the software is built in the arduino IDE. I edited the post the code is not uploading, only compiling.

COM1 is usually reserved for the built in serial port in the computer. Your USB serial port is more likely going to be COM3 or COM11, or even COM23 rather than COM1.  Make absolutely sure you have the right COM port selected, and that you have installed the right serial drivers for your board.

I used this to download my driver and install it  https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows

On OS X you could check by looking at the USB devices found in the system configuration or the serial devices found in /dev – I pretty sure there is something similar in Windows 8, but it has been so long since I've used Windows that I can't remember what it is called. On OS X the IDE lists the devices that it has found, so I'd start there. If you only see COM1 then it is a good bet that you don't have the necessary USB serial drivers installed.

i tried using different coms
im getting this error: avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x5a
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x5a
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x5a
Problem uploading to board.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x5a

I've got an idea. Your board isn't being recognized. Try unplugging the arduino and see if Com 1 is still there. Sometimes it can recognize mice and other devices as Com 1 or 2 instead of your arduino.
On some of my development machines after everything settled out my devices will show up on Com 4 and 5 when I am working on two at a time.
If this is not the case go into the device manager and see if you can see the board listed.
I would also wonder if you have your sensor hooked to digital pins 0 and 1. These pins are used for your serial line on usb. So if you have anything such as a sensor hooked to them it may be generating data keeping the line busy instead of it being able to negotiate.
I had this happen when setting up hc-05 for the first time. I realized I had to keep the chip off while flashing or I would end up with errors or Com busy.
Please provide your pinout and basic information about the Com ports available on the ide. Also consider that you will need to specify the correct board as it will default to an uno.
Programmer not in sync issues generally occur because the board is recognized but cannot be written to for one reason or another.

the board has something plugged into digital 1 and 0 which are serial i/o pins
the board programmer is busy running your last batch of code
usb error

So

try a different cord
try unplugging potential wiring issues and see if it can be written to without anything on it
try holding down reset on the board until the board when you try to write to it until just after it finishes compiling to clear any potential programing issues

In my experience mega have a tendency to suffer from the last one.

I had a similar issue (port busy, RN42+Win 8.1) and find a solution by changing the usb bluetooth dongle of the computer.
The one which finally works for me was the Adafruit Bluetooth 4.0 USB Module (v2.1 Back-Compatible).

Simple solution:
Close the arduino application and start again.
if still the issue persist restart your system. :)


text:
Problems when communicating with SD card using ethernet shield
I am using the "SD read/write" code from the Arduino IDE examples to test an ethernet shield (clone). The problem is that although a file is created no data is stored in it.
When running the serial monitor will only show the first characters of the Serial.print() sentences, e.g when doing Serial.print("Initializing SD card...") the serial monitors displays Ini or In and nothing else.
Also the IDE shows the following error message: (some words in spanish)
Error dentro de Serial.serialEvent()
java.io.IOException: Error de entrada/salida in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.available(RXTXPort.java:1598)
at processing.app.Serial.serialEvent(Serial.java:258)
at gnu.io.RXTXPort.sendEvent(RXTXPort.java:774)
at gnu.io.RXTXPort.eventLoop(Native Method)
at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1644)

I have tried with 2 different SD cards, including a brand new one, and 2 different Arduino Uno (a clone and an original one). The OS is Ubuntu 13.10.
My guess is that it has something to do with the myFile.println() sentences, when they are commented the serial monitor works fine.
Any help is much appreciated since I couldn't find the problem anywhere else so far!


text:
Sketch stops working after ~40 minutes. Overflow?
I have this simple sketch I use on Arduino Micro:
int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
unsigned long prevMicros = 0;        // will store last time LED was updated  +
unsigned long interval =  7000000;           // lunghezza della pausa in secondi
unsigned long intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
 pinMode(fan, OUTPUT);
 pinMode(led, OUTPUT);
 prevMicros = micros();
}

void loop() {
  unsigned long currMicros = micros();

  // manage overflow? BOH
   if (ledState == HIGH && (((unsigned long)(currMicros  - prevMicros)) >= intervalON)){
     prevMicros = currMicros;
      ledState = LOW;
    }
    else if (ledState == LOW && (((unsigned long)(currMicros - prevMicros)) >= interval)){
      ledState = HIGH;//riparte
      prevMicros = currMicros;
    }

    digitalWrite(led, ledState);
    digitalWrite(fan, ledState);
}

I could use millis() instead of micro(), but I decided to keep this to shorten the overflow rate (should be 72 minutes). I shall go back to millis() once my issue is fixed.
The sketch works as expected, turning on the LED for a second every 7, but the sketch hangs after 40 minutes. Can you tell me why, and how to manage overflow properly? Why is it hanging after 40 and not 72 minutes? Thanks

Shouln't it be (((unsigned long)(currMicros  - prevMicros)) >= intervalON) instead of (((long)(currMicros  - prevMicros)) >= intervalON), since the timing value from micros() is unsigned?

To confirm: if the problem really is (long) vs (unsigned long) time interval comparison, then the observed behavior should be LED stops blinking after at t=40 minutes, but then starts blinking again at t=70 minutes when then micros() overflows back to 0. Definitely a good idea to test/verify with micros() first.

I think your observations deserve a voted answer :)

40 minutes is approximately 2^31 microseconds, so it seems an overflow of some kind. Also it is good practice to use type definition like uint32_t instead of unsigned long for readability and cross platform portability.

I think the problem is in the prevMicros being pushed up all the way and never being reset when the currMicros rolls over to 0. Better to use a delta for currMicros in this case rather than an absolute number. You'll have to detect and correct for micros() roll over though.

What about using unsigned long long?

Your code looks rollover-safe to me, as does the current implementation of micros(). This should work just fine across the micros() rollover. What version of Arduino are you using?

BTW, you have too many casts and parentheses: if (ledState == HIGH && currMicros - prevMicros >= intervalON) is the same, but easier to read.

Here is how you can speed up your tests: globally declare extern unsigned long timer0_overflow_count; then, in setup(), set this global variable to 0x001f0000. This way the high bit of micros() will toggle in ≈ 67 seconds. Set it to 0x003f0000 and micros() will roll back to zero, again in ≈ 67 seconds.

I just tested the program on an Uno, using the technique mentioned above to trigger a prompt rollover, and with a Serail.println(micros()); for debugging. It works exactly as expected: it does not hang. The question asked is “Why does the program hang?”. Since it does not really make sense, shouldn't the question be closed?

When comparing time intervals, use unsigned long instead of long.
if ( ... (((unsigned long)(currMicros - prevMicros)) >= intervalON) )

The time counter overflows at some point -- micros() overflows after 70 minutes, milis() overflows after nearly a month -- but these are unsigned values.
When an unsigned value is interpreted as a signed value -- (long) instead of (unsigned long) -- then half of the values are interpreted as negative numbers. So after 40 minutes, the micros() value looks like a negative number, and the (curr-prev) >= interval comparison returns false. After 70 minutes, the micros() overflows back to 0, and the signed comparisons work as expected.
The solution is to use unsigned long for all delta-time comparisons.
This is easier to see if you consider a smaller, 3-bit number: there are 8 values for a 3-bit number. If the 3-bit number is unsigned, then the values are 0, 1, 2, 3, 4, 5, 6, 7. But if the 3-bit number is signed, then those same binary code numbers are interpreted as 0, 1, 2, 3, -4, -3, -2, -1. Same principle for int and long values, just a larger range of values.
EDIT:
Based on your comment below, I did some testing on my own hardware (Sparkfun "red board" Arduino UNO R3 clone), and added some code to help make it more testable. Some highlights:

Added a diagnostic LED on Arduino pin 9, to indicate when the timer overflow has happened (i.e. new time is less than previous time).
Added a mask to force the timer overflow to happen sooner, so I don't have to wait an hour to verify whether the code had any effect.
Calculated timeSinceLastChange and applied mask, to handle overflow.
Added TIMER_DATATYPE based on jippie's comment

The complete code:
//--- based on comment from jippie about using C++ standard width integer types
// #define TIMER_DATATYPE unsigned long
#define TIMER_DATATYPE uint32_t

//--- MarkU: diagnostic LED to indicate that timer overflow happened.
// Comment out this line for normal operation.
#define DIAGNOSTIC_LED_TIME_OVERFLOW 9
//---

//--- MarkU: diagnostic: force timer overflow to happen sooner.
// This must be significantly longer than the intervals being measured.
// Must be a binary all-1's bitmask.
// 0x3FFFFFF overflow after approximately 1 minute
// 0xFFFFFFF overflow after approximately 5 minutes
// 0xFFFFFFFF overflow after approximately 70 minutes
#define DIAGNOSTIC_TIMER_OVERFLOW_MASK 0x3FFFFFF
//---

int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
TIMER_DATATYPE prevMicros = 0;        // will store last time LED was updated  +
TIMER_DATATYPE interval =  7000000;           // lunghezza della pausa in secondi
TIMER_DATATYPE intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);

  //--- MarkU: diagnostic LED indicate that timer overflow happened
#if DIAGNOSTIC_LED_TIME_OVERFLOW
  pinMode(DIAGNOSTIC_LED_TIME_OVERFLOW, OUTPUT);
  digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, LOW);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
  //---

  prevMicros = micros();
}

void loop() {
  TIMER_DATATYPE currMicros = micros();

  //--- MarkU: diagnostic: force timer overflow to happen sooner
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
  currMicros = (TIMER_DATATYPE)(currMicros & ((TIMER_DATATYPE)DIAGNOSTIC_TIMER_OVERFLOW_MASK));
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK

  //--- MarkU: consolidate time delta calculation
  TIMER_DATATYPE timeSinceLastChange;
  if (currMicros < prevMicros) {
    //--- MarkU: handle timer overflow
#if DIAGNOSTIC_LED_TIME_OVERFLOW
    digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, HIGH);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & DIAGNOSTIC_TIMER_OVERFLOW_MASK;
#else // DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & 0xFFFFFFFF;
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK
  } else {
    timeSinceLastChange = currMicros - prevMicros;
  }
  //---

  // manage overflow? BOH
  if (ledState == HIGH && (timeSinceLastChange >= intervalON)) {
    prevMicros = currMicros;
    ledState = LOW;
  }
  else if (ledState == LOW && (timeSinceLastChange >= interval)) {
    ledState = HIGH;//riparte
    prevMicros = currMicros;
  }

  digitalWrite(led, ledState);
  digitalWrite(fan, ledState);
}

I'm sorry it's still not working, I updated the code above

I'm testing your edited code. Anyway, I'm beginning to suspect the problem isn't overflow, since it's not re-starting ever. Your code is working as expected though, switching the DIAGNOSTIC_LED_TIME_OVERFLOW to ON after specified time. Let's wait to see if it hangs again... Thank you for your time!

nothing to do, it blocked after 2 hours, this time with ledState set to HIGH permanently. I don't think it's a circuit problem , but should I try  removing the load on fan?

Yes, I tested the above code driving an LED, not a fan. Perhaps the real problem is some kind of power disruption when turning the fan on or off -- maybe it's acting like an inductive load? Relays and motors are a bit tricky to drive. What circuit are you using to drive the fan, or is the fan just directly connected to an Arduino digital pin? And what kind of fan is it exactly (make/model number)?

the fan is a small 3V motor absorbing up to 0,5A. I'm driving it using a 2N3904 connected to Vin and a potentiometer 0-9k ohm from digital pin to transistor's base. Input voltage to Arduino Micro is 5V regulated

the motor is similar to pkz3916, with a small propeller on it


text:
IDE to program Arduino Uno especially internal interrupt vectors
I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?
What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.
Suggestions?

You can do all you need to do in the Arduino IDE.  It doesn't "block" you from doing any low-level operations.  Any other IDE will also allow you to do what you want.
All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.
http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf

Ah yes. For some reason I thought my chip was an Atmega16U2, which doesn't have interrupt vector names for its interrupts in its documentation. The documentation for the 328P actually has everything. Thank you for making me realize my mistake.


text:
Where is documentation on Arduino's Internal Interrupts?
First time arduino programmer here...however I have programmed the TI MSP430 in the past...
I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.
In the Arduino IDE, I am skeptical about writing lines of code like
ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

Because it doesn't appear to matter what I type inside ISR(), for instance I can write
    ISR(GibERisH) {
    }
And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1_CAPT_vect is without having the library?
I found a list of interrupt vector names here: http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html
But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.
Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.

The vector names are all defined within the header files for the main chip in the compiler.  The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.
Look for the files "lib/avr/include/avr/io*.h within the compiler in your chosen IDE.  In there are all the chips and all their definitions.
For instance, the ATMega328P definition (iom328p.h) has this list:
#define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
#define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
#define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
#define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
#define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
#define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
#define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
#define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
#define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
#define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
#define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
#define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
#define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
#define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
#define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
#define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
#define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
#define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
#define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
#define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
#define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
#define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
#define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
#define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
#define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

Further, _ISR() is just a macro.  It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.
#  define ISR(vector, ...)            \
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)

That is defined in "avr/interrupt.h" in the compiler's include files.  With your gibberish you'd end up with:
extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
void GibERisH (void) {
    // something here
}

With a real vector you'd get the more meaningful:
extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
void _VECTOR(7) (void) {
    // something here
}

Of course, _VECTOR() itself is a macro:
lib/avr/include/avr/sfr_defs.h:#define _VECTOR(N) __vector_ ## N
So that further expands out to:
extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
void __vector_7 (void) {
    // something here
}

And magically, that new function name of __vector_7 is directly referenced from the standard vector handling code in the startup library crt of the AVR compiler.

Thank Majenko. Also the documentation actually does have the names of the interrupts, but looking at the header makes it crystal clear. Thanks for answering.

ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

Rule #1. Don't do serial prints inside an ISR. Doing that will likely hang the sketch.

Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }

Yes you can do that. It just degrades into some function that is never called. The way it is organized with all the defines, any non-valid ISR name effectively creates a non-ISR function, which is therefore ignored. Even getting the capitalization wrong can cause this.

I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

There is a considerable amount of detail on my site: http://www.gammon.com.au/interrupts


text:
Did I accidentally short something? My Arduino UNO board does not communicate with the computer anymore
I had my sketch uplaoded and everything was working fine when I tried connecting one of the input pins(pre-configured as digital INPUT) to 12V, just to see if this was being read as a HIGH as well.
It seems to have done something and the board stopped working. Moreover, all pins seem to be stuck at HIGH!
So far Ive tried the following:

reset button: doesnt help
re-upload: doesn't work - it says not in sync

Physically nothing seems to be burnt/blown. What am I missing? Have I fried my board? I hope not. PS: It was connected to a 12V external power source
Any thoughts?

If you have an Uno with the ATMega328 in a socket, you could just replace the chip with a new one (with bootloader pre-programmed). If it's the SMD version, you're out of luck (unless you have a friend that does SMD soldering).

@Gerben :That seems like a good option, do you know where I can get a bootloader programmed ATMega328?

@Gerben : Do you know where I can get a bootloader programmed ATMega 328? I think i can replace it, luckily my board came with an IC socket.

I don't know where you live. But try stores that also sell regular arduino's. E.g. Sparkfun sells them.

@Gerben Thanks Gerben. I found some for a good price on Amazon.   Thank God for Amazon! :-)

Unfortunately, the arduino's input pins are not tolerant of 12 volts, You have likely caused permanent damage to the chip =(. There is a regulator that makes it capable of being powered by 12 volts, but the input pins are different.
If you look at table 30-1 on the datasheet for the Uno's controller here you can see the input characteristics. The arduino is powered at 5v, so the max digital input voltage is 5.5v

Thats good to know. I assumed they could take anything up to 20V!(as rather silly assumption. Looks like I will have to use a voltage divider to sample the input voltage and get it under 5V for my use. Thanks Brett!


text:
Why Arduino Severino (S3V3) sometimes needs reseting when uploading a sketch?
I have an original Arduino UNO R3 that I bought and an Arduino Severino (S3V3) that I've built.
I have no problems uploading sketches to the UNO, but sometimes, when uploading to the Severino board, I have to hard reset it at a specific time during the upload process, when the IDE says something like this below:
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]

If I don't reset it when one of the Send messages are being displayed, I get the not in sync message, as below:
avrdude: Recv:
avrdude: stk500_getsync(): not in sync: resp=0x00

Other times, if I'm lucky, I can upload to the Severino board without having to reset it.
So, my questions are:

Why does that happen? Why Severino needs a hard reset during upload?
Why is the problem intermitent? Why does it happen sometimes and others it doesn't?
How can I fix that problem? Is there a simple change to the Severino design that would fix that?

Why does that happen?
When the serial port is opened by either monitor, avrdude or other it toggles the DTR pin of the serial port. Which in turn is AC coupled through C4 100nF. This toggling is converted to a up and down pulse on the ATmega(CPU)'s RESET pin. The subsequent reset starts initially with the boot loader, which typically in turn waits for a avrdude's semiphore (e.i. Send: 0 [30]   [20] ) and if seen then responds in turn and if not seen after a timeout period (typically 5s) it continues on with the application in flash space.
You behavior is describing either; not hearing the response. Or the reset is not getting triggered. Since it does work some times I suspect its prior, but the later.
Why Severino needs a hard reset during upload?
This statement further supports the later.
Why is the problem intermitent?
the pulse is almost long and strong enough, where the DTR toggle is in code and likely has some significant inconsistency.
How can I fix that problem?
Yes, change the value of C4 100nF and or R11 10K, to better pass the toggle. I could derive some EE explanation of what value to pick. But I would suggest some trial and error.
It should also have 5V clamping, as the RS232 levels can reach +/-12V (typically +/-9V) where the AC coupling prevents the DC and burn out. but the AC will stress it.

Is there a way to confirm what the problem is with a scope? maybe setting it to a single run during an upload? If so, what signals should I watch?

start with scoping the reset pin into the ATmega, and make sure it is below the minimum voltage for longer then the minimum specified time, as per the data sheet.


text:
Arduino Nano - programmer is not responding
I cannot seem to upload the simple blink program to my Arduino Nano. I keep getting the message:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

What I have tried already with a lot of suggestions on Google. I have tried it on both a Windows 7 & 8 machine and with 2 different Nano's:

Set my Board to Arduino Nano
Set my Processor to ATmega168
Set my port to COM1
On windows 8 turned off driver signature
Installed the FTDI Driver
Checked my drivers in control panel

USB controllers says USB Serial Converter
USB Serial port says USB Serial Port (COM1)

Rebooted a Lot!

When I plugin the nano to the USB it starts blinking the L led 180 times a minute. When I start uploading, L blinks at about 80-100 times a minute, blinks the rx and then start blinking the L led fast again.

For me the problem was the selected "processor" type.
I had to change it to 328p (old bootloader).
Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.
My specs:

OS: Linux Mint 18.3
Linux kernel: 4.13.0-37-generic
Arduino IDE: v1.8.5
board: the cheap and common Nano Chinese clone
USB to serial chip: CH340

If it's a new nano is probably the new version which has the 328 processor. Try switching to that.
Also does your computer make the windows "I just plugged something in" sound when you connect? Is the driver recognized?
Try this instead:
Set Board to Arduino Nano
Set Processor to ATmega328
Set port to COM2 or any other device if recognized. Test to see if the Com1 stays if you unplug it. Try other usb ports as well.


text:
Programmer only uploading with its own power source
Can anyone explain to me why the following occurs (See image below)?
When I connect the pins according to situation 1, everything works fine and I am able to upload my project. However when I connect the pins according to situation 2 it gives me the following error:

wrong direction/command: 0x00 0x08, expected 0x01 0x08 esp8266

Both supply the same constant 3.3V and after the project is uploaded it runs with the pins connected as in both scenarios.
(All the other factors are constant in both scenarios. Think of pulling down IO0 etc.)

This will not work for the same reason you can not measure the voltage of a battery by only connecting the measurement device to the positive battery terminal. You always need a ground reference.
Perhaps you were thinking all grounds, no matter where they come from, are the same. This is only true if all your power supplies are grounded. But this is usually not the case. In fact it can be dangerous and can lead to other problems such a ground loops.
So, connect your grounds together and try your circuit again.

You must always connect the grounds. Without the grounds connected, even when using a separate power supply, there can be no circuit. With no circuit, no electrons can flow.
I cover it in detail in this blog post.

Very nice blog post, made me understand it quite good!

There's no problem with supplying a separate power supply to the ESP8266 but you always need to connect the grounds between the "programmer" and the ESP8266.

Can you also explain why? (Why is the ground of the separate supply not good enough for the esp8266)


text:
Distorted audio from mcp3002
I have setup a MCP3002 to convert an analog signal to digital signal. When I read it directly through serial and convert it to a wav file, it sounds relative clear. Serial is limited for samples per second though, I can get about 7000 sps.
When I send the signal directly to a server I can reach around 17.500 sps. however when I convert this to a wav file, it also sounds relative clear, but with a slight distortion/'robot voice' through the audio.
Is there a simple way to prevent this, or why is this happening?
The code how I read the SPI is in this question:
Reading data from MCP3002

Without any code we cannot do much. Having a robot voice sounds like a sampling frequency issue. How do you set a sampling frequency and how did you measure the sample frequency?

Does your ADC reach saturation? You can check whether you have samples with values 0 or 1023. Are you sure your sampling rate is strictly constant? Unless your SPI is clocked from a timer it probably isn't.

@chrisl the code for reading mcp is added in the link (from another question, where you have also helped me =) )

@EdgarBonet I added the code how I read the code, the ADC is between 100 - 200 so no saturation. My SPI is set at a constant frequency if that is what you mean?

And how are you sending the signal directly to a server? That is not in the code of your previous question. That can be very important, since it may screw up your timing, thus producing an unstable measurement frequency.

I can add this tonight, it is a 'windowed' buffer which are send through UDP. Good thing to look at this indeed!

From the code you linked to, it appears the SPI port is completely
controlled by the software:
void loop() {
    ...
    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);
    ...
}

This means that the timing of the SPI transaction (when exactly it
starts) and, by extension, the timing of the ADC conversion, is
dependent on the timing of your code execution. You have no good control
on that timing. It depends on what other things may be in your loop, and
on the other interrupt sources (timers, network...).
The least you can do is set up a timer interrupt, and run the SPI from
the interrupt handler. Your timings should then be more consistent. You
will still have some jitter due to the interrupt handler being delayed
by some critical sections, including other interrupts. But it may be
good enough for your application.
For best results, you would ideally want the timing to be completely
controlled by hardware. Maybe there is a way to trigger the SPI port
from a timer. This depends on the specific MCU you are using: you will
have to dig into the datasheet.

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


text:
"missing filename" compilation Error
I've recently got back to my Uno. I tried compiling my program and got the following error:
Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"

avr-g++: error: missing filename after '-o'

exit status 1
Error compiling.

This happens on any of the programs I've tried to compile/upload.
I've searched around on Google but I have gotten no definite answers and how to fix this or what has caused this? Does anyone have an idea on what I could do?

I had same problem. You should download Arduino IDE 1.6.8
https://www.arduino.cc/en/Main/Software


text:
Arduino Uno not appearing under ports
I have an Arduino Uno attached to my MacBook Air running the Arduino IDE 1.6.4.
The Arduino was visible in the Serial port section this morning, but then it just disappeared. The ON light on the Arduino still comes on, but I cannot connect to it through the port section. I attached the Uno to another computer and it did not appear there either. However, when a different Arduino is connected to my computer it does show up. I also tried using a different IDE version, and it did not appear there either.
All of the other topics I found regarding this were saying it is the OS's fault, but since I was able to see the other Arduino, I am pretty sure it is not. I updated the FTDI drivers, and I tried using a powered hub and it is still not there.
UPDATE:
When I took the chip out of the UNO that is not appearing and put it into a working UNO, I was able to see it, is it possible that the Serial port is just not working, and if so how would I fix that
Any help would be appreciated.

Have you consider that your arduino is may be burned.

Is anything plugged in to the arduino? does its power light come on? Can you tell if its running the last program you uploaded still?

This doesn't seem to be the case since it works on another computer...

Step one: from a terminal, run sudo dmesg and note the last line.  Step two, plug in the Arduino.  Step three: run sudo dmesg again and find the same last line.  Step four: post what comes after that line into your question.

@BrettAM There were things pluged into the arduino but I took them off and the arduino still did not show up, the power light is on, and I am not sure is the last program running because all it did was print to the serial monitor.

@Akkilah I do not think so, as the power light still comes on

@Majenko On both times the last line remained the same, it is 'Google Chrome He (map: 0xffffff80145feb40) triggered DYLD shared region unnest for map: 0xffffff80145feb40, region 0x7fff97c00000->0x7fff97e00000. While not abnormal for debuggers, this increases system memory footprint until the target exits.'

Are you plugging it directly into the mac or into a hub? If it's a hub, is it a powered hub?

@Majenko I am plugging it directly into my mac

I have an UNO where I have to hold the cable at the right angle for it to register.  The fault is with the USB socket on the UNO.  Try applying pressure to the plug from different angles.

@Majenko No that did not work, I do not think it is the cables fault, as the same cable works fine with another uno

As I said, the fault with mine is the socket, not the cable - the contacts inside the socket don't make good contact with the plug.

@Majenko The same socket also works fine with another arduino using the same cable

That makes no sense - I am talking about the socket on the Arduino itself - how can you swap that to another Arduino?!

@Majenko Sorry I was quick reading, I tried holding the cable at different angles to the uno's socket but it is still not appering up on the computer

@Akkilah Is there a way to check

@user10529: if you got anther PC go and try on it

@AnnonomusPenguin: at first i though i didn't read his post correctly , but after reading it again , there was no mention of him trying the problematic UNO in a different PC

@Akkilah I tried it on another computer on another computer and it still did not show up

@user10529 : if it for my i would count it as fired, but you can  check this link if you really wanna make sure its burned  http://goo.gl/gtHtgR

@Akkilah The green led on mine does come on. The led on pin 13 does not come on because I have changed the sketch

@Akkilah Is there anything I can do if it is fried

@user10529 : Im wondering if your older sketch ( the last  one u uploaded to the bored) still working ?

@Akkilah Unfortunately all that sketch did was print something to the Serial Monitor(it was a I2Cscanner)

@user10529: you can check the answer given in this link http://goo.gl/BDJJwZ as im actually run out of idea

@Akkilah Is there a way to check what part of it is fired

@user10529 : have you tried to re-upload bootloader to ur UNO

@Akkilah No i looked into it but you need to get special equipment

@user10529 : just use on of ur working arduino as AVRISP Programmer, u can check this link http://www.arduino.cc/en/Tutorial/ArduinoISP

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.

If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.
If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.
If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.
If *nix, make sure you've configured it properly.

When an Arduino stops appearing, it is usually because it's fried. Especially if other machines appear when connected, and the faulty machine appears on no other machine.
Try burning the bootloader.

I do not the bootloader is broken as when I took the chip out of the board and put in into another board that board was able to be seen


text:
MPU6050 causing arduino not to run sketch
I have a mpu6050(which I got from here http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html) and I have connected it to special ports on a sensor shield made for the mpu6050(http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem.
This is my code
#include <Wire.h>
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <I2Cdev.h>
#include <MPU6050.h>

MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;

#define Gry_offset 0
#define Gyr_Gain 0.00763358
#define Angle_offset 4
#define RMotor_offset 20
#define LMotor_offset 20
#define pi 3.14159

long data;
int x, y;
float kp, ki, kd;
float r_angle, omega;
float f_angle;
float Turn_Speed = 0, Turn_Speed_K = 0;
float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
float LOutput,ROutput;

unsigned long preTime = 0;
float SampleTime = 0.08;
unsigned long lastTime;
float Input, Output;
float errSum, dErr, error, lastErr;
int timeChange;

int TN1=3;
int TN2=4;
int ENA=9;

int TN3=5;
int TN4=6;
int ENB=10;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  pinMode(TN1,OUTPUT);
  pinMode(TN2,OUTPUT);
  pinMode(TN3,OUTPUT);
  pinMode(TN4,OUTPUT);
  pinMode(ENA,OUTPUT);
  pinMode(ENB,OUTPUT);

  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
  Serial.print("Hello");
}

void loop() {
  Recive();
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
  omega =  Gyr_Gain * (gx +  Gry_offset);
  //Serial.print("  omega="); Serial.print(omega);
  if (abs(r_angle)<45){
    myPID();
    PWMControl();
  }
  else{
    analogWrite(ENA, 0);
    analogWrite(ENB, 0);
  }
}

void Recive(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();

    y = data >> 16;
    x = data & 0x0000ffff;
    //Serial.print("  x="); Serial.print(x);
    //Serial.print("  y="); Serial.println(y);
    if(x >= 520){
      Run_Speed_K = map(x, 520, 1023, 0, 100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else if(x <= 480){
      Run_Speed_K = map(x, 480, 0, 0, -100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else{
      Run_Speed_K = 0;
    }
    if(y >= 520){
      Turn_Speed = map(y, 520, 1023, 0, 20);
    }
    else if(y <= 480){
      Turn_Speed = map(y,480,0,0,-20);
    }
    else{
      Turn_Speed = 0;
    }
  }
  else{
    x = y = 500;
  }
}

void myPID(){
  kp = analogRead(A0)*0.1;
  //kp=17;
  Serial.print("  kp=");Serial.print(kp);
  kd = analogRead(A2)*1.0;
  //kd=840;
  Serial.print("  kd=");Serial.print(kd);
  //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

  //kp = 0;  Serial.print("  kp=");Serial.print(kp);
  //kd = 0;  Serial.print("  kd=");Serial.print(kd);
  ki = 0.08;
  Serial.print("  ki=");Serial.print(ki);

  unsigned long now = millis();
  float dt = (now - preTime) / 1000.0;
  preTime = now;
  float K = 0.8;
  float A = K / (K + dt);
  f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;

  Serial.print("  f_angle=");Serial.print(f_angle);

  timeChange = (now - lastTime);
  if(timeChange >= SampleTime){
    Input = f_angle;
    error = Input;
    errSum += error * timeChange;
    dErr = (error - lastErr) / timeChange;
    Output = kp * error + ki * errSum + kd * dErr;
    LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
    ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
    lastErr = error;
    lastTime = now;
  }
}

void PWMControl(){
  if(LOutput > 0){
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, LOW);
  }
  else if(LOutput < 0){
    digitalWrite(TN1, LOW);
    digitalWrite(TN2, HIGH);
  }
  else{
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, HIGH);
  }
  if(ROutput > 0){
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, LOW);
  }
  else if(ROutput < 0){
    digitalWrite(TN3, LOW);
    digitalWrite(TN4, HIGH);
  }
  else{
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, HIGH);
  }
    analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
    analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
}

and this is a picture of the mpu6050 on the sensor shield

Please post your code and, if not included in the above links, the schematic.


text:
nRF24L01 module using Mirf library was working and then stopped

I have two nRF24L01 modules, they are both attached to a sensor shield that has special ports for this type of module, on Arduino Unos.

I have this code on the Arduino that is sending the signal:
#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <SPI.h>
#include <Wire.h>

//0 = stop, 1 = left, 2 = right, 3 = forward, 4 = backwards
long command;
long last_command;

long Joystick_1_X;
long Joystick_1_Y;
long Joystick_1;

void setup() {
  // put your setup code here, to run once:
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setTADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
}

void loop() {
  Joystick_1_X = analogRead(A0);
  Joystick_1_Y = analogRead(A1);

  if(Joystick_1_X < 450){
     command = 1;
  }else if(Joystick_1_X > 600){
    command = 2;
  }else if(Joystick_1_Y > 600){
    command = 3;
  }else if(Joystick_1_Y < 400){
    command = 4;
  }else{
    command = 0;
  }
  if(command == last_command){
  }else{
    Mirf.send((byte *)&command);
    last_command = command;
   }
  }

and this code on the Arduino that is receiving
#include "SPI.h"
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"

int TN1= 3;
int TN2 = 4;
int ENA = 9;

int TN4 = 5;
int TN3 = 6;
int ENB = 10;

long data;

void setup() {
 pinMode(TN1, OUTPUT);
 pinMode(TN2, OUTPUT);
 pinMode(TN3, OUTPUT);
 pinMode(TN4, OUTPUT);
 pinMode(ENA, OUTPUT);
 pinMode(ENB, OUTPUT);

 Mirf.spi = &MirfHardwareSpi;
 Mirf.init();
 Mirf.setRADDR((byte *)"serv1");
 Mirf.payload = sizeof(long);
 Mirf.config();
 Serial.begin(115200);
 Serial.print("begin");

}

void loop() {

  // put your main code here, to run repeatedly:
  receiveCommand();
  if(data == 1){
    left();
  }else if(data == 2){
    right();
  }else if(data == 3){
    forward();
  }else if(data == 4){
    backwards();
  }else if(data == 0){
    stop_rover();
  }
}

void receiveCommand(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
    Serial.print(data);
  }else{
    Serial.println("No data to be recieved");
  }
}

void forward(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, HIGH);
  digitalWrite(TN2, LOW);
}

void backwards(){
  digitalWrite(ENB, HIGH);
  digitalWrite(ENA, HIGH);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, HIGH);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, HIGH);
}

void left(){
   digitalWrite(ENA, HIGH);
   digitalWrite(TN1, HIGH);
   digitalWrite(TN2, LOW);
}

void right(){
  digitalWrite(ENB, HIGH);
  digitalWrite(TN4, HIGH);
  digitalWrite(TN3, LOW);
}

void stop_rover(){
  digitalWrite(ENB, LOW);
  digitalWrite(ENA, LOW);
  digitalWrite(TN4, LOW);
  digitalWrite(TN3, LOW);
  digitalWrite(TN1, LOW);
  digitalWrite(TN2, LOW);
}

This was working, and the rover did spin its wheels when the remote broadcasted a signal, but then it just stopped. The sensor shield says that they are plugged into the 3V port, I tried using the RF24 library and that did not work either.
Any help would be greatly appreciated.

Could you please try the builtin self test checks that come with RF24 library maintained by TMRh20? Do they all work properly?

I uploaded the GettingStarted.ino file to two Arduinos the trasmitting node printed out this Now sending
Sent 18204112, Got response 0, Round-trip delay 18204112 microseconds
Now sending
Sent 28434792, Got response 0, Round-trip delay 28434792 microseconds
and the receiving node printed out this Sent response 251854848
Sent response 0

Something is wrong. Check your wiring and if you can, solder electrolytic caps to the GND and 3.3V pins of the radio module.

There is no wiring the nRF24L01 is plugged into a sensor which is on the arduino, I put a picture of the sensor shield with the nRF24L01 above.

Are the defined pins in the sketch right? Could you please solder a cap to the power pins of the radio module?

I tried changing the defined pins to something else but I keep getting Now sending
failed
Sent 3496020, Got response 0, Round-trip delay 3496020 microseconds. And i do not have any caps

What does the other node say? Also, please go buy some capacitors and solder them on, it can solve your problem.

I soldered on capacitors, but I am still getting Sent 28434792, Got response 0,

What does the second node say? Have you checked if your CS and CE pins are defined correctly?

The receiving node is writing Sent response 1795, Sent response 0, Sent response 259, Sent response 0 and when I swaped around the defined CS and CE pins the node wrote Now sending
failed
Failed, response timed out.

Try the example named Transfer. The round trip delay and sent responses are weird although the pins are right and you have soldered capacitors on the NRF24L01+ modules. Weird.

I do not think that that worked, the receiving node wrote this Rate: 365.92
Payload Count: 11435
Rate: 16.54
Payload Count: 517
Rate: 0.00
Payload Count: 0
Rate: 0.00
Payload Count: 0
Rate: 0.00
Payload Count: 0
Rate: 0.00 and the transfering node wrote this Initiating Basic Data Transfer
Transfer complete at 219.18 KB/s
0 of 10000 Packets Failed to Send
Initiating Basic Data Transfer
Transfer complete at 219.18 KB/s
0 of 10000 Packets Failed to Send

Also they both wrote at the start this also at the start they both said this STATUS   = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1  = 0x0000000000 0x0000000000
RX_ADDR_P2-5  = 0x00 0x00 0x00 0x00
TX_ADDR   = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR  = 0x00
RF_CH   = 0x00
RF_SETUP  = 0x00
CONFIG   = 0x00
DYNPD/FEATURE  = 0x00 0x00
Data Rate  = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power  = PA_MIN

If it is true that you have defined the CS and CE pins right, your nrf24l01+ modules are broken.

Using the MIRF Library that I got from here, and then using this code to send
 Mirf.send((byte *)&command);
    while(Mirf.isSending()){
        }

and this code to receive
 if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
else(){
}

I was able to get it to work