text:
Communication between IC and microcontroller (Teensy 3.2)
I am trying to use a rotary encoder with an integrated circuit to measure the position of a rotating shaft. I am then taking this data and writing to an SD card. The IC seems to be working correctly and outputting binary data to the specified pins,  but the data does not seem to be reaching the micro-controller. My output data is fragmented, and seems to only be receiving binary data from some of the IC pins. The IC I am using is HCTL-2021-A00 (http://www.mouser.com/ProductDetail/Avago-Technologies/HCTL-2021-A00/?qs=RuhU64sK2%252bsgeK17XZB%2fNA%3d%3d). I tried using a larger gauge wire to connect the two, but then the micro-controller didn't seem to pick up any of the data. Here is the code I used.
I am trying to use a rotary encoder with the HCTL-2021-A00 from avago. I am getting data output from the IC, but only one of the two bytes which it should be providing. When I move the encoder forward, it will only give me the LOW byte and all of the high bits will be zero. However, when I move the encoder backward, all of the high data bits are 1, and the low data bits still operate normally, counting the position. What could cause the high data bits to all be 1 when moving backward, and all 0 when moving forward? Code used is below.
#include <SD.h>
#include<SPI.h>

File datafile;
const int chipSelect = 10; // connected to the CS pin on the sd card, Make sure the card is formatted
int encoderpos=0;
int i=0;
int pulses, A_SIG=0, B_SIG=1;
int b[15];  //the individual bits of data read from the IC
int pos; //position output of IC ranging from 0 to 5000 for 1 revolution
int selpin=1, OEpin=2;
int clock=4;
int d[7]; //the pins on the IC attached to which digital teensy pins
double deg; //degree position of the servo as found from the encoder and IC

void setup()
{
  //set pwm signal for timer input
  pinMode(4, OUTPUT);
  analogWriteFrequency(4, 6000000); // Teensy 3.0 pin 3 also changes to 375 kHz
analogWrite(4, 128);
   //First setup and attach the pins used to communicate with the IC and encoder
  d[0]=22;//pin numbers for attaching the IC to the teensy
  d[1]=21;
  d[2]=20;
  d[3]=19;
  d[4]=18;
  d[5]=17;
  d[6]=16;
  d[7]=15;
//first set pins as inputs and outputs
pinMode(selpin, OUTPUT);
pinMode(OEpin, OUTPUT);
pinMode(d[0], INPUT);
pinMode(d[1], INPUT);
pinMode(d[2], INPUT);
pinMode(d[3], INPUT);
pinMode(d[4], INPUT);
pinMode(d[5], INPUT);
pinMode(d[6], INPUT);
pinMode(d[7], INPUT);

digitalWrite(selpin, HIGH);
digitalWrite(OEpin, HIGH);

pinMode(5, OUTPUT);

digitalWrite(5, HIGH);
delay(5);
digitalWrite(5, LOW);
delay(5);
digitalWrite(5, HIGH);
delay(5);

pinMode(chipSelect, OUTPUT);
SD.begin();
datafile=SD.open("c.txt", FILE_WRITE);
pinMode(7, INPUT);
pinMode(8, OUTPUT);

}

void loop()
{
datafile.println(pose());
if (millis()>4000)
{
  datafile.close();
}

delay(5);
}

int pose()     //Gives the position in degrees from the readings from encoder and IC for 0 to 5000 representing one revolution
{
    digitalWrite(selpin, LOW);     // The sel pin on the IC
  digitalWrite(OEpin, LOW);     // The OE pin on the IC
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[0]=digitalRead(d[0]);
  b[1]=digitalRead(d[1]);
  b[2]=digitalRead(d[2]);
  b[4]=digitalRead(d[4]);
  b[5]=digitalRead(d[5]);
  b[6]=digitalRead(d[6]);
  b[7]=digitalRead(d[7]);
if(digitalRead(7)==1)
{
  digitalWrite(8, HIGH);
}
else if(digitalRead(7)==0)
{
  digitalWrite(8, LOW);
}
  digitalWrite(selpin, HIGH);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[8]=digitalRead(d[0]);
  b[9]=digitalRead(d[1]);
  b[10]=digitalRead(d[2]);
  b[11]=digitalRead(d[3]);
  b[12]=digitalRead(d[4]);
  b[13]=digitalRead(d[5]);
  b[14]=digitalRead(d[6]);
  b[15]=digitalRead(d[7]);

  digitalWrite(OEpin, HIGH);

  pos=0;
  i=8;
  for(i; i>0; i--)
  {
pos=2*pos+b[i-1];
  }

  i=16;
  for (i; i>8; i--)
  {
    pos=2*pos+b[i-1];
  }

  return pos;

}

I found the problem.
I had assumed that the rst pin was supposed to be held low unless you wanted to reset the count on the encoder, and was ignoring it the whole time. Once I held the reset pin high, the count started to show up.
As of now there are still problems, I cannot read the high byte from the IC.

Probably because you are still mishandling the clock

I also changed the clock to force up and down after changing sel and oe. These changes are now reflected in the code above. Would this still be incorrect?

You seem to be overlooking (or at least mishandling) the fact that these parts are built with a bus interface where the /OE and SEL signals as well as the internal position data latch are sampled synchronously with a clock input which you do not seem to be driving.

You need to generate a low-to-high transition of the CLK signal to latch the count into the readout
You need to generate a high-to-low transition of the CLK signal to latch in chosen values of the /OE and SEL signals.

On second examination of your code, perhaps you are trying to use a free-running clock asynchronous to your reading.  That, however, is extremely unwise.  First, you don't know that a suitable clock edge will happen between when you set the /OE or SEL and when you try to read the data.  Next, you do not know that an undesired clock edge will not happen in the midst of reading data, causing you to end up with a corrupted value that contains some "old" bits from before the clock edge and some "new" bits from after.  This would be particularly bad if it happened across a transition such as 0b01111111 to 0b10000000 or similar...
You may have other problems as well - your question is not complete without a schematic diagram of how you have wired up this chip.

No, it doesn't - it would only mean that if you could verify that the critical clock transition occurred between when you set these signals and started reading, and not at some point in the midst of reading... which at present you can't.  Your asynchronous approach is fundamentally broken.  If you want to keep the free-running clock, at minimum you will have to have your program wait for suitable clock transitions between settings and readout.

Either drive the clock explicitly in code after you set the control signals, or else read back the clock and wait for the necessary transition between setting the control signals and reading the data.

Wanted to just put this in a comment but apparently still don't have the rep to do that, so taking a stab at answering.
Sounds to me like you are having physical layer corruption issues.  I highly doubt that your wires were too fine a gauge since these are just signal wires for SPI, however, it was instructive that you did that since larger wires seemed to make the problem worse, I would guess that you have too large capacitance on the wire for the datarate you have chosen.
When I am debugging any serial communications for the first time, the first thing I do until communication is reliable is to slow the data rate down.  Something like 10kHz should work in most cases.  See if this fixes the corrupted data.  If it does, go back to a finer gauge wire and then bump the speed back up til you see corruption issues.  If you have a logic analyzer or a scope you can get on the line, it will be very educational to see what is going on with your edge rates.


text:
millis() in a millisecond stopwatch
I'm making a stopwatch that will measure time between two points.
I want that stopwatch to have a millisecond accuracy.
After the start when someone touch the pad it will show like the time of the touch (15.359) 15 seconds and 359 millis.
I have an arduino uno board.
Everywhere I read it says that millis its not reliable, and in a feel tests it seems not very accurate. Also a lot of places say to use a RTC, but every RTC I found and read about it seem to use only second and not milliseconds. Others say to use a 32 KHz crystal, but I'm not sure if it will fix this. Could anyone give some ideas?
The Arduino will only record time, only that, start and get time and subtract and write on the serial and end.
Thanks!
update 1: thanks Mattia for the edit.
update2 : I was making some  math, and if the device is on for 8 hours, and i want millisecond precision i need something like 30ppb right?
Would this do the job?
http://www.digikey.com/product-detail/en/abracon-llc/AOCJYR-12.800MHZ-M5649LF/535-12624-1-ND/4989030

Use a precision oscillator (possibly temperature compensated), then measure its time. You can find even 5ppm oscillators, which means that you can have an accuracy of one millisecond for times less than 200 seconds..

Some RTC can also output a frequency. E.g. the DS3231 can output a 1Hz, 1.024kHz, 4.096kHz, 8.192kHz square wave. This frequency is quite precise, as it's temperature compensated. You could use it, and count the number of pulses between the two touches. Might I ask what you are using to detect a touch? I hope you are not using CapSense for this.

Theres a touchpad, that when someone touch theres a contact similar to a button, i just read LOW or HIGH on arduino to know if someone touchs it. I'll read about count the pulses. thanks

For a ms in 8 hours, I get ~ 1 part in 30 million: (8hrs * 3600 sec/hr * 1000 ms/sec = 28,800,00 ms).

Yes! 28,800,800! But i have to multiply over the 20/1.000.000.000 in this case from the crystal right? to know the precision? because i dont found any 1/30ppm crystal, neither 0.33ppm. I'm probably messing up everything, first time working with this math.

The resonator on the Arduino Uno is better than the internal oscillator of the Atmega328p, but still not very precise. Therefore, for accurate measurements, you need to use a better quality crystal. For instance @ 16 MHz. Once you set the correct prescaler in the Arduino, this should give you accurate millis() - as long as the crystal that you're using is accurate.

Do you know or have any material for implemente the crystal on arduino?  i'll also look more for it. thanks

Here's a starting point: http://www.google.com?q=Temperature+Compensated+Crystal+Oscillator+16+mhz

From what I read, Eduardo isn't using the internal oscillator. He says he's using an Arduino Uno, that already has an external crystal.

You are right, my bad. I have corrected my answer. The 16 MHz external oscillator of the Uno is probably miles ahead of the internal 8Mhz oscillator in the Atmega. Still, it's a relatively cheap resonator. I reckon that replacing it with a high quality oscillator can increase the precision by many orders of magnitude without breaking the bank. See this thread for a comparison: http://forum.arduino.cc/index.php?topic=60662.0

I'm even considering get an expensive (until 30$ maybe) crystal to get a better precision. There a good "brand" or any that you or anybody vouch for?

source: Stack Exchange

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

sort: votes


text:
How to listen for an incoming serial string inside loop with long delay?
I'm trying to build a datalogger using Arduino UNO, I'll use RS232 for the communication between PC and Arduino, the problem I'm facing now is that I'm using delay(10000) : 10 seconds as a timestep for data acquisition. however, I can't find any solution to receive a string from the serial input to Arduino while delay is executing. Here is the code :
void setup() {
  Serial.begin(9600);
}

void loop() {
  serialRoutine();
  dataLoggingEvery10Second(); // That's a function to receive data from the sensor and store it in SD card.
  delay(10000);
}

  // A function to handle all the serial in out
  void serialRoutine(){
  // print the string when a newline arrives:
  while(Serial.readString() == ""){
    String serstr = Serial.readString();
      /*
      *  Getters
      */
      if(serstr == "GETDATA"){
        Serial.println("Here is my data");
      }
      serstr = "";
  }
}

Any help would be highly appreciated !

You could also look at interrupts.

Why the delay at all? Nothing will happen until it receives GETDATA anyway, so what is the point of the delay?

I can't find any solution to receive a string from the serial input to Arduino while delay is executing. - why do you need to receive data anyway? Aren't you sending it?

Sorry guys, I forgot to put the data acquisition function between serialRoutine(); and delay(10000);

while(Serial.readString() == ""){String serstr = Serial.readString(); - this seems to me to be reading two strings.

If your PC is sending GETDATA, then it can send it every 10 seconds (or every 15 or 30 minutes) so you don't need any delays at the Arduino end at all.
I have a page about getting serial data without blocking which illustrates how you can be doing other things (like reading sensors) without blocking.
An example sketch is:
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

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


text:
Setting up two arduinos connected to separate serial ports with wires in-between
I intend to have both an Arduino Nano and an Uno connected to a PC via the on-board USB ports, but have them inter-connected with wires from one's GPIO pins to the other's (one reads the status of the other's pins). I've read that having two Arduinos communicate with each other requires them to share a common ground, so am not sure if this will work at all (the common power source in the PC may serve as the common ground, I'm not sure).
As some background, I would like the Nano to serve as an EEPROM programmer and have the Uno connected as a logic analyser to help debug the EEPROM programmer, both using serial to communicate with the PC in real-time.
How should I set up the Arduinos and power supply to make this possible in a safe way?

https://majenko.co.uk/blog/importance-sharing-grounds

can you not run a ground wire next to the tx or rx wires? it doesn't have to come from the power connections...

what is your question?

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


text:
SOLVED Accelerometer/gyro MPU6050 is freezing after random time
SOLVED: I "solved" the problem by cycling my Arduino's power and I haven't had an issue since. I would still like to figure out what was going on. I still think it's something in that MPU6050 library with getMotion. But anyway, if anyone eventually has any ideas post it up. Thanks

Original question:
I'm using an MPU6050 accelerometer/gyro that controls a servo through a Mega.
QSTN: The sensor simply stops reading after an arbitrary time, usually between 2-4 minutes. I have to reinitialize the serial monitor/MPU to get it to work again which is not good. I suspect it has something to do with getMotion but I can't put my finger on it.
Any ideas? Thanks. Code is below:
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

MPU6050 mpu;

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

Servo servo1;

int val;
int prevVal;

void setup()
{
    Wire.begin();
    Serial.begin(38400); //38400

    Serial.println("Initializing MPU6050");
    mpu.initialize();
    Serial.println(mpu.testConnection() ? "CONNECTED" : "Connection failed");
    servo1.attach(9);
}

void loop()
{

    mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);

    if (val != prevVal)
    {
        servo1.write(val);
        prevVal = val;
        Serial.println(val);
    }

    delay(75);

}

I suspect something with the i2c bus. There can be many problems with a i2c bus. For example a bad quality breadboard or long wires. For the arduino mega you need a level shifter for the sda and scl. Can you show a photo of the wiring between the arduino mega and the mpu-6050? Could you upgrade to a 3.3v arduino board, a mpu-9250, and the ahrs filter? Then you can use this guide: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide When we ask extra information, please add that information to your question.

Can you measure the voltage on the SCL and SDA lines, when the freezing happens? Despite the rather short (and supposely rare in relation to the whole time) transmission period, both lines should be HIGH. If you see one of the lines being LOW for a longer time, then the I2C communication freezes for some reason during transmission, blocking the bus. May be a good starting point for debugging.

I suspect you may be right about the I2C but I think it may be a library issue. I tried a second breadboard and I've heard of the wire issues with I2C but these are standard hobby jumpers. Why do you think the level shifter is necessary at clock and data? I hooked it straight to the 3.3v on the Mega but it also appears to be 5v tolerant because I tried that out too and left it on all day and it was working okay. I unfortunately don't have an oscilloscope or multimeter on hand but I can look into that.

I "solved" the problem by cycling my Arduino's power and I haven't had an issue since. I would still like to figure out what was going on. I still think it's something in that library. But anyway, if anyone eventually has any ideas post it up. Thanks

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


text:
Arduino UNO doesn't produce expected square waveform
I want to produce quick square waveform for testing purposes. If I will use this code:
void setup()
{
 pinMode(2, OUTPUT);
}

void loop()
{
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
}

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.
I use latest Arduino 1.6.9 environment.
Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.
Any idea what I'm doing wrong?
Same results if I use asm sbi and sci instead of macros bitSet/bitClear.
Thank you!

/*
So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:
void setup()
{
 pinMode(2, OUTPUT);
 noInterrupts();
}

void loop()
{
 while(true)
 {
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
 }
}

On the Uno, the Timer 0 overflow interrupt kicks in every 2014 µs. This is probably the glitch you are seeing. If you want to avoid it, do not use Arduino core, just plain avr-libc.

Or disable interrupts.

“Whole loop cycle take 1 us which mean 16 instructions”. There are actually only 6 instructions. Two of them take 4 cycles each (call and ret), the others take 2 cycles each (sbi, cbi, sbiw and breq).

Yes. I should have write "cycles" instead instructions.

The fastest you can get is 8 MHz: take the “Use a hardware timer” code I posted and change the OCR2x registers to OCR2A = 1; OCR2B = 0;.

@EdgarBonet Wow! Awesome! Your knowledge about Arduino amazes me! Thank you very much!

As I explained in my comment, the reason for this glitch is the Timer 0
overflow interrupt kicking in every 1024 µs. This interrupt is used
by the Arduino core library for timekeeping. It is the basis of
millis(), micros() and delay(). The interrupt is enabled by the
init() function in
wiring.c.
There are several approaches to avoid that:
Avoid the Arduino core initialization
This may be overkill, but since it seems you are already familiar with
directly accessing the IO ports of the ATmega chip, it may well suit
you. You can use the Arduino IDE without the Arduino core initialization
simply by defining your own main():
#include <util/delay.h>

int main(void)
{
    DDRD |= _BV(PD2);        // PD2 as output
    for (;;) {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
        _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
    }
}

Notice the extra delay: without it, the loop would complete in 6 CPU
cycles (2 per port access, 2 more to loop back). Not doing the Arduino
core initialization means you have no timekeeping and no analogRead()
or analogWrite(). Other Arduino functions should work normally but
some, like Serial.begin() will bring their own interrupts.
Disable interrupts
As suggested by Majenko, this may be the simplest way to have a steady
waveform:
void setup()
{
    pinMode(2, OUTPUT);
    noInterrupts();
}

void loop()
{
    PORTD |= _BV(PD2);   // PD2 high
    PORTD &= ~_BV(PD2);  // PD2 low
}

Without interrupts, you have no timekeeping, no serial communications
and, obviously, no attachInterrupt(). Most other Arduino functions
should work.
Use a hardware timer
This allows you to generate the signal without relying on the CPU. You
can keep interrupts enabled and do other work in the program while the
waveform goes undisturbed. The simplest way to generate such a waveform
is with analogWrite(). The resulting frequency is quite low though,
like 0.5 to 1 kHz. If you want 1 MHz, you will have to
configure the timer the hard way. For example:
void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 as output
    OCR2A = 15;           // period = 16 clock cycles
    OCR2B = 1;            // high during 2 clock cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS20);   // clock at f_CPU
}

void loop() { }

The output is on pin PD3 = digital 3. This configuration will disable
analogWrite() on pins 3 (PD3) and 11 (PB3).

What piece of Arduino starts this timer / implements it's interrupt (you should kill it at it's roots? So you can still use other interrupts)? And is there an easy way to see which pieces of code depend on the timed interrupt of Arduino?

@Paul: It's all in the wiring.c file I already linked to. The interrupt service routine only updates three variables: timer0_millis, timer0_fract and timer0_overflow_count. These are only used inside wring.c. You can see what depends on the interrupt by searching for these variables through the file: only millis() and micros(). But then delay() depends on micros(), Stream on millis(), and some USB stuff (not on the Uno) on delay().

Cool, so I could disable this interrupt and still use libraries that use interrupts (such as servo/softserial). Or well, I would have to check if they rely on millis() or micros().

@Paul: That's correct, but any enabled interrupt would cause the kind of glitch seen here.

So I added noInterrupts(); in my code and now the waveform is perfect! Thank you very much @Edgar Bonet! And I will try other methods too. There is still so much to learn. I am familiar with Arduino timer but I thought it doesn't affect running program. BTW You all probably know it but these microcontrollers are so cool  :D haha

I want to produce quick square waveform for testing purposes.
Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.
  Any idea what I'm doing wrong?

You are assuming that what goes on outside loop() and the call to loop() takes no time at all.
This is what the Arduino core main() looks like.
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

There is both the call to loop(), if-branch, and for-branch. This all adds up. On top of this there are a number of Interrupt Service Routines (ISR) such as for the Timer which is used for the micros() and millis() count. These will interleave periodically (as you have observed).
Now the question is how to fix this and I think @Edgar Bonet has done an excellent job with that.
Cheers!

If you just want a rough square wave to test and you don't care about the frequency then try this:
void setup()
{
   pinMode(2, OUTPUT);
}

void loop()
{
   digitalWrite(2, true);
   delay(2);
   digitalWrite(2, false);
   delay(2);
}

If you don't care about the frequency, analogWrite(3, 128); is simpler.

@sa_leinad: I care about frequency so I used bitSet/bitClear to make it quicker. Now I have clean 1 Mhz waveform (thanks to Edgar) which I will never achieve with standard digitalWrite.

Could you please edit your question to reflect this information.


text:
Powering ESP8266 from Leonardo's 3.3v pin
I'm new to Arduino, and I'm trying to connect my Leonardo via WiFi using a ESP8266 module. What I want to know is if I can power it directly from the onboard 3.3V pin like in the image:

Or do I need an external voltage regulator? I don't want to damage it.
Thanks!

The Leonardo is specified to provide only 50mA on the 3V3 pin. A ESP8266 can use up to almost 300mA when transmitting. Consider using a LDO regulator connected to the 5V pin instead.

Thanks! And the 5V pin can handle the current?

If supplying power via USB it should be fine unless you have a few other devices connected to it. If supplying power via an external 7-12V supply then the on-board regulator may get a bit warm, so you'll have to judge from that.

That specification in wrong. The 3.3v regulator is actually 150mA not 50mA. Don't believe everything you read on the Arduino website.

Ok, so which one should I trust? I don't want to find out by testing and killing my brand new Leonardo ;)

If you're communicating with the ESP8266 for very short bursts then you may be able to get away with the on-board LP2985 if you add a local bulk capacitor. If you need constant communications then you should strongly consider a larger regulator.

Ok, I finally used an LM2596 to lower the voltage from the 5V pin to 3.3V and a voltage divisor for the Rx pin in the ESP8266 module.

Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module.

Actually that's the one I've been using. Aaand, I got rid of the Leonardo. I'm programing the ESP module, avoiding the bottleneck of the slower Leonardo's processor.


text:
What is happening in this basic push-button circuit?
In the example circuit below (Arduino Uno R3), what would the equation be to identify the amperage going into pin 2 when the button is pressed? What if I used the 3.3v on the arduino or a 9v battery instead?
What is happening to the input pin when the button is not being pressed? (I assume it's a guaranteed LOW state due to any current being sapped by the GND, yes?)
What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?
A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.
Sorry for so many little questions in this one question, but these are the kinds of things I'm not seeing addressed in most tutorials.

Have you heard of Ohm's Law?

@majenko I'm familiar enough with the concept for a typical series circuit or parallel circuit from a single tutorial or two, but that's about it. Branching off between the button and resistor is the bit that confuses me on how to calculate it here (I believe).

what would the equation be to identify the amperage going into pin 2 when the button is pressed?

Once the button has been pressed for more than a few nanoseconds the current will be 0 (or as near as).
Immediately the button is pressed the formula is  I(t) = dQ(t) / dt since the input pin is a MOSFET gate and as such is seen (in simple terms) as a capacitor.

What if I used the 3.3v on the arduino or a 9v battery instead?

The same.

What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

It is pulled down to ground by the resistor.

What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

The input will be HIGH when the button is pressed, and floating (initially HIGH) when released.

A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The main concern with a pullup or pulldown resistor is the current it demands from the power supply when the button is pressed. If it's too low then you will be wasting current. If it's too high then the input may take a while to turn off when you release the button.  10K is a "good" value since it is a good balance between those two factors.
The current from the supply is calculated as I=V/R, so 5/10000 = 0.5mA.  Low power systems may choose a higher value (100kΩ, say) to reduce the current.

what would ... the amperage going into pin 2 when the button is
  pressed?

Virtually zero Amps, as pin 2 is set to an input. There is some input impedance, but according to the datasheet that is, at maximum, 1µA.

What if I used the 3.3v on the arduino?

Same thing. 1µA.

or a 9v battery instead?

Then you will blow up your chip.

What is happening to the input pin when the button is not being
  pressed? (I assume it's a guarangeed LOW state due to any current
  being sapped by the GND, yes?)

That's where the resistor in the circuit comes in. It's called a pull-down resistor. It will make sure the pin is LOW. Without it the pin is "floating", and could read as HIGH. e.g. due to some static in the air, or just having your hands nearby the pin.

What would happen without the pull down resistor? A short when the
  button is pressed?

If you remove the resistor, you shouldn't connect GND to the other side of the switch. That would indeed cause a short between 5V and GND, possibly damaging your powersupply/PC or blow up your wires, or traces on the Arduino PCB

What would happen without the ground being connected at all? Anything?

The pin would be floating and result in sometimes reading a HIGH even when the button isn't pressed.

A tutorial for how to choose a pull down resistor I seen suggested a
  resistance value of 10 times the impedance of the pin. I'm not quite
  sure where to find this impedance value, but I have seen on an arduino
  tutorial "A 10K resistor is a good value for a pullup or pulldown
  resistor." Just not much of an explanation of why that value.

The value here isn't very critical. Somewhere between 1k and 100k will work.


text:
Count specific range of output as 1 single output
The LDR sensor gives a range of values to show whether a LED is OFF/ON, let's say above LDR range 400, the led is ON. When a LED is ON, after reading the sensor values it shows above LDR range 800, because the LDR sensor measuring in ms, a single LED blink shows six LDR 800+ values. Is there any way to count all the six  LDR 800+ values to increase counter by 1?
Here's my output in serial monitor. 314 to 322 is led OFF state and 816 to 851 is led ON state.
LED : 314
LED : 314
LED : 314
LED : 321
LED : 322
LED : 322
LED : 816
LED : 817
LED : 818
LED : 817
LED : 817
LED : 815
LED : 351
LED : 329
LED : 323
LED : 327
LED : 326
LED : 339

what is the problem?

what do you observe when you are counting flashes of a light? ... write your program to do the same

There are two distinct problems here.
The first problem is to convert the analog reading into a binary value.
You measure a value between 314 and 856, and you want to know whether
the LED is ON or OFF. The simplest solution is to compare the reading to
a threshold that is roughly in the middle of the range you measure. You
could say, for example, that the LED of OFF if the reading is below 580,
and is ON otherwise:
bool led_is_on = analogRead(ldr_pin) >= 580;

If the readings are noisy while they cross the threshold (does not seem
to be the case in the short span of data you show), you may want to use
some noise cancelling techniques. You could, as suggested by Michel
Keijzers, require multiple consecutive “ON” reading before deciding the
LED is actually ON. Or you may research the technique of using
hysteresis, which would be my favorite solution, as it is extremely
simple. However, if your readings are always as clean as what you are
showing us (never fluctuating mid-range), you can stick with the simple
threshold solution shown above.
The second problem is called edge detection. You want to count the
blinks. For this, you need to count how many times the LED turns ON,
which is not the same as how many times the LED is ON. You know that
the LED turned ON if you just detected it is ON and, on the previous
iteration it was OFF. So you have to remember whether the LED was ON
last time you looked at it. This means you have to store this
information (whether the LED was ON) in a static (or, if you prefer,
global) variable. Which leads to the following program:
int blink_count;

void loop() {
    static bool led_was_on = false;
    bool led_is_on = analogRead(ldr_pin) >= 580;
    if (!led_was_on && led_is_on) {
        blink_count++;
    }
    led_was_on = led_is_on;
}

Note the condition: !led_was_on && led_is_on means “The LED was not
ON and now it is ON”.

I'm not sure what the value 400 is used for exactly, but the code below is for increasing the counter when at least 6 consecutive values above 800 are occurred.
The key is to use a state machine.
I don't have a compiler at hand so forgive possible syntax errors.
First we define a state. In your case, there are only two possibilities, so a boolean (bool) is used, normally an enum is used.
bool _counting = FALSE;

We also need a constant (or define) and a counter to see how many ON values are needed before incrementing the counter, which counts downwards to 0 (and can go negative when more ON values occur).
const int MIN_FLASH_LENGTH = 6;
int _onBeforeIncrementing = MIN_FLASH_LENGTH;

However, we can use the last variable to see if counting is occurring, so we do not have to use the boolean above.
Then we need a counter for the amount of flashes itself:
int _amountOfFlashes = 0;

Both of these are global variables.
Furthermore, in the loop, we need to check for the LED value.
Thus the entire code will be:
const int MIN_FLASH_LENGTH = 6;

int _onBeforeIncrementing = MIN_FLASH_LENGTH;
int _amountOfFlashes = 0;

void loop()
{
    int ledValue = getLedValue(); // Use your code here
    if (ledValue >= 800)
    {
        _onBeforeIncrementing --;
        if (_onBeforeIncrementing == 0)  // Flash of enough length occurred
        {
            _amountOfFlashes++;
        }
    }
    else // Restart counting
    {
        _onBeforeIncrementing = MIN_FLASH_LENGTH;
    }
}

The code fragment
if (_onBeforeIncrementing == 0)
{
    _amountOfFlashes++;
}

can be reduced to:
 _amountOfFlashes += (_onBeforeIncrementing == 0) : 1 : 0;

Also note if you have more code to add, to use the name LED or LDR into the global variables for clearity.

For a single blink in LED, I'm getting multiple 800+ values. I want them to count as a single value until it drops below 800. So, the counter will increase by 1 if the values cross 800 until it drops below 800 again. So, I wanted to know if there is any way to make this as a range code where all the values will count as 1.

I appreciate your help, although I do have multiple LDR and LEDs to count, so I wanted to have something unified.

In that case use arrays for each led (global variable). This will cost 800 bytes if you make it a single (signed) byte.

By my understanding you want to count the values where your LED is on (800+ values in your case).
For this you can simply create an if condition where in you say if the value is greater than 800 increase counter by 1
int count = 0;

if(value>=800):
    count++

Here the variable value is the data you are printing on your serial monitor and count is your counter.
Also add the if condition inside the loop function and the declare the variable count = 0 outside the loop function

For a single blink in LED, I'm getting multiple 800+ values. I want them to count as a single value until it drops below 800. So, the counter will increase by 1  if the values cross 800 until it drops below 800 again.  So, I wanted to know if there is any way to make this as a range code where all the values will count as 1.

Exactly what I did above if you print count on the serial monitor you will see that count increases each time your value goes above 800. If you want to reset it just add else: count = 0 and count will reset to zero as soon as your value goes below 800

look, for a single blink i'm getting multiple 800+ values. if i , use  for ( values >800){ counter++;} my counter increases by 6-7 at a time for a single blink. using this condition because of multiple 800+ values it increases counter by a lot for a single blink. and I don't want that. i want to increase that by 1. i couldn't think about anything that would solve this.  you can refer to my question. i have added serial monitor output.


text:
Error Compiling for board Arduino Nano while using Adafruit GFX
Whys is this happening to me??
I have to meet a deadline please help!!
Here is my code.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for SSD1306 display connected using software SPI (default case):
#define OLED_MOSI   11
#define OLED_CLK   12
#define OLED_DC    9
#define OLED_CS    8
#define OLED_RESET 10
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);
void setup()
{
  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
}

  display.display();
  delay(2000);

  display.clearDisplay();

  display.drawPixel(10, 10, SSD1306_WHITE);

  display.display();
  delay(2000);
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  }
void loop()
{
drawLine(20,60,5,50,256);

}

The Error

C:\Users\hp\AppData\Local\Temp\ccyB6dO1.ltrans0.ltrans.o: In function
loop': C:\Users\hp\Desktop\Sunfox\Sunfox\BP_Plus_ECG\February_11\OLED_Testing_w_Adafruit\Test_2\Test_2/Test_2.ino:51: undefined reference to drawLine(unsigned int, unsigned int, unsigned
int, unsigned int, unsigned int)' collect2.exe: error: ld returned 1
exit status exit status 1 Error compiling for board Arduino Nano.

Kind Sir @MichelKeijzers what does that even mean?

I will make an answer.

@MichelKeijzers But I am using Adafruits built in library. I thought they would have done that for me.

I thought initially that you want to create your own function, but I made an answer to use the library instead of your own function.

Currently, you defined a forward declaration for drawLine, however I assume you want to call the method (function) inside display.
So change
drawLine(20,60,5,50,256);

into
display.drawLine(20,60,5,50,256);

And you can remove the forward declaration, because this method is already defined in the library.
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);

Note, if you call drawLine without an instance (which is display), then the linker tries to find the drawLine function which it cannot find, so you get a linker error (see ld returned in your error, together with undefined reference).


text:
generate and using a precompiled library ESP32
I would like to ask you how I can generate a dot_a file for a given library for ESP32? I want to replace my .cpp file with a precompiled .a in the Arduino IDE.
Is that possible? Can you please guide me?

Welcome, next time don't use bold text for an entire text. Also check the shift key.

https://arduino.github.io/arduino-cli/latest/library-specification/#precompiled-binaries


text:
Do Loop query not stopping
I am new to Arduino programming and I would like to ask a question.
Firstly apologies if this has been answered before and I understand if it gets locked if this has been answered elsewhere.
I am trying to get three LED's (red, amber, green) to loop 5 times (in a do loop).
for this I have created a integer variable (x) and initialised the variable to 0.
I then increase x by 1 each time.
However I cannot get them to stop looping when x is greater than 5. The program does work as expected for everything else (green LED lit, wait 1 sec, Yellow LED lit, wait 1 sec, red LED lit and then loop).
   //set LED pins
int greenPin = 13;
int yellowPin = 12;
int redPin = 11;

void setup()
{
  pinMode(greenPin, OUTPUT);      // sets the digital pin as output
  pinMode(yellowPin, OUTPUT);
  pinMode(redPin, OUTPUT);
}

void loop(){
int x = 0;

 do {
  digitalWrite(greenPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(greenPin, LOW);
  digitalWrite(yellowPin, HIGH);    // sets the LED off
  delay(1000);
  digitalWrite(yellowPin, LOW);// waits for a second
  digitalWrite(redPin, HIGH);    // sets the LED off
  delay(1000);
  digitalWrite(redPin, LOW);
 }
   while(x<=5); {
    x = x + 1;
   }
}

Move the incrementation statement inside the do while loop

Chrisl already gave the clue.
However, to add a comment with a code example I use the answer box.
In C you have more or less two kind of loops:

for
do / while

The first one is when you know beforehand how many iterations you have, the second when it depends on external input (e.g. when you expect a value acquired from within the loop).
In your case, you can better use the for loop, so you get:
for (x = 0; x < 6; x++)
{
   ...
}

What this does i:

Initializes x to 0 (first part of the for statement)
It checks the condition x < 5' (second part of theforstatement). If false, it continues with the first statement after thefor` body (after the } bracket).
It runs the body of the loop (inside the brackets)
It increases x (third part of the for statement)
It continues with 2

Also it is quite common for the condition to include the start element of the ragne (x = 0), but exclude the end element of the range (x < 6), thus it runs the last time with x == 5.

Thanks for the answers. As I am learning this I am trying to complete an excercise such as the one below:
Green LED On
Wait 1 sec
Green LED Off Yellow LED on
Wait 1 sec
Yellow LED Off Red LED on..
Do this for 5 iterations. It does state in the exercise that I must use a do while loop.
As I am specifically limited to the above conditions

@MrDigs ok if the exercise has that limitation, than do so. It's just not the most usual way in this case. You can try both for yourself to see the difference if you have time.


text:
Cannot make LCD & Gyro work together
I'm new to this so there are some poor methods in my code when I try to introduce the LCD into the loop. My issue is that the LCD delay and the servo delay are interfering with each other. How can I isolate them? I like the 50ms response for the servo. But I would like maybe a 200ms refresh for the LCD. But in their current state they are giving a very odd response if I have them both in the loop. The servo is spinning slower as though it's adding both delays. If I disable the LCD it all goes back to normal. Any ideas? Could someone please show me the correct method so I can expand in the future? Thanks!!!!
I've got this so far:
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

//SERVO
#include <Servo.h>
Servo microservo1;
int servo_pin = 8;

//MAPPED VALUES
int16_t AcXmapped, AcYmapped, AcZmapped;

//LCD
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//initializes the library

void setup(){

  //SERVO SETUP
  microservo1.attach ( servo_pin );

  //WIRE SETUP
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
  Serial.println("Transmission Line Initializing");
  delay(350);
  //print("3"); print("2"); print("1");
  Serial.println("3");
  delay(1000);
  Serial.println("2");
  delay(1000);
  Serial.println("1");
  delay(1000);

  //LCD SETUP
  lcd.begin(16,2); //setup LCD number of columns and rows
  digitalWrite(9,1); //can either go 0 --> 1 or LOW --> HIGH || turns LCD on or off ||
  analogWrite(6,70); //contrast setting for the text on the LCD
}

void loop(){

  //WIRE LOOP
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,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)
  Serial.print(" | AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  //Serial.print(" | Tmp =  "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

  //MAPPING the values from e.g. AcX to AcXmapped so they're better values for servo control.
  //set the AcX inside the map to negative if you want to invert the rotation of the servo.
  AcXmapped = map (AcX, -17000, 17000, 0, 180); //ROLL
  AcYmapped = map (AcY, -17000, 17000, 0, 180); //PITCH
  AcZmapped = map (AcZ, -17000, 17000, 0, 180); //YAW

  //SERVO LOOP
  microservo1.write(AcYmapped);
  //50 ms response between movements
  delay(50);

  //LCD LOOP
  lcd.setCursor(0,0); //set the cursor to (0,0)
  lcd.print(AcYmapped);
  delay(50);

  //EXTRA LCD
  lcd.noAutoscroll(); //turns off autoscroll
  lcd.clear(); //clears the screen for the next loop

}

First upload the msg errors you've get .
Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding.
I recommend you to use millis  instead of delays and use  multitasking code like freertos .

I fixed the error message BUT (bracket issue) my code is still giving me trouble. My delays are combining between the servo and the LCD. Do you know how I can isolate them so that I can give them both their own delay?

Use millis() if you think realtime data is necessary  . I noticed that you use lcd.noautoscroll() function under the extra lcd comment which is not necessary because the lcd by default doesn't scroll the characters. So try to delete that function . Now first try to delete all the delay and run your code then watch how the system behaves . Actually the servo take it's own time when it moves . During the movement of servo the arduino blocks every thing until the servo reach the desire angle then execute the rest in the loop .

the servo in this question is a hobby servo .... it is non-blocking because there is no position feedback ..... the code simply changes the PWM signal that is being sent to the servo ... the servo does the motion to the desired angle automatically

Don't use delay() at all. You need to refactor your code to record the value of millis() at the beginning of a time interval and then wait until the new value of millis() is greater by the desired interval. Do a google search on "Arduino blink without delay" for articles that discuss this coding technique. It's a fundamental of programming for a single-threaded microcontroller like the Arduino, and something you must learn to do if you're going to write anything of any complexity for the platform.


text:
connection for hall sensor 4 pin and arduino nano
I'm not from electronics background so I don't know what should be the connections. My Hall sensor has 4 pins(AO, GND, +, DO)
So, I have connected hall sensor pins to Arduino nano pins in this order(connection)
AO(Sensor) <-> A4(Arduino)   [Changed from A0 to A4]
DO(Sensor) <-> D4(Arduino)   [Changed from D0 to D4]
+(Sensor) <-> 5V(Arduino)
GND(Sensor) <-> GND (Arduino)

What should be pseudo code? So that if the magnet passes close to the sensor. Arduino should get the output & I'll blink the led on Arduino
This below is my code that I have written so far
int sensorPin = 4; // this is for sensor in analog pin 4
int buttonPin = 4; // we are looking for digital 4
int val;

bool flag = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin, INPUT); // defines digital pin 4 as input for LED
  Serial.begin(9600);
}

void loop() {
   int reading = analogRead(sensorPin);

   float voltage = reading * 5.0;
   voltage /= 1024.0;

  if(voltage > 3.0) {
   Serial.print(voltage); Serial.println("volts");
  }
   val = digitalRead(buttonPin);  // read data from digital Pin

   if(val == HIGH) // when the sensor detects a magnetic field
   {
      flag = !flag;
      if(flag){
         digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      } else {                 // wait for a second
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      }
      //delay(1000);                       // wait for a second
   }
   delay(100);
}

Expected output: It should turn On/Off the LED when voltage goes HIGH
Known issues: It works sometime. It doesn't work sometime. Also it works only when magnet is kept clone. Doesn't detect when I'm waving magnet close to the sensor

I guess you might have a bouncing button.  Have a search for "debouncing a switch", there are lots of different solutions.  The magnet has nothing to do with the LED, the analog reading is not used to trigger the LED in this code.

The board you have has two outputs - AO and DO (note, those are the letter O not the number zero - for output).
You can connect AO to any of the analog inputs on your board if you want to read a discrete analog value from the sensor.
You can connect DO to any of the digital inputs (or analog ones since they are also digital inputs) if you just want a simple "Something is there" signal.
The sensitivity of the "something is there" is controlled by the trimmer on the board.
The simplest way of doing what you want is to use DO and adjust the trimmer to suit. Then the sensor looks, to all intents and purposes, like a switch or a button (but you don't need the pull up / pull down resistor).  So you can leave AO disconnected.
Note that using D0 (zero) and D1 (one) on the Arduino is discouraged since they are connected to the USB interface and using them can affect your ability to upload sketches. It also means you cannot use any serial communication in your program.

yes done also please see my code. It works & doesn't work. Can you tell me why this strange behaviour. Detection should be very quick right?

Not with a 100ms delay in there it won't be - it will be slow.

Someone will probably post a comment saying this is not a code writing service, but I get the impression that you just need pointers, so here they are.
In the IDE you have an example on how to blink the LED, called blink, if you haven't already make yourself familiar with that.
I think there is an example on how to read from the analog pin, if not its int value = analogRead(A0);
Now print that value to the Serial monitor and see what happens when you start waving the magnet around.  The value will change say for 400 odd to 800 odd.
Now write an if statement that turns on the LED when the value you read is greater than (>) a certain value.
If you need any help on the code you need to write look in the Help->Reference section of the IDE, you might find the Bold words especially relevant :)
If you get stuck, post the code of how far you have got and people will help.

Hi @CodeGorilla can you please verify my code & what's wrong with the code. It's not behaving as expected


text:
How is a 41KB char array filling up 256KB of program memory?
I have an array of 41,400 elements of type char, which I am trying to put in program memory on a Mega2560. It should have 256KB of flash memory, but when I try to compile my sketch, it says the size of the array is too large. Each char is one byte, so this array should be 41,400 bytes. I'm at a loss as to how this can be too big.
I have also tried using an array of byte variables (should be the same thing) with no success. This is the only variable going into program memory.
Here is the relevant line:
const char Array[] PROGMEM = {0,19,21,25,27,27,27,29,24, ... };

I have included avr/pgmspace.h
Thanks in advance for any help.

What is the exact error message?

I included <avr/pgmspace.h> (that part of my question didn't display as I expected).

The error message is: error: size of variable 'Array' is too large

It seems AVR GCC limits the size of variables to 32K. Did you try with an array of 32767 chars, I guess it should work. If you try with 32768 chars, then it should show the error message.

I have just proved that in experimentation. 32767 is the limit for a progmem array.

I will try that. I will update when I have done that. It won't be until later today or Monday though. It is a shame they are limited to 32K when there is so much program memory.

00000108 l     O .text 00007fff _ZL5Array

Chances are the AVR architecture is not the right choice for your application.  There are plenty of 32-bit ARM parts with 32-bit ints permitting ordinary data pointers to flash offered at lower prices than an AVR with 256KB of flash.

The limitation here is the data type of the index of the array. That is int, and on an 8-bit system an int can hold a value in the range -32768 to 32767.
That means the biggest index number an array can have is 32767.
That limit cannot be changed. You're stuck with it.
However, there are some tricks you can use to expand it.  One is to use a larger data type than char and pack your data into it.  For instance, using unsigned int as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.
Using unsigned long (32 bits) would double that again.
It is then up to you to work out how to get to the individual bytes. Using the pgm_read_byte_*() function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...

Or an array of arrays. Or an array of structs. There's many ways of skinning this cat. But when it comes to reading it's just seen as a block of raw memory with no inherent type.

Agree, there is many different ways of doing this. Choose the easiest for you :). I gave you +1.

This makes sense. Thanks for the suggestions on workarounds.

You cannot have more than 32767 elements in one array. The reason is explained nicely by Majenko.
Solution for your problem is very simple, because you need only 41400 elements:
class MyArray
{
  static char array1[30000] = {...};
  static char array2[11400] = {...}; // rest

  public:
    char get(long index)
    {
      return index > 30000 ? array2[index - 30000] : array1[index];
    }

    char operator[] (long index)
    {
      return get(index);
    }
};

So you can use two arrays and depending of the index choose which one to use. I think it is faster than using array of ints, because you need to have division (by two, so it can be only shift right by one) and than again shifting to get the char. Also it is easier to use because for ints you need first to pack values (two values in one int).
This is just example code, fit it to your needs.

You're not putting the arrays in PROGMEM. And when they are, you can't access them like that - you need pgm_read_byte_near() etc.


text:
Works for 2-3 hrs, then LED blinks rapidly - Sleep Mode and Watchdog timer wakeup
I hope somebody can shed some light on this problem. I've researched the internet and forums and noticed that others have experienced similar problems.
This sketch runs fine for a couple of hours...it activates a relay approximately every hour, has a 10 second loop for an LED flash and then enters sleep mode. The watchdog timer is set to 8 seconds and wakes it up from sleep. I don't know why it works for a couple of hours and then gets caught into some sort of loop with the LED flashing rapidly. The requirements for disabling and resetting the watchdog might be the problem but I just don't know where to go next. I have seen a few discussions on memory leakage but not sure what that means or how to check for it. I also wonder if need to add any short delays after resets, etc. Additionally, when I press the reset button it has no effect on restarting the sketch. The sketch is running on a breadboard atMega328p-pu. Any help would be greatly appreciated.
ps. in the preview I noticed the # statements are not shown. They are the following libraries: avr/sleep.h, avr/power.h, avr/wdt.h
// In this sketch, the LED's flash every 10 seconds, then at each approximately 1 hour period, the relay is activated
// for 12 seconds.  It uses the WDT at its maximum 8 second delay to wakeup the circuit from low power sleep.

// Source: citizen-sensing.org/2013/07/arduino-watchdog/

// Check this out for good explanation on the Watchdog timer and code.
// http://www.leonardomiliani.com/en/2013/impariamo-ad-usare-il-watchdog-2/

// SEE NOTE at the end on known WDT reset issue

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value
float tCumm = 0.0; // Cummulative time
float hSet = 1.0; // Set relay activation once per hour
float hSet2 = 0.0; // Previous hSet value

// Create sleepNow function

void sleepNow() {

  wdt_reset();
  wdt_disable();

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Selecting the lowest power setting

// Set watchdog parameters
  MCUSR &= ~(1<<WDRF); // reset status flag
  WDTCSR |= (1<<WDCE) | (1<<WDE); // required to enable configuration changes
  WDTCSR = (1<<WDP0) | (1<<WDP3); // set the pre-scalar for 10, ie 8 seconds delay
  WDTCSR |= (1<<WDIE); // enable interrupt mode

// Disable the ADC
  ADCSRA &= ~(1<<ADEN); // Set bit 7 in ADC register to 1 to disable the ADC

// Ready for sleep
  sleep_enable(); // Enable sleep function
  sleep_mode(); // Go to sleep.  Will wake up upon interrupt via Watchdog timer in this sketch.

// disable sleep after waking up
  sleep_disable(); // Disable sleep for now after Watchdog timer interrupt activation
}

void setup() {

  pinMode(4, OUTPUT); // set pin 4 as output for LED
  pinMode(7, OUTPUT); // set pin 7 as output for relay
}

void loop() {

  // 10 second LED flashing + sleep loop

  for (int i = 0; i < 2; i++) {
  digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(200);               // wait for 0.2 sec
  digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
  delay(200);              // wait for 0.2 second
}

  // Add delay for total approx 2 sec
  delay(1200);

  // Start sleep / Low power / Watchdog interrupt
  sleepNow();

  // Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

  // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

  // Check to see if tCumm exceeds the user defined period (hSet) before activating relay
  if (tCumm > hSet) {

  // Activate relay for 12 seconds
    digitalWrite(7, HIGH);
    delay(12000);
    digitalWrite(7,LOW);

  // Reset hSet for next relay activation time
    hSet2 = hSet;
    hSet = hSet2 + 1.0;

    }
}

ISR (WDT_vect) {

}

NOTE from an online discussion: The problem is that a RESET does not turn off the watchdog timer once it has been turned on, and neither does the bootloader.  So you set things up to have the watchdog cause a reset in 15ms, and the reset occurs. Now the bootloader starts up, and starts its LED-flashing, and OOPS another 15ms has gone by with no one feeding the watchdog, and it resets again.  This repeats until a power cycle turns off the watchdog.
(This behavior is explicitly described in the ATmega datasheet...)

You should put the wdt_disable(); at the end of sleepNow. It doesn't make much sense to disable it right before setting it. I always put a distinct blinking pattern in the setup function, so I can detect when the Arduino is reset.

Looking at this declaration
int j = 1; // Elapsed time multiplication factor
int j2 = 0; // previous j value

and then this code
// Cummulative time in increments of 10 seconds
  tCumm = ((2.0 + 8.0)*j)/3600.;

 // Time multiplication factor. Used to increment tCumm. Never resets to zero.
  j2 = j;
  j = j2 + 1;

along with the associated comments seems to indicate that this variable "j" which is a (signed) int only increments without ever resetting, and is critical to the process of calculating the next time at which your code will act.
Your includes indicate that you are building for an AVR-based Arduino, and under the compiler used, an int on this platform is only 16 bits, meaning it has a range of -32768 to 32767.  Most modern platforms including this one use 2's complement representation, and most non-DSP platforms including this one do not use saturating arithmetic.  Therefore, incrementing a positive number beyond the positive limit will actually product a negative value.  Once your target time exceeds the maximum possible result of a calculation that has a positive int as an input, it becomes a target you will never be able to achieve.
Given the the amount of time your loop takes to execute, such integer overflow may not be not the issue you are hitting first, and does not seem perfectly correlated to your rapid-cycling failure mode.  But if your loop takes around 10 seconds, it seems like this would be an issue in a little less than four days.

Thx..j increments 1 every 10 seconds...so.if I use a 5 hour period for example, j gets up to only 1800...56060/10...yes it will definitely run into the limit in 3-4 days looks like and will have to be fixed for sure...but now it only runs 2-3 hours...I think there is something about my watchdog setup that I'm missing with the resets, disabling, etc but i'm just guessing...

You have a watch dog timer for 8 seconds and when you activate the relays you do a delay of 12.
This means that your watchdog will trigger when you activate the relays.

Do you think I need to add a wdt_reset() or wdt_disable(), or both, right after the sleepNow() command in the loop function?

Given that the watchdog appears to be operating in interrupt mode (with an ISR that does nothing) rather than reset mode, I'm not sure that this matters.  The routine which goes to sleep seems like it is attempting to establish a suitable watchdog state before doing that, so it's not clear how an additional wdt timeout during the delay would matter.  But watchdog usage definitely needs careful thought.

But watchdog usage definitely needs careful thought. indeed. And using it with delays is making it very hard to predict what is ongoing.


text:
Arduino String memory allocation
When a String variable is declared and modified inside a function, where does it go? To the heap(as string declaration is a part of dynamic memory allocation) or to the stack(as it is a part of function)? And is the space regained after the function goes out of the scope?
For example
void loop()
{
  Serial.println(foo("def"));
  while(1);
}

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

So, in this case, the variable "test" is declared in stack or heap? And this space is regained at the end or not?
Modified:
What if inside loop variable is declared like below?
String foo_test = F("def");
Serial.println(foo(foo_test));

In this case what will be the status of variables?

There is the String object, and then there is the character data referenced by that object. They don't live together.

It compiled fine and showed the output too. What's wrong with that?

@EdgarBonet    you mean to say that string object will reside in stack and the char data reference will stay in heap? Pardon for misunderstanding in previous comment.

The string object may reside in the function's stack, in the caller's stack, or in CPU registers. That's a matter of compiler optimization. For a simplified mental picture, you may assume it's in the function's stack. Everything should work “as if” that's the case.

@EdgarBonet     @Mikael@Michel Please see the modified

This is an excellent question to illustrate the amount of string copying and heap operations (malloc/free) going on when using the Arduino String class.
void loop()
{
  Serial.println(foo("def"));
  while(1);
}

The compiler will generate loop() something like this:
void loop()
{
  // String literal is stored in program memory. Needs to be copied
  // to temporary variable. This is done before main() is called.
  static const char temp0[4] PROGMEM = "def";
  static const char temp1[4];
  copy_from_program_memory(temp1, temp0);

  // The parameter to the call to foo() is actually a temporary String
  // variable constructed from the string literal. Storage is allocated
  // on the heap and the assigned from the value of the string literal.
  String temp2;
  temp2.constructor(temp1);

  // The return value of the call to foo() is a String that is passed
  // to Serial.println(). This is also a temporary String variable.
  String temp3;
  temp3.constructor(foo(temp2));
  Serial.println(temp3);

  // The String class destructor has to be called for the temporary
  // String variable so that the string values on heap are deallocated.
  temp2.destructor();
  temp3.destructor();
}

Note that each call to the constructor involves allocating and copying data to the heap.
String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

The function foo() needs to copy strings several times to perform the string concatenation. The operator+ will require an intermediate String copy.
Cheers!
PS: For more details please see the assembly listing below with the calls to String member functions. The compiler reduces inline member functions and reuses temporary local variables. Also the call to foo() is inlined. The member function reserve() is part of the constructor.
00000198 <main>:
 1de:   60 df           rcall   .-320       ; 0xa0 <String::reserve(unsigned int)>
 1fc:   50 d2           rcall   .+1184      ; 0x69e <strcpy>
 212:   46 df           rcall   .-372       ; 0xa0 <String::reserve(unsigned int)>
 230:   36 d2           rcall   .+1132      ; 0x69e <strcpy>
 248:   62 df           rcall   .-316       ; 0x10e <String::operator=(String const&)>
 26a:   1a df           rcall   .-460       ; 0xa0 <String::reserve(unsigned int)>
 27e:   0f d2           rcall   .+1054      ; 0x69e <strcpy>
 28e:   3f df           rcall   .-386       ; 0x10e <String::operator=(String const&)>
 294:   60 df           rcall   .-320       ; 0x156 <String::~String()>
 29a:   5d df           rcall   .-326       ; 0x156 <String::~String()>
 2a0:   5a df           rcall   .-332       ; 0x156 <String::~String()>

Bottom-line is that the String class uses a lot of instruction cycles and memory, and there is a potential risk of heap fragmentation and allocation failure.

I would expect copy_from_program_memory(temp1, temp0); to be done only once, by __do_copy_data(), from the C runtime.

Yes, that would also make temp1 static. Should correct that.

This is a nice explanation. Can you please suggest some good reference or articles to this memory issue?

Please see https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

See also http://www.nongnu.org/avr-libc/user-manual/malloc.html

And last the source https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.h and https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.cpp.

The truth here turns out to be a bit more complicated than the other answers express. There's more than one implementation of the Arduino String library, and some are better than others. Which one you get depends on which board you deploy to.
The newer code handles strings a whole lot more efficiently, particularly in terms of memory usage, and changes the whole dynamic around the answer to this question.
Compare the original version of the Arduino String library, the one for AVR, to the version for the ESP8266.
(As of writing this answer, these were this snapshot and this snapshot, respectively.)
Looking in particular at the functions like changeBuffer you can see that the ESP version contains something called "SSO" ("Small String Optimization") added with this PR here. Basically, for small strings—small enough to fit in the structure would otherwise be used to track the string buffer on the heap—it'll just store the string in that space (in the String object itself) instead.
In practice, this means strings smaller than 12 characters don't require memory allocation; they're stored on the stack inside the String object.
This is a pretty huge deal if you push around a lot of tiny strings, like in the example listed in the question. It means that the code works about as efficiently as you might hope, without problematic side-effects.

The string is an instance of an object, high likely keeping the administration like the offset and size (unless it is implemented as a 0-delimited string).
This is a local variable and will be stored on the stack and will be nicely removed after finishing the function.
The characters itself ("abc" ...) will be stored on the heap since this needs to be dynamic. This data will be freed by the string object after returning from the function and possibly when needed to relocate the string.
Normally a string instance will keep some memory allocated, when it is increased (or increased too much) the string content will be copied. This all happens in heap and 'holes' in the heap can occur by this.
That's why in a memory/time critical process it's best to allocate the string before hand, of course this is only possible if you know the (maximum) string size.

You said this is a local variable and will be stored in stack. Did you mean to say variable "test" will be stored in stack?But when string manipulation occurs i.e test += arg1; isn't it that the size of test will increase in heap or is it stack?

As Edgar already wrote, there are two items: the instance (keeping the administration), this is probably the pointer and possible the size of the string; this will be kept in stack. The memory allocation will never change. However, the characters itself are stored on the heap since this will change. When you add a character, depending on the implementation, possibly the whole string will be copied from one heap space to another location in the heap (using one more byte), and the pointer (stored in the stack) is pointing to the new allocated space in the heap.

Also you can use the F(" ..." ) way, this puts the fixed strings in flash memory (of course for altering strings this is not possible).

Yes, Explanation is good.


text:
Programming arduino using avrdude from command prompt
Out of curiosity, I am trying to upload a simple hex file to Arduino UNO using avrdude from windows command prompt.
As per this forum, I tried to implement it. But got stuck at

avrdude: ser_open(): can't open device "COM41": The system cannot find the file
  specified.

This command was directly imported from Arduino IDE verbose, and also it works fine when uploaded with Arduino IDE. I checked both the device and syntax are correct unless I would not be able to generate the hex file by Arduino compiler.
P.S. I have installed Winavr separately although it was pre-installed by Arduino
itself.
Here is a snapshot of the error
What could be the possible reason for it to fail? Please notify, if anything is missing.

I seems like you are using a different avrdude, as normally arduino uses the avrdude binary that is inside the arduino application folder. Also the avrdude conf-file is missing. So it looks to me like you have modified the command "directly imported" from the IDE.

@Gerben I downloaded the software Winavr and installed it separately. This is not the avrdude that was present inside arduino application folder.

After a lot of experiment, I finally made it. I got to know from some forum that when COM PORT is greater than 10, you have to put a '.' after COM PORT setting e.g. -P.COM41.
But, unfortunately that did not work. Then I changed the COM PORT to under 10 in device manager -> Properties -> COM Port Setting -> Advanced Setting; e.g. COM6.
Then it worked. At the time of flash just I have to press the RST button for once.
And now bingo!!
Still, I will try to find out why it didn't work with higher COM Port.

can't open device "COM41": The system cannot find the file specified.

This means there is no device at COM41. This may be due to 2 reasons:

You may not have connected your arduino. If this is the case then you please connect the arduino and retry
Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace COM41 with that and retry.

No, that is not the case here. As I said I have connected the Arduino and in the device manager it showed COM41. And I can easily program it from arduino IDE, but when I try to upload using Avrdude it shows this particular error.


text:
arduino quadcopter freezing while reading MPU6050/RC Receiver
I am trying to build an Arduino Flight controller. I have an MPU6050 (Gyroscope/Accelerometer) on board that is helping me configure my stabilization software. I also have my ESC's, and receiver plugged in to my Arduino. At some point during the code running, receiving and processing data from the Gyroscope and Receiver, the Arduino Uno freezes and I am not sure what is causing this problem. Any advice on how to fix this is greatly appreciated.
I am also getting FIFO overflows.
#include <Servo.h>
#include <Wire.h>
Servo esc1;
Servo esc2;
Servo esc3;
Servo esc4;
byte last_channel_1, last_channel_2, last_channel_3, last_channel_4, last_channel_5;
int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3;
int receiver_input_channel_4, receiver_input_channel_5;
unsigned long timer_1, timer_2, timer_3, timer_4, timer_5;
int reciever1, reciever2, reciever3, reciever4, reciever5;
int pastreciever1, pastreciever2, pastreciever3, pastreciever4, pastreciever5;
bool keycode;
int avg1, avg2, avg3, avg4;
int i;
const int avglen = 8;
int reciever1avg[avglen], reciever2avg[avglen], reciever3avg[avglen], reciever4avg[avglen];
int landingspeed = 1140;
int requestedspeed = 1400;
int autothrottle;
int motor1change, motor2change, motor3change, motor4change;
int yawchange, rollchange, nickchange;
int wait;
int set;
unsigned long interval=5000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
unsigned long timer = 0;

//#define printdata

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_YAWPITCHROLL
#define LED_PIN 13
bool blinkState = false;
bool dmpReady = false;
uint8_t mpuIntStatus;
uint8_t devStatus;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;
float euler[3];
float ypr[3];
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

float initialGyroX;
float initialGyroY;
float initialGyroZ;
const int autopilotkey = 1150;
int deg_x;
int deg_y;
int deg_z;
int requiredspeed;

void setup()
{
  //Arduino (Atmega) pins default to inputs, so they don't need to be explicitly declared as inputs
  PCICR |=  (1 << PCIE0);    // set PCIE0 to enable PCMSK0 scan
  PCMSK0 |= (1 << PCINT0);  // set PCINT0 (digital input 8) to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT1);  // set PCINT1 (digital input 9)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT2);  // set PCINT2 (digital input 10)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT3);  // set PCINT3 (digital input 11)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT4);  // set PCINT4 (digital input 12)

  pastreciever1 = 1058;
  pastreciever2 = 1058;
  pastreciever3 = 1058;
  pastreciever4 = 1058;
  wait=0;
  set=0;
  keycode = false;

   esc1.writeMicroseconds(1000);
   esc2.writeMicroseconds(1000);
   esc3.writeMicroseconds(1000);
   esc4.writeMicroseconds(1000);

   esc1.attach(9);
   esc2.attach(6);
   esc3.attach(5);
   esc4.attach(3);

  #ifdef printdata
  Serial.begin(115200);
  #endif

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24;
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif
    mpu.initialize();

    #ifdef printdata
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
    #endif
    devStatus = mpu.dmpInitialize();
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setXAccelOffset(-2580);
    mpu.setYAccelOffset(2567);
    mpu.setZAccelOffset(1920);
    //Serial.println("The timer has begun.");
   if (devStatus == 0)
   {
    #ifdef printdata
        Serial.println(F("Enabling DMP..."));
        #endif
        mpu.setDMPEnabled(true);
        //Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        #ifdef printdata
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        #endif
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        #ifdef printdata
        Serial.print(F("DMP Initialization failed (code "));
        #endif
        //Serial.print(devStatus);
        //Serial.println(F(")"));
    }
}

/*void ascend()
{
  Serial.println("Ascending.");
  for (autothrottle = landingspeed; autothrottle<requestedspeed; autothrottle++)
  {
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    delay(100);
    //gyro auto-level code??
    if ((avg3 != autothrottle)&&(avg3 < autothrottle));
    { }
    if ((avg3==requestedspeed)||(avg3>requestedspeed)||(avg1>1532)||(avg1<1472))
    {
      break; //go back to reciever input
    }
  }
}

void descend()
{
  Serial.println ("Descending.");
  for (autothrottle = avg3; autothrottle>landingspeed; autothrottle--)
  {
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    delay(100);
    //Gyro autolevel code??
    do
    { } while ((avg3 != autothrottle)||(avg3>autothrottle));
    if ((avg3 == autothrottle)||(avg3<autothrottle)||(avg1>1532)||(avg1<1472))
    {
      break; //go back to reciever input
    }
  }
}*/

void loop()
{
   print_signals();
   motor1change=0;
   motor2change=0;
   motor3change=0;
   motor4change=0;

   if (wait==0)
   {
    delay(20000);
    //XBee.write the weather
   }
   wait=1;
   if (set==6)
   {
    initialGyroX = (ypr[1] * 180/M_PI)-0.34;//X
    initialGyroY = (ypr[2] * 180/M_PI)-0.5;//Y
    initialGyroZ = ypr[0] * 180/M_PI;//Z
    #ifdef printdata
    Serial.print ("STORED:");
    Serial.print("\t");
    Serial.print (initialGyroX);
    Serial.print("\t");
    Serial.print (initialGyroY);
    Serial.print("\t");
    Serial.println (initialGyroZ);
    #endif
    }

    //Automatic Take-off
    /*if ((set>=6)&&(average3<1300)&&(average4<1300)&&(average2<1300)&&(average1>1700))
    {
      Serial.println("Ascending..");
      ascend();
    }*/

   //Nick (Go forward/backward)------------------------------------------
   if(avg2 > 1532)
   {
    nickchange = (avg2 - 1532)/2;
    motor1change=motor1change+nickchange;
    motor2change=motor2change-nickchange;
    motor3change=motor3change-nickchange;
    motor4change=motor4change+nickchange;
   }
   if (avg2 < 1494)
   {
    nickchange = (1494-avg2)/2;
    motor1change=motor1change-nickchange;
    motor2change=motor2change+nickchange;
    motor3change=motor3change+nickchange;
    motor4change=motor4change-nickchange;
   }
   //Yaw-------------------------------------------------------------------
   if (avg1 > 1510)
   {
    yawchange = (avg1 - 1510)/2;
    motor1change=motor1change+yawchange;
    motor2change=motor2change-yawchange;
    motor3change=motor3change+yawchange;
    motor4change=motor4change-yawchange;
   }
   if (avg1 < 1470)
   {
    yawchange = (1470 - avg1)/2;
    motor1change=motor1change-yawchange;
    motor2change=motor2change+yawchange;
    motor3change=motor3change-yawchange;
    motor4change=motor4change+yawchange;
   }
   //Roll------------------------------------------------------------------
   if (avg4 > 1532)
   {
    rollchange = (avg4 - 1532)/2;
    motor1change=motor1change+rollchange;
    motor2change=motor2change+rollchange;
    motor3change=motor3change-rollchange;
    motor4change=motor4change-rollchange;
   }
   if (avg4 < 1472)
   {
    rollchange = (1472 - avg4)/2;
    motor1change=motor1change-rollchange;
    motor2change=motor2change-rollchange;
    motor3change=motor3change+rollchange;
    motor4change=motor4change+rollchange;
   }

    if (!dmpReady) return;
    while (!mpuInterrupt && fifoCount < packetSize) {
       }
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();
    fifoCount = mpu.getFIFOCount();
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        mpu.resetFIFO();
        #ifdef printdata
        Serial.println(F("FIFO overflow!"));
        #endif
    } else if (mpuIntStatus & 0x02) {
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
            //Print Data
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            /*Serial.print("XYZ:\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[2] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[0] * 180/M_PI);*/
        //#endif

//Stabilization----------------------------------------------------------------------------
if ((keycode==true)&&(avg3>autopilotkey))
{
   //X Axis----------------------------------------------------------
  if ((ypr[1]* 180/M_PI)>(initialGyroX + 2))
  {
    deg_x = initialGyroX - (ypr[1] * 180/M_PI);
    requiredspeed = (-4.5*deg_x);
    #ifdef printdata
    Serial.print ("GyroX++: ");
    #endif
    //Serial.println(requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
  if ((ypr[1]* 180/M_PI)<(initialGyroX - 2))
  {
    deg_x = initialGyroX - (ypr[1] * 180/M_PI);
    requiredspeed = (4.5*deg_x);
    #ifdef printdata
    Serial.print("GyroX--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
  //Y Axis------------------------------------------------------------
  if ((ypr[2] * 180/M_PI)>(initialGyroY + 2))
  {
    deg_y = initialGyroY - (ypr[2] * 180/M_PI);
    requiredspeed = (-4.5*deg_y);
    #ifdef printdata
    Serial.print ("GyroY++: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
   if ((ypr[2] * 180/M_PI)<(initialGyroY - 2))
  {
    deg_y = initialGyroY - (ypr[2] * 180/M_PI);
    requiredspeed = (4.5*deg_y);
    #ifdef printdata
    Serial.print ("GyroY--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
  //Z Axis--------------------------------------------------------------
  if ((ypr[0]* 180/M_PI)>(initialGyroZ + 4))//decrease
  {
    deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
    requiredspeed = (-1*deg_z);
    #ifdef printdata
    Serial.print ("GyroZ++: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
  if ((ypr[0]* 180/M_PI)<(initialGyroZ - 4))//increase
  {
    deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
    requiredspeed = (1*deg_z);
    #ifdef printdata
    Serial.print ("GyroZ--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
 }
}
  motor1change=constrain(motor1change, -100, 100);
  motor2change=constrain(motor2change, -100, 100);
  motor3change=constrain(motor3change, -100, 100);
  motor4change=constrain(motor4change, -100, 100);
  #ifdef printdata
   //Elevation------------------------------------------------------------
   Serial.print ("Motor Changes (1-4): ");
   Serial.print (motor1change);
   Serial.print (" ");
   Serial.print (motor2change);
   Serial.print (" ");
   Serial.print (motor3change);
   Serial.print (" ");
   Serial.println (motor4change);
  #endif
   if (avg3>1150)
   {
   esc1.writeMicroseconds((avg3+7)+motor1change);
   esc2.writeMicroseconds((avg3+7)+motor2change);
   esc3.writeMicroseconds(avg3+motor3change);
   esc4.writeMicroseconds(avg3+motor4change);
   }
}

//This routine is called every time input 8, 9, 10 or 11 changed state
ISR(PCINT0_vect){
  //Channel 1=========================================
  if(last_channel_1 == 0 && PINB & B00000001 ){         //Input 8 changed from 0 to 1
    last_channel_1 = 1;                                 //Remember current input state
    timer_1 = micros();                                 //Set timer_1 to micros()
  }
  else if(last_channel_1 == 1 && !(PINB & B00000001)){  //Input 8 changed from 1 to 0
    last_channel_1 = 0;                                 //Remember current input state
    receiver_input_channel_1 = micros() - timer_1;      //Channel 1 is micros() - timer_1
  }
  //Channel 2=========================================
  if(last_channel_2 == 0 && PINB & B00000100 ){         //Input 10 changed from 0 to 1
    last_channel_2 = 1;                                 //Remember current input state
    timer_2 = micros();                                 //Set timer_3 to micros()
  }
  else if(last_channel_2 == 1 && !(PINB & B00000100)){  //Input 10 changed from 1 to 0
    last_channel_2 = 0;                                 //Remember current input state
    receiver_input_channel_2 = micros() - timer_2;      //Channel 3 is micros() - timer_3
  }
 //Channel 3=========================================
  if(last_channel_3 == 0 && PINB & B00001000 ){         //Input 11 changed from 0 to 1
    last_channel_3 = 1;                                 //Remember current input state
    timer_3 = micros();                                 //Set timer_4 to micros()
  }
  else if(last_channel_3 == 1 && !(PINB & B00001000)){  //Input 11 changed from 1 to 0
    last_channel_3 = 0;                                 //Remember current input state
    receiver_input_channel_3 = micros() - timer_3;      //Channel 4 is micros() - timer_4
  }
  //Channel 4=========================================
  if(last_channel_4 == 0 && PINB & B00010000 ){         //Input 12 changed from 0 to 1
    last_channel_4 = 1;                                 //Remember current input state
    timer_4 = micros();                                 //Set timer_5 to micros()
  }
  else if(last_channel_4 == 1 && !(PINB & B00010000)){  //Input 12 changed from 1 to 0
    last_channel_4 = 0;                                 //Remember current input state
    receiver_input_channel_4 = micros() - timer_4;      //Channel 5 is micros() - timer_5
  }
}

//Subroutine for displaying the receiver signals
void print_signals()
{
  //Constrain
  reciever1 = constrain(receiver_input_channel_1, 1000, 2100);
  reciever2 = constrain(receiver_input_channel_2, 1000, 2100);
  reciever3 = constrain(receiver_input_channel_3, 1000, 2100);
  reciever4 = constrain(receiver_input_channel_4, 1000, 2100);
  reciever5 = constrain(receiver_input_channel_5, 1000, 2100);

  set=set+1;

  //AVG 1-4-----------------------------------------------------
  for (i=0; i<avglen-1; i++)
  {
    reciever1avg[i]=reciever1avg[i+1];
  }
  reciever1avg[avglen-1]=reciever1;
  avg1=0;
  for (i=0; i<avglen; i++)
  {
    avg1+= reciever1avg[i];
  } avg1/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever2avg[i]=reciever2avg[i+1];
  }
  reciever2avg[avglen-1]=reciever2;
  avg2=0;
  for (i=0; i<avglen; i++)
  {
    avg2+= reciever2avg[i];
  } avg2/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever3avg[i]=reciever3avg[i+1];
  }
  reciever3avg[avglen-1]=reciever3;
  avg3=0;
  for (i=0; i<avglen; i++)
  {
    avg3+= reciever3avg[i];
  } avg3/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever4avg[i]=reciever4avg[i+1];
  }
  reciever4avg[avglen-1]=reciever4;
  avg4=0;
  for (i=0; i<avglen; i++)
  {
    avg4+= reciever4avg[i];
  } avg4/=avglen;

  //Activate Autopilot
  if ((avg1==pastreciever1)&&(avg2==pastreciever2)
    &&(avg3==pastreciever3)&&(avg4==pastreciever4)&&(avg3>autopilotkey))
  {
    keycode=true;

  } else {keycode=false;}

  pastreciever1 = avg1;
  pastreciever2 = avg2;
  pastreciever3 = avg3;
  pastreciever4 = avg4;

What does the Arduino IDE say about memory usage when building the sketch?

Sketch uses 18,698 bytes (57%) of program storage space. Maximum is 32,256 bytes.
Global variables use 597 bytes (29%) of dynamic memory, leaving 1,451 bytes for local variables. Maximum is 2,048 bytes.

Hint: Can "do { } while ((avg3 != autothrottle)||(avg3>autothrottle));" lock up?

I commented those two voids out, and it is still freezing. I believe it is some sort of track overflow.

I am receiving data from both the MPU6050 and my Hobby-king RC Receiver simultaneously  .

This can happen in I2C sometimes. Basically the controller asks the sensors for data but there may be a bit error in the address. If so the sensor thinks you are talking to another chip, meanwhile your I2C master code waits for a reply, forever.
To fix this problem I would recommend the use of a watchdog timer. You can find the many examples online of how to set this up.


text:
Serial1 is not reading the Xbee on a Arduino Due
I am trying to test simple communication between a Xbee on my Arduino Due and a Xbee linked to XTCU. I attached jumper wires from RX and TX to RX1 and TX1 (Serial 1 hardware port) but I cannot send or receive data between the Xbees. I tested the Xbees previously with an Arduino Zero talking to the XTCU and it worked flawlessly.
Extra information: I am using a Xbee Shield on my Arduino Due (as shown in the picture)
char c,d;

void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);

}

void loop()
{
// put your main code here, to run repeatedly:
if (Serial1.available())
{
 c = Serial1.read();
 Serial.print(c);
}
else if (Serial.available())
{
 d = Serial.read();
 Serial1.print(d);
}

}

My wiring is attached. What am I doing wrong?

Are you using an Xbee shield? And doesn't it connect to pin 0 (RX) and 1 (TX)?

@MikaelPatel  Yes, I am using a Xbee Shield. Yes, but since there is no SoftwareSerial library, I have to use one of the multiple hardware serial ports to read data from the Xbee, hence the jumper wires.

So you have cut the pins from the Xbee Shield? Pin 0 and 1 are not connect to the corresponding pins on the due?

The pins used for SoftwareSerial are pins 2 and 3 (according to the documentation of the shield). I guess you could put them in input mode and connect to a hardware serial port (Serial1).

@MikaelPatel Actually, my jumper wire setup was correct but I had to flick a switch on the shield to communicate via UART. Thank you for your responses, though! I have another question (in the answers). I'm probably missing something simple in my code.

I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.
Extra information: The serial monitor solely prints out received data.
I attached an example.

Has there been any update on this problem?  Your post has been incredibly helpful as I've been looking for ways to use a Due and an Xbee (specifically with the Sparkfun Xbee shield).
I haven't been able to solve this entirely, but I've noticed a few things;
First of all if you delete the second Serial.available, it does not change the functionality of the code at all, still works the same way.  I believe this has to do with the hardware Tx and Rx pins on the Due.
What seems to be happening is that if you use XCTU to send information to the Due, XCTU sends the data out, in which the Due receives it.  Then it bounces back and seemingly resends it from the Due to XCTU again, without displaying in the serial monitor.  I'm probably wrong in my observations but very curious if there's an answer to this.  Hope to hear back from someone soon.  Thanks!
EDIT
Upon thinking about it, I figured out a work around.  As stated in one of the comments earlier, you still have the shield's Rx and Tx pins connected to the Due.  This is what's giving you double values on XCTU.  The Due receives the input from XCTU and immediately sends it back out to XCTU.  A simple fix is bending the Rx and Tx pins out slightly so they are not connected to the Due but all of the other pins remain in place.  I hope this ends up being helpful!

There is no second Serial.available the other one is Serial1.available with 1 at the end.

Yes, I figured out that work around a few weeks back! Sorry I didn't say anything!