text:
SIM800L change default baud rate
I am using an ATmega328P with internal clock (8 MHz) with a SIM800L module. The default baud rate of the SIM800L is 115,200 baud and I can't make them talk to each other correctly. Although I was able to make them talk very easily at a baud rate of 9600 baud. But now, with a new SIM800L I can't.
Question:
How to change the default baud rate of a SIM800L?
Is it possible to run an ATmega328P at a baud rate of 115,200 baud?
Thanks in advance!
EDIT:
I know that I can run atmega328p at baud rate of 115200 with different crystal, but is it possible to it using internal crystal.

Default baud rate of SIM800L is 0 (auto-bauding). Maybe you have saved it before.

Well I do not think that the default baud rate is 115200. The default setting is autobaud which does not support 115200 baudrate. From the datasheet.

You can change it with the already mentioned AT+IPR command. From the AT manual you can also check that the default setting is autobaud, and also the selectable baud rates.

Note:  User  can  use  AT  command  “AT+IPR=x”  to  set  a  fixed  baud  rate  and  the  setting  will  be  saved  to  non-volatile  flash  memory  automatically.

If you use 57600 you will probably alright and you do not even have to change the baud rate settings as this value is supported.

You have mentioned an important rule about auto-bauding (Auto-bauding limited rates). Thanks man

As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.
You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(115200);      // Set your buad rate
}

And you can also do without this library.
void setup()
{
  Serial.begin(115200);        // Set your baud rate
}

Sorry but not true, you can change the SIM800's baud rate with the appropriate AT command, AT+IPR (as already mentioned in an other answer).

@BenceKaulics Thank you for this information.

According to Adafruit's pdf specsheet SIM800+Series_Serial+Port_Application+Note_V1.01.pdf, the SIM800 is set up to auto-baud when it starts out:

SIM800 series is designed in autobauding mode by default. Autobauding allows SIM800 series to automatically detect the baud rate of the host device. In application, host device must to synchronize the baud rate with SIM800 series. Host device must firstly send characters "AT" or "at" to synchronize the baud rate. It is recommended to send "AT" until host device receives the "OK" response, which means host device and SIM800 series are correctly synchronized. Once the baud rate is synchronized, it is suggested to use AT command "AT+IPR" to set SIM800 series baud rate according the host baud rate. ...

So, you might arrange your software to keep trying at 9600 bps.  If you get an ok connection at that rate, you can either keep using it or shift to a higher frequency via "AT+IPR".  [I haven't read the spec sheet enough to know whether that default autobauding is always on, or might be turned off somehow.]
As serial-data bps goes up, required clock accuracy becomes tighter.  Where a couple of percent error may be ok at 9600 bps, under a percent probably is needed at 115200 bps.
On several boards I've measured RC oscillator frequency errors of about 2%, which according to question How critical are UART frequencies? might or might not be good enough to allow high-speed serial communications.
If you can measure your ATmega328P's RC oscillator frequency, you can then apply a correction factor at startup.  In the spec sheet (eg Atmel-8271J-AVR-ATmega-Datasheet_11/2015), see §9.12.1, OSCCAL – Oscillator Calibration Register.
Your program can start out with the RC oscillator using the factory-set value, and then can load your own calibration value into the Oscillator Calibration Register to shift RC frequency as needed to make the board work ok for 115200 bps serial data.  Or, you can overwrite (in EEPROM fuse or signature area) the factory-set value with your own number.
Figure 32-37, ATmega48PA: Calibrated 8MHz RC Oscillator Frequency vs. OSCCAL Value, shows typical frequencies for various Oscillator Calibration Register values.  It is possible to tune clock frequency close enough that serial communications should work ok.
High-range byte values 144 through 160 typically move frequency from around 7.4 MHz to 8 MHz (at 85℃).  In this range, each count shifts clock frequency by about 0.5%.  See the figure for details.  For example, if value 158 gives an RC frequency of about 7820 KHz, then value 159 might raise the RC frequency to about 7860 KHz.
Low-range entries 96 through 112 move frequency from around 7.5 MHz to 8.5 MHz.  This overlap makes it necessary to try both low-range and high-range values when looking for the best Calibration Register value.
Note, there are inexpensive cymometers (frequency counters) on ebay, which can measure oscillator frequencies accurately enough to enable the calibration suggested above.

You can change the baud rate to 9600 on the SIM800L with the command:
AT+IPR=9600

Then to save this (to last between boot cycles), give the command:
AT&W

To see the saved settings, give the following command:
AT&V

From what I have read so far, the problem is that there is no good divisor from an 8 MHz oscillator to get a within-spec baud rate above 57,600. Using the internal oscillator is also susceptible to variation with temperature, so that appears to be bad solution as well in many applications. The problem being that it may work on one MPU, but not with the next one.
As far as I can tell, the best solution is to use a 7.372800 MHz oscillator. This results in the processor running a bit slower, but it also results in the baud rate divisors being spot-on for almost all the standard and popular baud rates, meaning you should be able to run to at least 921,000 baud.
If anyone has a better solution, I would love to hear it, as I am dealing with a similar issue in something I intend to take into production that will be in a variety of environments.


text:
How many pins does this circuit (HMC5883L) use?
I've been told 2 by a friend but this looks to only use one?
https://www.adafruit.com/product/1746

Two (SDA and SCL) and no additional pins when connecting other I2C (TWI) devices.

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.
GND of magnetometer ----> Arduino GND
Vcc of magnetometer ----> Arduino 3.3 Volt
SDA of magnetometer ----> Arduino Analog Pin 4
SCL of magnetometer ----> Arduino Analog Pin 5
A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.
I hope it will help you.

It is I2C so 2 pins.
Optionally it can use a third pin to indicate data ready.

It depends what you think of as a pin.
You have VIn and Gnd, SCL and SDA are the 4 main pins you will need to connect.  The 3.3V and RDY pin don't seem to be connected in any of the pics I can see.
So the answer is 2 pins plus 2 power.
Oh from the page on how to use it, https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/wiring-and-test:
"This 3-axis magnetometer breakout is thankfully very easy to use. It only requires 2 power pins and 2 data pins."
Interestingly it doesn't appear to use pull up resistors, which most I2C device require, so the might be built into the board.

Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be A4 & A5 pins of Arduino.
And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.

source: Stack Exchange

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

sort: votes


text:
Arduino Standalone construction
In tutorial - https://www.arduino.cc/en/Main/Standalone , they have used voltage regulator. Can we able to do without Voltage regulator ?(to compact the circuit), If so what should the voltage & current value in Atmega328?

That's actually quite an involved question to answer. The short answer is "Yes, you can do without the regulator as long as you get the voltage right".
And that is where it gets tricky.
The datasheet states:

Operating Voltage:

1.8 - 5.5V

So you can power it from two or three AA batteries, for instance (3V - 4.5V). However, that is not the whole story.
The voltage you provide it with dictates what frequency the chip can reliably run at. Later in the datasheet is this nice little graph:

Since the normal Uno-like arrangement runs at 16MHz you're looking at a minimum voltage of around 3.8V - 4V (it's actually quite hard to work out from that graph).
But if you are willing to reduce your clock speed to 8MHz (which is what the 3.3V Arduino "Pro" boards run at) then you can drop right down to about 2.5V.
At a 2.5V lower limit with 3 AA batteries it would equate to a minimum voltage of 0.83V per cell, which is below the normal minimum accepted "flat" voltage of 0.9V per cell.
So powering from 3 AA batteries with a clock speed of no more than 8MHz would give you probably the best run-time.  Note, also, that a decrease in clock frequency decreases the current consumption as well - the slower you run the chip the less current it needs. You can see that in this graph in the datasheet:

And yes, as you can see, the lower the supply voltage the lower the current as well. So as the batteries run down and the voltage drops so does the current, reducing the speed at which the batteries will run down.
As you can see, if you don't mind the supply voltage changing (which of course will affect everything else in the circuit, so you need to check those out first), running directly from batteries without a regulator can actually have advantages. But as I say, you need to check what else you are running in the circuit to make sure it doesn't mind if the power supply voltage drifts.
And don't forget, also, that the supply voltage affects the ADC readings, since they are referenced to that voltage as well.

so yu are recommending not to use ? @Majenko

voltage is b/w 1.8 to 5.5v, what about current?

My understanding is that the frequency-voltage graph is made of two linear parts, below and above 10 MHz. Then, working out the required voltage from the operating frequency is easy: 2.4 V @ 8 MHz and 3.78 V @ 16 MHz.

@EdgarBonet No, it's just one (roughly) linear guide (not precise numbers, just a guide). The 10MHz is just shown as an example.

@sankar As I say - it can be good to not use a regulator, but check the rest of your components to make sure they are happy.  The current depends on the voltage and the frequency as I showed with the second graph. It also depends on the rest of the components in your circuit. There is no answer "It is X milliamps".

so can i give 5v-1Amp ? 'm connecting a ADXL335 sensor & one serial device

No, it's not just a rough guide, these are actual specs. Quoting the datasheet: “the Maximum Frequency vs. Vcc curve is linear between 1.8V < Vcc < 2.7V and between 2.7V < Vcc < 4.5V.”

If the 5V supply is regulated internally (say a USB power adaptor) then that would be perfect and a regulator is not needed (the power supply already has one). It would be exactly the same as running with a 9v battery and a regulator.

@EdgarBonet Oh right, must have missed that bit.

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


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.

There is now as SafeString library available for Arduino, via the Library Manager (mine :-) )
SafeStrings are GOOD for Arduino
They are only ever placed in Static or Stack memory and so completely avoid heap fragementation and small transient object construction and unnecessary data coping, NEVER causes your sketch to reboot and has extensive debugging and error messages.
SafeStrings are designed to be uses by Beginners and includes extensive error checking and detailed error messages to help you find the errors and correct your code.  SafeStrings also corrects a number of errors that are in the String code.
There is a detailed tutorial at
https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
and extensive examples include in the library, including parsing/tokenizing
In this case because SafeString implement almost all of String functionallity it is easy to replace EVIL Strings with GOOD SafeStrings
    #include "SafeString.h"
    createSafeString(dataString,60); // allocate global 60 byte safestring, just once,
//  for assembling the data to log
// You could also use createSafeString within the method if you want a local SafeString
    .. .. ..
    void setup() {
    Serial.begin(9600);
    // ....
    SafeString::setOutput(Serial); // enable sending debug/error msgs to Serial
    // So you will get a message if dataString runs out of space (but no reboots)
    // ....
    }

    // Data preparation for file saving:

    // Add time tag:
    dataString = Time0; dataString += ","; // or ',';

    // Append the MPU6050 data to the string:
    // no new strings created here!!!
    dataString += AcX; dataString += ",";
    dataString += AcY; dataString += ",";
    dataString += AcZ; dataString += ",";
    dataString += GyX; dataString += ",";
    dataString += GyY; dataString += ",";
    dataString += GyZ;

    // etc ....

    // SafeStrings are printable so can use println(dataString)
    // you can also print TO a SafeString so you could use, for example
    // dataString.print(AcX);
    // to access all the formatting print provides

Seems really Interesting! Thanks for sharing :)

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:
Is there some kind of timer function that returns the amount of time passed?
I'm doing a project and I want to get the amount of time between two sensor inputs.  i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable.  Is there a library or a specific function that exists?

It's simple enough to make a "helper" function to give you the number of milliseconds between each call of the function:
uint32_t millisSince() {
    static uint32_t lastMillis = millis();
    uint32_t now = millis();
    uint32_t diff = now - lastMillis;
    lastMillis = now;
    return diff;
}

Every time you call that it will return the amount of time that has passed since you last called it. The first time it will return 0 since it has never been called before.

Just adding a few notes to the perfectly valid answers you already got:
On your typical AVR-based Arduino, micros() has a resolution of
4 µs and millis() is updated every 1024 µs. This last point
implies that millis() increments most times by 1 ms, but
occasionally by 2 ms. Keep this in mind if time resolution is an
issue.
Both millis() and micros() return 32-bit unsigned numbers. This
implies that millis() overflows (it rolls-over to zero) roughly every
49.7 days and micros() every 71.6 min. This limits the
maximum interval length you can measure with each of those functions. It
does not limit the maximum run time of your program, since
subtracting two timestamps does work fine across a rollover
event.

Yes, you can use millis() or micros() which give the milliseconds resp microseconds since the board started up.
However by substracting two values taken close within time you can measure a time period (for example for your sensors).
With this functionality you can program the timer yourself.
See https://www.arduino.cc/en/Reference/HomePage and search for micros/millis.

Yes, read and store the value from millis() at the first event. Then read millis() again at the second event. Subtract the stored value and you'll have the time, in milliseconds, between the events. millis() returns a long unsigned int and your memory variables for storing its value need to be of the same type.


text:
Does sharing code on Arduino Create automatically grant any license rights?
I have code I am happy to share under a GNU GPL License and which is marked accordingly. Before I upload it to Arduino Create Web Editor I want to check whether in doing so I inadvertently grant additional license rights. I have searched for any terms and conditions which may inform me but not found any as yet.

Arduino Create doesn't assume any licensing of any form. Sharing isn't a public thing. You have to specifically provide someone with a link to your sketch. If you choose to post that link publicly then that is your concern.
Any licensing should be included with your sketch.

You should read the GPL License terms with respect to any rights you are concerned about, but in general, GPL licensed software is available to anyone to do anything with, as long as they keep it public and perpetuate the GPL License. Note: IANALawyer. If you wish to protect any specific rights, you should probably consult one.


text:
Arduino Mega and LP621024D70LL
I'm intending to try a LP621024D70LL (128 KB SRAM memory, 32 pins) on an Arduino Mega.
However, I now see there is no library for it ... I wonder how hard it is to access it? I can miss 32 digital pins (the Mega has enough), however, I'm a bit worried about having to write a library, especially since I do not have any gear like an oscilloscope.
Would it be easy to use the library of the more knwn 32K256 or 23LC1024 as basis? (where I also have no experience with btw).

That's so old I can't find a datasheet for it. If you know the pinout then you know more than me at the moment. Chances are it's a standard 8-bit CPU interface.

Writing:

Set the address on the address pins, set the data to write on the data pins, enable the chip, and pulse WR.

Reading:

Set the address on the address pins, enable the chip, and while pulsing the OE pin read the data pins.
And no, you can't really use a serial SRAM chip library as a basis - the operation is completely different.

http://www.allcomponents.ru/pdf/amicc/lp621024d70ll.pdf

Thanks ... well I have the datasheet: http://html.alldatasheet.com/html-pdf/55651/AMICC/LP621024D-70LL/133/1/LP621024D-70LL.html
Doesn't seem to complicated what you write :-) Going to give it a try ... and if I succeed I will make it public for everyone if interested.
Didn't know it as old, but I guess it doesn't matter.

Yep, it is as I described. It has two chip-enable pins, one has to be high and the other low to enable it (you can probably tie them both permanently enabled since you aren't sharing the bus) and just toggle the OE or WR pins.

No one much uses parallel SRAM chips any more. They are quite rare new.

Thanks for the extra explanation ... and I understand the 23LC1024 has less ins, but works more complicated (although with a library it isn't a problem). But besides it is a bit cheaper, the main reason is I'm just getting into electronics so 'back to the basics' is maybe not so bad after all.

This kind of chip is best used with a small MCU. Something like a 6502 or a Z80. Use it to build your own computer from discrete ICs ;)

(I also ordered a 23LC1024 so I can try both... 6502 sounds cool to (I remember it was the heart of the Commodore 64).

And many other systems too. 4 things are all you need: a 6502, some SRAM (you have), a parallel Flash chip, and some form of IO interface. Oh, and some way of getting code onto the flash chip. And there's your computer.

Let us continue this discussion in chat.


text:
Can Digital/Analogue pins double as power supplies?
I'm doing research into if the Arduino Uno has enough power pin slots to power multiple components, and I'm unsure if it's possible to convert some of the pins from the Digital and Analogue sections to be power/ground. Anyone know>

Only for very light loads (a few mA).
But why would you want to? The number of power pins doesn't dictate the number of devices you can power. Power pins can have as many things connected to one pin as you like. As long as you stay within the board's total power budget you are fine.

@user32033 This may help you understand more: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

Yes, for most modules that use modest power, it can be handy to treat modules as shields, in cases where pins can align. You just set each pin on the common 4-pin module connector as needed and plug them in.  I've done this several times with DHT22 modules, and it's fun "plug and play"ing on such a low-level.
With an UNO, you get a generous 40ma per output, though I would use a real power rail for anything over 100mw or so.
To make a pin act as VCC:
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

To make a pin act as ground:
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);

the other advantage to this is being able to switch the module on/off with digitalWrite() (from HIGH to LOW) to save power or reset flaky sensors.

But note that the output pins have a not-insignificant impedance of 25ohm, which means that the more you draw from them the lower the voltage will be.

the dht22 uses less than a ma. All but a couple of the "37 sensor" kit's modules would work with pin power; the relay+buzzers mainly. 25r limits 5v to 200ma, far more than the rated current...

"25r limits 5v to 200ma" No, it means that if you try to draw 200mA you will get 0V. Even just 40mA means a drop of 1V, which will put it out of spec for most 5V or 3.3V devices.

@IgnacioVazquez-Abrams: sure, but 40ma is far more than most sensors use, a 4v triggers UNO's inputs...

Right, but is far less than, say, a ESP8266 module needs.

again, I would use a real power rail for anything over 100mw or so... i'm not syaing power everything though it. i'm saying it can be fun to throw together an led and a temp sensor in 5 mins no solder ;)


text:
How does avrdude burn a bootloader much quicker than the Arduino IDE?
To burn a bootloader to the Arduino Micro (ATMega32u4), I'm using an Arduino Uno with the ArduinoISP program uploaded to it.
1st case: Arduino IDE
Very straightforward, using the ArduinoISP sketch included in the IDE.

From clicking on "Burn Bootloader" to the output window displaying "Done burning bootloader", it takes 61 seconds.
2nd case: avrdude
I'm running avrdude directly from the Arduino IDE's folder like so (line breaks added for your reading pleasure):
D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino
-p atmega32u4 -P com4 -b 19200
-U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

From pressing Enter to avrdude.exe done.  Thank you. displaying on stdout, it only takes 11 seconds. Full output is posted below.
 D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino -p atmega32u4 -P com4 -b 19200 -U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

avrdude.exe: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\MHV AVR Tools\bin\avrdude.conf"

         Using Port                    : com4
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude.exe: Device signature = 0x1e9587 (probably m32u4)
avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude.exe: erasing chip
avrdude.exe: reading input file "..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: writing flash (32730 bytes):

Writing | ################################################## | 100% 0.25s

avrdude.exe: 32730 bytes of flash written
avrdude.exe: verifying flash memory against ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: load data flash data from input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex contains 32730 bytes
avrdude.exe: reading on-chip flash data:

Reading | ################################################## | 100% 0.35s

avrdude.exe: verifying ...
avrdude.exe: 32730 bytes of flash verified

avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: safemode: Fuses OK (E:CB, H:D8, L:FF)

avrdude.exe done.  Thank you.

Question:
Where does this discrepancy come from? The baud rate is hard coded to be 19200 in the ArduinoISP sketch, so that can't be it.

Have you checked the obvious things like baudrate?

@PlasmaHH The baud rate is hardcoded to 19200 in the ArduinoISP sketch. I'll remove that part from my question.

Given that the IDE uses avrdude to do this, it's a bit odd, but you should probably turn on verbose mode and look at the actual command line issued.  Note that the baud rate of sending data from the ISP sketch to the target is distinct from the baud rate of communicating with the ISP adapter.   avrdude supports varying this, but my memory was of the ISP sketch ignoring that specification.

@ChrisStratton It looks like the problem isn't with avrdude, but the hex file. Arduino IDE ships with both a Caterina-Micro.hex and a Caterina-Genuino-Micro.hex. The former is what the IDE uses, the latter is what I used with avrdude. There are differences between the files and burning the latter is very quick but doesn't actually work.

In the Arduino IDE do this:

File > Preferences > Show verbose output during: > upload (check) > OK
Tools > Burn Bootloader

After it finishes examine the output in the black console window at the bottom of the Arduino IDE window. If you look carefully you'll see that the Arduino IDE actually runs two separate AVRDUDE commands when you Burn Bootloader. The first sets the fuses according to the settings in boards.txt for the selected board, the second actually burns the bootloader. So your comparison is not really fair unless you run both commands in your test of using AVRDUDE directly.
Edit by OP:
Full output in the Arduino IDE:
D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: erasing chip
avrdude: reading input file "0x3F"
avrdude: writing lock (1 bytes):

D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:i -Ulock:w:0x2F:m
Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3F:
avrdude: load data lock data from input file 0x3F:
avrdude: input file 0x3F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0xcb"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xcb:
avrdude: load data efuse data from input file 0xcb:
avrdude: input file 0xcb contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xd8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xd8:
avrdude: load data hfuse data from input file 0xd8:
avrdude: input file 0xd8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xff"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xff:
avrdude: load data lfuse data from input file 0xff:
avrdude: input file 0xff contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex"
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 35.65s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: load data flash data from input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 19.92s

avrdude: verifying ...
avrdude: 32730 bytes of flash verified
avrdude: reading input file "0x2F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x2F:
avrdude: load data lock data from input file 0x2F:
avrdude: input file 0x2F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude done.  Thank you.

Thanks, that seems to be correct! There's quite a lot of stuff the IDE is doing, including reading a lock byte apparently.

So as it turns out, there seems to be more to this. Burning the fuses takes less than a second. I'll investigate further.

If you look at the output above, you'll notices that not only does the Arduino IDE write the firmware, it also verifies it. The verification process has to read the entire flash memory after the firmware is written, and the result must be compared to the source file. As shown in the output, the firmware verification takes almost a full 20 seconds.


text:
Arduino voltmeter maximum amp input
I made a programmable Arduino that measures an input voltage. The Arduino will close or open an inverter using a relay to prevent the set of batteries from dropping below 50% to keep the batteries healthy. I currently have a set of 8 6V batteries configured to supply a total of 12V to one inverter. I used a set of 10k ohm and 100k ohm to safely measure the 12 volt input from the batteries. In the current configuration the total Amperage provided by the set of batteries is 400 amps. Is it safe to measure the voltage from a 12V/400A input or do I need some kind of protection?

measuring 12 volts is easy, measuring 400 amps is not.

It is perfectly safe.
The Arduino will see the voltage reduced by the divider you have. It will see whatever current it needs to see in order to sense the voltage - which is a tiny amount.
Remember: Current is drawn on demand by the load. It is never pushed by a supply.

Why do some DMM have a maximum input of 10A when measuring? Also, why Hall-Effect is used to measure high amp current if it's safe to directly measure it using resistance devider?

That is for the current measurement mode. Measuring current and measuring voltage are two very different things.

You measure voltage across something, but measure the current through something. When measuring current that current has to pass through the DMM. When measuring voltage the only current that flows through the DMM is that drawn by the measuring device.

Thank you, I understand now. So basically a hall-effect sensor is to measure the amperage (current) that a component is drawing.


text:
String to char array conversion
In my project I need to convert a string to a char array. From various examples I concluded that toCharArray() will convert a string to a char array. But I failed to do so. The error is:

'a' does not name a type

The code I am using is:
String a = "45317";
char b[6];
a.toCharArray(b,6);

Resources are https://www.arduino.cc/en/Reference/StringToCharArray and http://forum.arduino.cc/index.php?topic=199362.0

maybe this example may help you:
https://stackoverflow.com/questions/68497443/convert-an-arduino-c-string-to-an-ansi-c-string-char-array-using-the-string

If you're trying to use a method of a in the global scope, that's doomed to failure. You can only call methods within functions.
If all you want is a char array with "45317" in it then just use:
char *b = "45317";

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.

There's a built in conversion which will return the underlying string-contents as a NULL terminated character array:
 String foo = "Steve was here"
 char *text = foo.c_str();

That is probably all you need, unless you do want to copy into a buffer.  In that case you can use the standard C library to do that:
 // Declare a buffer
 char buf[100];

 // Copy this string into it
 String foo = "This is my string"
 snprintf( buf, sizeof(buf)-1, "%s", foo.c_str() );

 // Ensure we're terminated
 buf[sizeof(buf)] = '\0';

(You might prefer strcpy, memcpy, etc to snprintf.)

c_str() is no replacement for toCharArray(): your first example fails to compile with “error: invalid conversion from ‘const char*’ to ‘char*’”. Of course, if you only need a const char *, then c_str() is to be preferred. 2) In terms of code size, snprintf() is a very inefficient way of copying a string. 3) No need to subtract one from sizeof(buf) in the second argument to snprintf().


text:
Arduino Serial Communication Issue
I state that I have already written a similar question on StackOverflow thinking that the problem is with my computer software. Anyway, after some shell debugs, I notice that the real issue is on the Arduino Due serial communication.
I am trying to send several data (around 500) from an Arduino Due to a computer software. In order to perform some test I write this little software:
  int dle = 10;
  int stx = 2;
  int etx = 3;
  int counter = 0; //It define the sample frequency
  int dataLength = 7; //How many data I have to read
  // The array of byte will be with this structure
  // DLE,STX,Data1HighByte,Data1LowByte,..,Data7LowByte,CounterHigh,CounterLow,DLE,ETX
  //int arrayLength = (dataLength + 1 ) * 2 + 4;
  byte buff[20];
  int val = 0;

  int myTime = 0; //it is used in order to define the sampleFrequency

  void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200, SERIAL_8N1);
    buff[0] = dle;
    buff[1] = stx;
    for (int i = 2; i < sizeof(buff) - 2; i++) buff[i] = 0;
    buff[sizeof(buff) - 2] = dle;
    buff[sizeof(buff) - 1] = etx;

    myTime = millis();
  }

  void loop() {

    //fill the buffer
    for (int c = 0; c < dataLength; c++) {
      val = analogRead(c);
      val = 30 + c; //as a test
      buff[c * 2 + 2] = (byte)((val & 0xFF00) >> 8);
      buff[c * 2 + 3] = ((byte)(val & 0x00FF));
    }
    buff[dataLength * 2 + 2] = (byte)((counter & 0xFF00) >> 8);
    buff[dataLength * 2 + 3] = ((byte)(counter & 0x00FF));

    counter++;

  //print the content on serial
    for (int i = 0; i < sizeof(buff); i++) {
      Serial.write(buff[i]);

    }

    if ( millis() - myTime >= 1000 ) { //if is passed 1 sec, the counter will be reset
     // Serial.println(counter);
     // delay(1000);
      myTime = millis();
      counter = 0; //This identify the sample frequency
    }
  }

As you can see, the arrays of bytes that I send have the form of DLE-STX-DATA-DLE-ETX. Anyway, some data are missing and some other data get strange values.
Here are an output example (1000 samples):
    Reading 0 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,44,10,3
    Reading 1 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,45,10,3
    Reading 2 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,46,10,3
    Reading 3 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,47,10,3
    Reading 4 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,48,10,3
    Reading 5 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,49,10,3
    Reading 6 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,50,10,3
    Reading 7 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,51,10,3
    Reading 8 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,52,10,3
    ...
    Reading 173 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,217,10,3
    Reading 174 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,218,10,3
    Reading 175 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,219,10,3
    Reading 176 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,220,10,3
    Reading 177 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,221,10,3
    Reading 178 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,222,10,3
    Reading 179 time: ,0,33,0,34,0,35,0,36,0,170,10,3,10,2,0,30,0,31,0,32
    Reading 180 time: ,0,33,0,34,0,35,0,36,0,171,10,3,10,2,0,30,0,31,0,32
    Reading 181 time: ,0,33,0,34,0,35,0,36,0,172,10,3,10,2,0,30,0,166,10,
    Reading 182 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,167,10,3
    Reading 183 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,168,10,3
    Reading 184 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,169,10,3
    Reading 185 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,170,10,3
    Reading 186 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,171,10,3
    Reading 187 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,172,10,3
    Reading 188 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,173,10,3
    Reading 189 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,174,10,3
    ...
    Reading 607 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,8,10,3
    Reading 608 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,9,10,3
    Reading 609 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,10,10,3
    Reading 610 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,11,10,3
    Reading 611 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,12,10,3
    Reading 612 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,13,10,3
    Reading 613 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,14,10,3
    Reading 614 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,10,30,0
    Reading 615 time: ,31,0,32,0,33,0,34,0,35,0,36,1,145,10,3,10,2,0,30,0
    Reading 616 time: ,31,0,32,0,33,0,34,0,35,0,36,1,146,10,3,10,2,0,30,1
    Reading 617 time: ,140,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 618 time: ,141,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 619 time: ,142,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 620 time: ,143,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 621 time: ,144,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 622 time: ,145,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 623 time: ,146,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 624 time: ,147,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 625 time: ,148,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 626 time: ,149,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    Reading 627 time: ,150,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1
    ...
    Reading 994 time: ,189,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0
    Reading 995 time: ,190,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0
    Reading 996 time: ,191,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0
    Reading 997 time: ,192,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0
    Reading 998 time: ,193,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0
    Reading 999 time: ,194,10,3,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0

As you can see, in this example, Arduino lost some bytes. In addition, the counter has a strange behavior. It, when I "lost" the data jump to another "random" value. For example in the line 178-182
Reading 178 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,1,222,10,3
Reading 179 time: ,0,33,0,34,0,35,0,36,0,170,10,3,10,2,0,30,0,31,0,32
Reading 180 time: ,0,33,0,34,0,35,0,36,0,171,10,3,10,2,0,30,0,31,0,32
Reading 181 time: ,0,33,0,34,0,35,0,36,0,172,10,3,10,2,0,30,0,166,10,
Reading 182 time: ,10,2,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,167,10,3

it has the value of 1 in high byte and 222 in low byte. Anyway, at the next reading, the value become 0 for high byte and 170 for low byte. And lastly (line 181), it restarts normally to count with 0 in high byte and 166 in low byte.
I try to change the device (I test on an Uno and the problem is the same), the communication protocol (with parity, etc), change the baud and use another PC. The issue is always the same.

I suggest you start smaller and work up to your whole program.  Begin with just sending the same thing over and over with a counter that increments.  That way you will make sure you have a good serial connection to start with.

I try to send a simple package with this structure: DATA-COUNTER-DLE-ETX. In this test the data is a simple 30, the counter is a counter, and DLE=254, ETX=255. So, the array of bytes is composed of 6 bytes (2 for the data and 2 for the counter). Anway, the problem persist.

How about if you send only the counter and no other data?    My point is that you want to try to trap the bug by proving the basics work.

It can be a problem at the other end of your cable. The code you show seems to be OK. What are you using for capturing data?


text:
How to detect if the arduino wire is still connected
I have hall sensors connected to an arduino, because of mechanical movements there is some possibility that the input wire may accidentally slip out of the arduino analogin sockets. Is there any way I can detect if the wire is still connected to hall sensor  ? I don't want to solder the cables yet.

Schematic and datasheet where?

if the read values don't make sense, or fluctuate wildly, they've become unplugged.

Solder the cables to headers so they don't slip out?

You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.
digitalWrite(Ax, INPUT_PULLUP);

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.
Otherwise, use some vinyl duct tape.... this would securize the thing a bit!

are you mixing up pinMode constants and digitalWrite, or is this a secret?

this is no secret: link. It may work by writing HIGH instead of INPUT_PULLUP, at least it works when wanting to set the internal pullup resistor for digital input.

Either use pinMode(Ax, INPUT_PULLUP); or digitalWrite(Ax, HIGH);. It will work either way, but it's no good programming practice.

What would be the best programming practice to enable an input pull-up on arduino? Other than accessing the proper register directly?


text:
Manchester 433MHz Nano to ATTiny85
My transmitter is a Nano, the receiver is a Tiny85.
I use a Logic Analyzer to check if stuff is moving, I can clearly see data coming in at the receiver.
The receiver does not 'decode' the data, man.receiveComplete() is never True so in the end nothing happens.
I think the problem may be the difference in clock speeds, there are some things I have tried. The Nano is sending every second, in the logic analyzer I can see this come in every second so he is 'right on time'.
But I am not so sure about the ATTiny85..

ATTiny85
Tiny Core
8MHz (burned bootloader 3x)

It is still to fast, counting to 3 is not working ok..
Bootloader burning log
    /home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Uefuse:w:0xFF:m -Uhfuse:w:0xD7:m -Ulfuse:w:0xE2:m

avrdude: Version 6.3, compiled on Dec 16 2016 at 12:32:01
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
         User configuration file is "/home/thijs/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x1e930b (probably t85)
avrdude: erasing chip
avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: reading input file "0xFF"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFF:
avrdude: load data efuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xD7"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD7:
avrdude: load data hfuse data from input file 0xD7:
avrdude: input file 0xD7 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xE2"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xE2:
avrdude: load data lfuse data from input file 0xE2:
avrdude: input file 0xE2 contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200

avrdude: Version 6.3, compiled on Dec 16 2016 at 12:32:01
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
         User configuration file is "/home/thijs/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.04s

avrdude: Device signature = 0x1e930b (probably t85)

avrdude done.  Thank you.

high level

zoomed

I have tried to use the Analyzer options for Manchester encoding in Saleae Logic but I do not know how to configure it right..
Receiver Code

#include <Manchester.h>
#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
#include "LiquidCrystal_attiny.h"

LiquidCrystal_I2C lcd(0x27,16,2);

#define RX_PIN 1
uint8_t moo = 1;
#define BUFFER_SIZE 4
uint8_t buffer[BUFFER_SIZE];

int curs = 0;

void setup() {
//  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  delay(1000);
  pinMode(4, OUTPUT);
  lcd.init();
  lcd.backlight();
  lcd.home ();
  lcd.setCursor (0, 0);
  lcd.print("Start ");
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
  count();
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;

    //do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);

//    pushtolcd(".");
    lcd.print(".");
    Serial.println();

    man.beginReceiveArray(BUFFER_SIZE, buffer);
    moo = ++moo % 2;
  }
}

void pushtolcd(String text) {
  lcd.home ();
  lcd.setCursor (0, curs);
  curs++;
  lcd.print(text);
  delay(500);
}

void count() {
  for (int i=0; i<3; i++) {
    lcd.print(i);
    delay(1000);
  }
};

Sender code
#include <Manchester.h>

#define TX_PIN  5  //pin where your transmitter is connected
#define LED_PIN 13 //pin for blinking LED

uint8_t moo = 1; //last led status
uint8_t data[20] = {11, '1','2', '3', '4', '5', '6', '7', '8', '9','1','2','3','4','5','6','7','8','9'};

void setup()
{
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, moo);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TX_PIN, MAN_1200);
}

uint8_t datalength=2;   //at least two data
void loop()
{

  data[0] = datalength;

  man.transmitArray(datalength, data);
  moo = ++moo % 2;
  digitalWrite(LED_PIN, moo);

  delay(800);
  datalength++;
  if(datalength>18) datalength=2;
}

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


text:
The working of a MFRC522 and its Interface protocols?
I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given this datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.
I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.
I have here the image of the pinout from a MFRC522 and I have the following questions:

Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

Let's have a look at the datasheet of that chip:
Paragraph 8.1 says

The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on this specific board the control pins are preconfigured for SPI. But, the supporting library only supports SPI so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK

what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

I think this is your board, and luckily they include a schematic on that page:

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.

Thanks for helping out again, after helping me provide these informations. :)
As the device is hardcoded to SPI mode, I guess I do not need to worry about the other compatible host interfaces. I understand how Pin 1 being connected to GND would rule out the possibility of I2C mode, but how does EA being connected to 3.3V rule out the possibility that it uses UART communication?

@Tsubakura the communication mode is decided by the combination of pins 1 and 32, and UART needs pins 1 AND 32 tied to 0. That's explained in 8.1.1