text:
HCSR04 Sensor without delay
I've made a code to make a stepper work together with a HCSR04 sensor. The problem here is that the sensor has to use a delay in order to work. This delay messes with the smootness of the stepper.
If I remove the code for the sensor the stepper runs verry smooth, adding the sensor code causes the stepper to run 'shaky'.
The code:
int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2); //**problem**
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5); //**problem**
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm:");
 Serial.print (distance);

//eigen creatie
if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(1000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(3000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(3000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

else
{
 velocity();
}

}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}
 }

Have you searched for other libraries or example code for this particular sensor?
I found this NewPing library that claims to have been developed to fix poor performance of such modules due to poor timing methods.

Yes, the https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home#!event-timer-sketch has a non-blocking timer-interrupt based example.

I have been looking into the newPin library but I cannot find a function that resolves the problem. Still, I am going to look into the NewPin library. It seems to promising. But I quess it is not going to completly fix my delay problem.

You only have a single thread of execution of an Arduino.  So you have limited options:

Live with it.
Use two Arduinos.
Use a microcontroller with 2 cores.
Interrupts

2 Is possible, you could have a slave mcu to drive the motor and control it over I2C.  You will still have contention when you are driving the I2C bus, but you can time that so it is not when you are scanning.
3 Is a very similar solution to 2, but is all in one chip.

You MIGHT be able to use interrupts which will let processing continue whilst you are waiting for something to occur.  I can't remember if the Arduino has timer interrupts, if it doesn't an external source could generate the interrupts and changes the state of the lines.,

Hi Matt, Interesting options. I do have a second Arduino Uno laying around for this project. Haven't heard of I2C but I will look into it.

You could also use Serial to talk between the two devices, but you can't use the main serial port on an Uno, because that will make debugging difficult and people keep reporting issues with software serial.


text:
Does the SIM800L works in the US?
I want to know if the SIM800L works on US soil? I can´t get it to work on the H2O network! Does it work wit ATT or I only need the APN settings? If so what are the commands for data connection and configuration? Does the SIM800C works then?

I wanted to post an update in April 2021 on the status of this question.
The SIM800L will work in the US, but T-Mobile is the only carrier that it can interface with. AT&T shut down its compatible towers in 2017. T-mobile will shut down its 2G network at the end of 2022.
So, the SIM800L is only good for another year and a half. Maybe you're better off finding a different module!

Both SIM800C and SIM800L (you mention both modules in your question) are compatible with the US GSM networks. It is not possible for me to tell if H2O or AT&T have GSM coverage whereever you are trying to use the module. AT&T is planning to shut down their GSM network by the end of 2016. If you issue the AT+COPS=? command, the module will list all available networks at your location.
Documentation on the commands required to handle voice calls, SMS or internet connections can be found in the 'SIM800 Series AT Command
Manual'.

Is that so... Then I should be moving to CDMA? or is there another network available? What chip could be useful? I´m planning to deploy this in a long term! Btw I did search for all available networks but none of them appeared and the signal was low or none existent! Why? No GSM/GPRS? I activated both
I appreciate your help!

Why don't you simply do a network search with a regular cell phone? It will list which operators and which network types are available where you are. There are plenty of cellular modems for 3G and 4G networks as well, but they are quite a bit more expensive than the GSM modules.

Well there are plenty of networks around and I can confirm that H2O use AT&T network towers and the GSM network is present on all carriers. I saw that GPRS with 3g is available too but to my understanding it´s part of the GSM network, right?
I saw different types of connections around the web... Do I need to use the reset pin? And what is the DTR pin? I got a battery at 3.7v with 2000mA connected so there is no problem with the ESD function of the chip

Does the SIM800L supports 3g? I mean from what I saw it does support 3g

As far as I know 2G and 3G is still around however ATT and Verizon are not taking on anymore subscribers for 2G and 3G. However you might still could use a 3rd party such as ting.

source: Stack Exchange

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

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

sort: votes


text:
ArduinoISP external programmer produces verification error?
I am using an ArduinoISP external programmer to upload a sketch to an Arduino MEGA.
I set the processor type to MEGA 2560, and use Ctrl-Shft-U to upload using a programmer. My programmer is set to ArduinoISP under tools>Programmer.
So far, I haven't been able to get the sketch to upload without a verification error. Worse, the programmer made it far enough in the upload process to overwrite the bootloader. Trying to re-upload the boot loader ("Burn Bootloader") also fails. The verbose error output is below with the exact error at the bottom.
A previous post suggested that code with a lot of 0xFF statements in it would fail. I have none.
Following a suggestion in the comments, I unsoldered the power over ISP programmer jumper (SJVCC) on my ArduinoISP. I powered the Arduino using the power jack; however, I got the same verification error.
I have also tried updating the software the the latest version (1.6.12), but that also does not seem to work. I may try to downgrade the software, but this all seems a little futile. Other forums don't seem to have a good answer for similar verification problems.
Is this a known problem? What can I do to fix it? What is particularly frustrating is that the problem occurs intermittently, ocassional after a computer reboot, it will upload successfully one time.
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : arduinoisp
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

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

     Programmer Type : USBtiny
     Description     :
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be     performed
     To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file     "C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex"
avrdude: writing flash (9334 bytes):

Writing | ################################################## | 100% 10.71s

avrdude: 9334 bytes of flash written
avrdude: verifying flash memory against     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Te    nsion_wo_Averaging.ino.hex:
avrdude: load data flash data from input file     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex:
avrdude: input file                     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex contains 9334 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 7.34s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0600
         0xdd != 0x4a
avrdude: verification error; content mismatch

avrdude done.  Thank you.

How is the board powered? 2) Did you try downloading the zip of Arduino IDE 1.5.7 and then trying. (might be waste of time but I hear sometimes older versions work better)

The ArduinoISP provides power to the board, but I have tried it with a USB cable plugged in too.

Haven't tried the older version yet. Will work on that too.

Did you put the jumper back on the ISP when trying external power?

No, the ArduinoISP doesn't have jumper pins, just jumper pads. I didn't change any of the soldering.

https://www.arduino.cc/en/Main/ArduinoISP

By default, my board had the SJVCC jumper soldered over, indicating it should be able to power the board.

I tried desoldering the SJVCC pin, and powering over USB while programming. Same problem.

Yes I read the ISp article on Arduino.cc. It mentions verification errors and says to power via external power so having a soldered power jump on the ISP might be an issue.

I updated my question with the latest tests.

Did you try older arduino ide? The tools have changed. If that doesn't work try using the Device Programming Tools in Atmel Studio to burn the bootloader

Similar to:  https://arduino.stackexchange.com/q/44965/19409 https://arduino.stackexchange.com/q/59837/19409 https://arduino.stackexchange.com/q/52798/19409

I'm having the same problem with my USBtinyISP. It worked great for about a year and then one day it started giving verification errors on every board that I own. I tried a new ICSP cable, a different PC, several Arduino boards and it consistently corrupts flash (verification errors!). The board seems to work fine as far as my PC is concerned. I've ordered another USBtinyISP, hopefully this next one will last longer than the first.

Sounds like you have a bad Arduino ISP board.
I've had limited success restoring bootloaders on some Arduinos with my bad USBtinyISP programmer by connecting a 9V power supply to the Arduino in addition to the 5V that the ICSP cable provides.  Worth a try.
Note that back when my USBtinyISP was working properly I didn't need to attach 9V, the 5V from the ICSP cable was all the power needed.

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


text:
How do I measure watts without a CT clamp?
I'm trying to build an "IoT" project for home that will in effect create a smartplug. I'd like to add the capability to measure the watt usage of the plug (and whatever's connected to it). I'd like to not use a CT clamp for this purpose, and I was hoping someone here can help.
I have a 220 V mains connection and I'd like to measure the watts used by a connected appliance to the smart plug is a small as possible form. CT sensors are too big for this purpose.
Thanks.

You don't need a clamp if you are building the plug.  What's wrong with a Current Transformer? Mouser sells a 1000:1 CT for less than 6$ that you could put in-line with one of your plug's leads.

I've seen a lot of people connect an Arduino to an existing power-meter, like e.g. a Kill-A-Watt meter.

You can't use a CT sensor to measure power.  CT sensors measure current.  Measuring Watts is the correct unit if you want to know the rate of energy consumption (power) from an outlet.
Response to a Comment: There are consumer devices that cost only $12.95 that might be ideal, if the only usage scenario is to compare various devices for steady state power draw and you are fine with 3% (1.5 digit) accuracy.  For the 220 VAC (whether split phase or single phase) you would need to gang two of them together appropriately.  These plug-outlet designs are nicely miniature, but will not support checking past values, providing feedback to a control system, or Wattage plotting against date, time of day, or tay of week.
Measuring of Wattage accurately (to two or three significant digits) is not trivial if the 220 Volt source is an AC power grid, thus the length of this answer.
The basic EE formula for power is P=IV for DC, meaning power is the product of current and voltage.  But you can't just go with Watts = 220 X current and expect any more than one significant digit of accuracy.  Grid Voltage may not be a clean sine wave and may vary five or ten Volts under normal conditions.
If you want more than one digit of accuracy, you'll need to calculate RMS (root mean square) power in Watts by sampling both Voltage and current and using the AC principles that extend the simple P=IV relation.   I don't know if you have knowledge of what electrical engineers call RMS.  In case you don't, the articles in the result set of This Search [1] may be helpful.
Let's hypothetically say you are considering doing the work necessary to get the two or three significant digits of accuracy in determining power consumption.  To get a sense of what that would entail, here's some information on doing that properly.  You will want to consider line voltage fluctuation, reduce your noise levels, protect your Arduino board from over-voltage, and follow electrical code reasonably well.
The below measurement fixture design is not small, but it could be miniaturized.  Unfortunately the design of a miniaturized version is large project FAR outside of the scope of an answer in this forum.  You may be one of those that likes the challenge, so I'll share a design for a larger version and leave it to you or other answering parties to think of a miniaturization that meets all these other reasonable goals.
Off the shelf parts to fabricate a full sized power measurement fixture to interface with an embedded board like the Arduino Due, for example:

Two electrical boxes
A length of electrical conduit at least 50 cm long
Electrical hardware to connect the two boxes and secure the AC cord leading to the plog and to the devices being powered.
Two lengths of 2-conductor 18 AWG shielded twisted pair cable with at least 500V rating
Code compliant AC cabling
Wire nuts
Box for the buffering circuit
A good quality digital Voltmeter with RMS AC as one of the options

Fabricate this way, but using proper code-compliant electrical practices in addition to these basic instructions for the main circuits:

Connect the plug to one of the boxes with properly rated AC cord.
Connect the two boxes with the conduit and properly rated power and return wires (white and black).
Connect the second box to the device
In each box, connect the 2 conductors of the shielded twisted pair in parallel to the AC circuit passing through the box with the wire nuts.  You must leave the shields of the two twisted pair lengths isolated (not connected to the box or the ground wire in the AC circuit.
Bring both twisted shielded pairs into the buffering circuit box.

The buffering circuit would condition each of the two AC voltage in three stages.

Surge protector
Resistor divider (see other Arduino articles for this)
Zener diode to further protect the A-to-D converter on the board

The Zener diode and the resistor divider would drop the voltage from 400 V down to below the max voltage of the Arduino board, which any of the voltages might be relative to the ground potential on the Arduino board under certain conditions.  The Arduino Due might be a good choice, because of multiple built in true A-to-D channels and the higher accuracy (digits resolution) than most other Arduino options.
The output of the box for each of the FOUR voltages would be connected to FOUR analog inputs.

Vph = the hot (black) coming from the plug
Vpr = the return (white) coming from the plug
Vlh = the hot (black) going to the load (devices to be powered)
Vlr = the return (white) going to the load

In the software you would probably want to measure the above four voltages in immediate succession (no delay between the four analogRead calls) every millisecond for a second, which will capture 60 cycles of data in 1,000 samples, enough to get three significant digits of accuracy in your power measurement.  The 60 samples of 4 channels can be thought of as 1,000 vectors of 5-dimensional data.  The fifth dimension is the time offset in milliseconds.
The software goal would be to calibrate the conversion of the 4 by 1,000 element array of analogRead integers to a 2 by 1,000 element array of doubles that represent instantaneous Voltage and current. Then power in Watts can be calculated from the Voltage-current data set.
When dealing with the 1,000 sample vectors, your loops will start with "for (int index = 0; index < 1000; ++ index) { ...".
You will need to convert your digital values representing the Voltages coming from your resistor divider to physical units.  These are the operations you would do on each sample.

V = Cv * (Vph - Vpr)
I = (Cih * (Vph - Vlh) - Cir * (Vlr - Vpr)) / R

V and I are the doubles that represent instantaneous Voltage and current respectively.
Cv, Cih, Cir, and R are also doubles. They are the calibration constants to convert the analogRead values to line voltages and currents.  A typical way to calibrate their values is to measure the RMS voltages across the three node pairs represented by each subtracted voltage pair in the inner parentheses above and the current, using some constant load.  A good load option would be some non-digital device that is fully warmed up and in some steady state.
From the voltages and currents and the digital values acquired from the four analog channels in the Arduino, with some algebra skill, one can determine the scaling factor C for each of the three cases, by dividing: (V1 - V2) / V, where V1 and V2 are the RMS values measured with the digital Voltmeter and V is the calculated RMS voltage from the samples.
R can be calculated by dividing the Voltage and current values V/I in accordance with the principles discussed in the articles referenced above.
Once you have calibrated your measurements for V and I in your block of 60 samples, the articles above give you some direction as to how to calculate your power in Watts RMS in a loop.
[1]: Search for "calculating rms watts from samples of voltage and current" via Google.


text:
Can I connect a servo directly to arduino uno without a transistor?
I am going to mount an ultrasonic sensor on the servo.

Please post a link to the servo you intend to use.

The data pin you can drive directly from an arduino. The power, you have to drive from something better.

What does a sensor have to do with the question? And for that matter, what is the question about? Connect what to what? Are you talking about the power or the signal?

The Arduino's GPIO pins can drive the signal of most model servos directly, without any extra transistors.
Driving a model servo signal input is not the main problem with driving servos from an Arduino.
The main problem is trying to use the Arduino's power supply to power the model servo. With many model servo's, the amount of current the model servo needs to start, or when it is almost stopped is so big that the Arduino's power supply can't maintain 5V. As the Arduino's power supply voltage drops, the Arduino often gets reset, and the program restarts from setup.

You need a supply that can deliver current spikes and longer durations of higher current. Using  capacitors may help for the spikes.


text:
Common/standard library and/or protocol for Arduino to be I2C slave for driving NeoPixel
I would like to control a string of WS2812/NeoPixels from a SBC like a BeagleBone or C.H.I.P. I realize someone has gone through the trouble to come up with a way to drive the WS2812 string from a BeagleBone directly with the PMU, but I would like to have an Arduino like a Pro Mini do the signal generation, while the SBC would direct the Arduino what to display.
I found the node-pixel setup with I2C backpack on the arduino, but it requires on the SBC side NodeJS, Johnny-Five and other libraries that I would have no other use for. It seems overkill.
Is there some commonly used protocol over I2C for controlling NeoPixels (with the arduino being the I2C slave), or will I be better off developing my own simple protocol?
On the SBC side, I would likely be coding either in C/C++ or Python.

You could use APA102 led strips, they use an "spi-like" protocol (see datasheet) which is much less time-restrictive. Using the right parts is IMHO a better solution than adding more parts to get something working.

Plus, NeoPixel's timing constraints are so bad that you can't even generate the pixels on the go. You need to put the whole strip in memory, before writing it. The APA102 led strips can be "streamed", pixel by pixel. So you can "calculate-send, calculate-send, calculate-send" to theoretically drive limitless strips witouth using limitless memory ;)

@Paul wrote: “NeoPixel's timing constraints are so bad that you can't even generate the pixels on the go”. No, they aren't so bad. See: NeoPixels Revealed: How to (not need to) generate precisely timed signals.

If it helps simplify your project, I wrote a small library that outputs to NeoPixels using the SPI hardware. The code to send one byte is simply this on the Atmega328P:
void sendByte (byte b)
  {
    // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
    //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
    for (byte bit = 0; bit < 8; bit++)
      {
      if (b & 0x80) // is high-order bit set?
        SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
      else
        SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
      b <<= 1; // shift next bit into high-order position
    } // end of for each bit
} // end of sendByte

One pixel is 3 bytes (green / red / blue):
void sendPixel (const byte r, const byte g, const byte b)
  {
  sendByte (g);        // NeoPixel wants colors in green-then-red-then-blue order
  sendByte (r);
  sendByte (b);
  } // end of sendPixel

The timing issue arises because the pixels "latch" if around 9µs elapses with no data. Thus you either precompute the data to be sent, or decide what to send very quickly.

Under the circumstances, using I2C, you would need to precompute the data, these is no way you could receive I2C on the fly and send it out to the Neopixels with them latching.

Is there some commonly used protocol over I2C for controlling NeoPixels ?

Not that I am aware of. I suggest you either send the pixel data (which would be a lot, and have to be broken into smallish packets), or send a "pattern number" and have the receiver generate the data.
Be aware that the standard I2C library has a 32-byte buffer so you can't send hundreds of bytes in a single I2C transaction.

Fortunately, this particular project is only using 3 to 5 LEDs and I can have the Arduino hold pre-computed patterns to be selected by the host controller. [I am using FastLED for the actual NeoPixel signalling.]

You should break your project up into smaller parts.

Consider using other led strips, that can be driven directly. Consider using ready-made parts or opensource code (google).
Make an Arduino drive a NeoPixel Ledstrip. (Check adafruit libraries/NeoPixel guide)(Sanity/wiring check)
Communicate with Arduino and Beaglebone over I2C. Try sending "Hi" and respond "Ok".
Think of a protocol, how to indicate start/stop of a message.
Send the "color bytes" using said protocol.
Unpack the color bytes and put them in a pixel array (See NeoPixel library).
Run "ledstrip.show();”

Please atleast try to do these steps. If one fails, you can create a question with details on what you have tried or what isn't working.
Maybe "nodepixel" already has the Arduino code for you. You then only need to know what bytes to send over I2C, which you can do with any programming language that supports I2C access on your platform.

Appreciate the response, but I have success on steps 1, 2, 3 and 7. Steps 4, 5, and 6 constitute the heart of my question -- is there a popular/standard/common protocol, or is it simply better that I "think of a protocol" myself.


text:
How to reprogram Arduino if USB port is already in use?
I'm developing a keyboard emulator using Digispark Pro (based on Arduino) which uses USB port as the keyboard interface. I haven't programmed it yet because I doubt how should I recognize the chip to Arduino IDE again using USB port after programming the board.
So my question is, how to reprogram Arduino if USB port is already recognized as keyboard HID?

Is the Arduino running with it's bootloader, or it is programmed with the target app only?

@EugeneSh. I haven't programmed it yet. Digispark Pro has Arduino bootloader by itself.

@joware you can make low speed  USB keyboard host in software mainly with arduino ng oe better

@yabbadabba I already bought digispark pro. My only problem is reprogramming the board.

If I'm correct, after a reset, it will first enumerate as an Digispark in the bootloader. Then after a timeout, it will run the main program and enumerate as a keyboard. The only problem might be that you'd have to manually press the reset button when you want to program the chip.

@Gerben Thank you, this is what I'm asking. So after programming the chip, for reprogramming it, I must connect it to PC and then press reset button and before reaching timeout (about 5 secs I think), I must program it again?

That's the way I understood it worked.

https://digistump.com/wiki/digispark/tutorials/connectingpro
It is suggested that in order to upload using the Arduino IDE you must:

Add the repository http://digistump.com/package_digistump_index.json in Preferences > Additional Boards Manager URLs
Install Digistump from the boards manager.
select the DigiSpark in Tools > Boards.
Then this is perhaps the important bit "You do not need to plug in your Digispark Pro before invoking upload"   So hit upload before connecting the Digispark.
Then connect the Digispark when prompted by the Arduino IDE.


text:
How can I play music using a speaker and Micro SD card Module?
I am trying to play music using my Arduino and micro SD card module but can't seem to do it. Can anyone shed some light on this? The SD card module I'm using is a Catalex sainsmart micro SD card module. It has the outputs VCC, GND, MISO, MOSI, CS, and SCK. VCC is in 5v, GND is in GND, CS is in Pin 4, MISO is in Pin 12, and MOSI is in Pin 11.

Your question is very broad and more detail is needed. For example, I take it that the music file resides on the SD card but what format would the music be? Would you be willing to change format? Also, what is your circuit? What have you tried so far?

I don't care what kind of file it must be. Also CS is plugged into 4, SCK is plugged into 13, Mosi is plugged into 11, Miso is plugged into 12, VCC is plugged into 5v, and GND is in GND.

please edit your question and add these details. Comments are for information that can be ignored.

This Arduino project is one of the most simple and fun projects you
  can build with Arduino in 10-15 minutes. The result of this make will
  be an Arduino Audio Player which will play “.wav” files. It consist of
  a speaker, a simple transistor acting as an amplifier and a micro-SD
  card adapter with a micro-SD in it through which the .wav files are
  loaded and played.

https://diyhacking.com/arduino-audio-player/

Thank you but does the speaker have to be the one he is using or can it be one that just plays clicks?

I expect any speaker is fine as long as the power is catered for, You can probably just wire a Piezo Speaker directly to output pins to play clicks

Use an MP3 shield. This includes an SD card reader on the board. Many tutorials are available for this popular board. This shield makes it easier to program the Arduino.
https://www.sparkfun.com/products/12660


text:
which Arduino UNO ethernet shield supports power over ethernet?
I ordered for this ethernet shield for my UNO as shown on the amazon website listing

I was thinking to add power over ethernet module to take advantage of shield that supports adding POE module.

.
But I received the one below

Does the one I received POE? Without the use of POE module!

No, it's not possible at all with this "MagJack". But you can always use injectors/extractors with 9V or 12V power supply...


text:
Why change the variable content?
I don't understand why change uidList[reader] variable, when doesn't run more to the else. I use in this test only the "0" reader.
First loop go to the "else" and fill the uid to uidList[reader]. (good)
Second loop go to the "if" because the two uid is equal.(good)
I remove NFC and place the other, but the uidList[reader] updated immediately to the new UID, not in the "else". Never go again to else. Why?
#define NR_OF_READERS   2
byte* uidList[NR_OF_READERS];
MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
......
void loop() {
  ....
  delay(2500);
  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {

     dump_byte_array(uidList[0], 8);
     dump_byte_array(uidList[1], 8);

   if (mfrc522[reader].PICC_IsNewCardPresent() &&     mfrc522[reader].PICC_ReadCardSerial()) {

     dump_byte_array(uidList[0], 8); //WHY UPDATED HERE???
     dump_byte_array(uidList[1], 8);

     if (uidList[reader] == mfrc522[reader].uid.uidByte) {

        Serial.println(F("Same NFC"));
        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     } else {

        Serial.println(F("Other NFC in this reader"));

        uidList[reader] = mfrc522[reader].uid.uidByte;

        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     }

   }
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
  Serial.println();
}

When I placed the new NFC in the reader, this debug appear on serial monitor.
 DF 6D 05 D2 00 00 00 00 //old NFC uid it's good

 AB 00 6C 02 F0 21 00 00

 FF 2C 02 69 00 00 00 00 //WHY UPDATED HERE???

 AB 00 6C 02 F0 21 00 00

Same NFC
 FF 2C 02 69 00 00 00 00

 AB 00 6C 02 F0 21 00 00

Thanks any idea.

The question isn't clear enough for me to understand what you are asking.

Why change uidList[reader] without "else". Without this: uidList[reader] = mfrc522[reader].uid.uidByte;

Well, it's easy, as you are using pointers. If the original place gets changed, you can see changed value because you don't have your own copy.
Your if statement is also wrong, as you are comparing two pointers here. They will be different at the first time comparation, but after the assigment they are unlikely to change.
The solution is using:
byte uidList[NR_OF_READERS][8]; // better to use some constant value instead of magic number

and memcpy for making a copy and memcmp for comparing its content. Both are from <cstring> include

Thx, you're right, but what is the solution? How do I compare the value, not the pointer in this code?

@Cipo You've to have your own space to store those values and you've to use the right functions for copying and comparing these values (or make your own). Added into the answer.


text:
Does the Arduino Uno have two crystals?
Take a look at this picture:

I think most of use agree that the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently.
I was bored so I looked at my Arduino Uno, and saw that it has what seems like another crystal (yellow). It looks like the one that is on the Pro Mini. It's also located near the XTAL pins. After I inspected the schematic a second time, it also appears that there are two crystals on the board.
Which one out of those two is actually connected to the XTAL pins and why are there two?

The ceramic resonator in yellow is connected to the main MCU, and the crystal in red is connected to the other MCU. USB requires tighter tolerances than is available from a resonator therefore a crystal must be used instead.

There are 2 that you can see, but there are internal resonators in both chips. You can use the ATMega328's one if it's on a breadboard (it's half the frequency tho), and much more temperature-dependent. Just need to give it a fresh bootloader.


text:
Thermosensor Error - 'Wire' does not name type?
Here is the code I am using:
#define D6T_ID 0x0A
#define D6T_CMD 0x4C

int ReadBuffer[35];
float ptat;
float tdata[16];

#include <Wire.h>
void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(500);

}

void loop() {

}
  int i;
  Wire.beginTransmission(D6T_ID);
  Wire.write(D6T_CMD);
  Wire.endTransmission();

  Wire.requestFrom(D6T_ID,35);

  for (i=0; i<35; ++i) {
    ReadBuffer[i] = Wire.read();
  }

  ptat = (ReadBuffer[0]+(ReadBuffer[1]*256))*0.1; //Reference Temp

  for (i=0; i<16; ++i) {
    tdata[i] = (ReadBuffer[(i*2+2)]+(ReadBuffer[(i*2+3)]*256))*0.1;
  }

  float tempF;

  if ( ((tdata[0]*9.0/5.0)+32.0)>0 )
  {
    for (i=0; i<16; ++i)
    {
      tempF = (tdata[i]*9.0/5.0)+32.0;
      Serial.print(tempF);
      Serial.print(',');
    }
    Serial.print((ptat*9.0/5.0)+32.0;
    Serial.print(',');
    Serial.println();
  }

    }
  }

This is the error I am getting:
exit status 1
'Wire' does not name a type
And it highlights this area of code:
Wire.requestFrom(D6T_ID,35);

I am completely new to using the arduino and coding so I am not sure if I already have the wire library that this code requires but when I look at the libraries in the Tools menu it is there. Do I need to download another library? If so can someone send me the link? Can someone explain what the error means? This is all foreign to me.
Thank you

***** It should say #include <Wire.h>

Your braces are not right. For example, for the loop function you have an open brace and then a close brace before you code starts.

You've goofed up your braces and none of that code is in loop(). Look at the braces in the code and make the appropriate corrections.

The reason for the error message is that your braces do not properly match, and the code that was meant to be inside loop() is not, but instead looks to the compiler like some new global declarations. Fix the syntax errors and your code will compile:

Remove the brace in line 18 that closes the loop() function prematurely,
Fix the missing ')' in line 46,
Remove line 52, an extraneous '}',


text:
How do interrupts work on the Arduino Uno and similar boards?
Please explain how interrupts work on the Arduino Uno and related boards using the ATmega328P processor. Boards such as the:

Uno
Mini
Nano
Pro Mini
Lilypad

In particular please discuss:

What to use interrupts for
How to write an Interrupt Service Routine (ISR)
Timing issues
Critical sections
Atomic access to data

Note: this is a reference question.

TL;DR :
When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be protected by "critical sections" (see below)
Don't try to turn interrupts off or on

What are interrupts?
Most processors have interrupts. Interrupts let you respond to "external" events while doing something else. For example, if you are cooking dinner you may put the potatoes on to cook for 20 minutes. Rather than staring at the clock for 20 minutes you might set a timer, and then go watch TV. When the timer rings you "interrupt" your TV viewing to do something with the potatoes.

Example of interrupts
const byte LED = 13;
const byte SWITCH = 2;

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  if (digitalRead (SWITCH) == HIGH)
    digitalWrite (LED, HIGH);
  else
    digitalWrite (LED, LOW);
}  // end of switchPressed

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  pinMode (SWITCH, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (SWITCH), switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

This example shows how, even though the main loop is doing nothing, you can turn the LED on pin 13 on or off, if the switch on pin D2 is pressed.
To test this, just connect a wire (or switch) between D2 and Ground. The internal pullup (enabled in setup) forces the pin HIGH normally. When grounded, it becomes LOW. The change in the pin is detected by a CHANGE interrupt, which causes the Interrupt Service Routine (ISR) to be called.
In a more complicated example, the main loop might be doing something useful, like taking temperature readings, and allow the interrupt handler to detect a button being pushed.

Converting pin numbers to interrupt numbers
To simplify converting interrupt vector numbers to pin numbers you can call the function digitalPinToInterrupt(), passing a pin number. It returns the appropriate interrupt number, or NOT_AN_INTERRUPT (-1).
For example, on the Uno, pin D2 on the board is interrupt 0 (INT0_vect from the table below).
Thus these two lines have the same effect:
  attachInterrupt (0, switchPressed, CHANGE);    // that is, for pin D2
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);

However the second one is easier to read and more portable to different Arduino types.

Available interrupts
Below is a list of interrupts, in priority order, for the Atmega328:
 1  Reset
 2  External Interrupt Request 0  (pin D2)          (INT0_vect)
 3  External Interrupt Request 1  (pin D3)          (INT1_vect)
 4  Pin Change Interrupt Request 0 (pins D8 to D13) (PCINT0_vect)
 5  Pin Change Interrupt Request 1 (pins A0 to A5)  (PCINT1_vect)
 6  Pin Change Interrupt Request 2 (pins D0 to D7)  (PCINT2_vect)
 7  Watchdog Time-out Interrupt                     (WDT_vect)
 8  Timer/Counter2 Compare Match A                  (TIMER2_COMPA_vect)
 9  Timer/Counter2 Compare Match B                  (TIMER2_COMPB_vect)
10  Timer/Counter2 Overflow                         (TIMER2_OVF_vect)
11  Timer/Counter1 Capture Event                    (TIMER1_CAPT_vect)
12  Timer/Counter1 Compare Match A                  (TIMER1_COMPA_vect)
13  Timer/Counter1 Compare Match B                  (TIMER1_COMPB_vect)
14  Timer/Counter1 Overflow                         (TIMER1_OVF_vect)
15  Timer/Counter0 Compare Match A                  (TIMER0_COMPA_vect)
16  Timer/Counter0 Compare Match B                  (TIMER0_COMPB_vect)
17  Timer/Counter0 Overflow                         (TIMER0_OVF_vect)
18  SPI Serial Transfer Complete                    (SPI_STC_vect)
19  USART Rx Complete                               (USART_RX_vect)
20  USART, Data Register Empty                      (USART_UDRE_vect)
21  USART, Tx Complete                              (USART_TX_vect)
22  ADC Conversion Complete                         (ADC_vect)
23  EEPROM Ready                                    (EE_READY_vect)
24  Analog Comparator                               (ANALOG_COMP_vect)
25  2-wire Serial Interface  (I2C)                  (TWI_vect)
26  Store Program Memory Ready                      (SPM_READY_vect)

Internal names (which you can use to set up ISR callbacks) are in brackets.
Warning: If you misspell the interrupt vector name, even by just getting the capitalization wrong (an easy thing to do) the interrupt routine will not be called, and you will not get a compiler error.

Reasons to use interrupts
The main reasons you might use interrupts are:

To detect pin changes (eg. rotary encoders, button presses)
Watchdog timer (eg. if nothing happens after 8 seconds, interrupt me)
Timer interrupts - used for comparing/overflowing timers
SPI data transfers
I2C data transfers
USART data transfers
ADC conversions (analog to digital)
EEPROM ready for use
Flash memory ready

The "data transfers" can be used to let a program do something else while data is being sent or received on the serial port, SPI port, or I2C port.
Wake the processor
External interrupts, pin-change interrupts, and the watchdog timer interrupt, can also be used to wake the processor up. This can be very handy, as in sleep mode the processor can be configured to use a lot less power (eg. around 10 microamps). A rising, falling, or low-level interrupt can be used to wake up a gadget (eg. if you press a button on it), or a "watchdog timer" interrupt might wake it up periodically (eg. to check the time or temperature).
Pin-change interrupts could be used to wake the processor if a key is pressed on a keypad, or similar.
The processor can also be awoken by a timer interrupt (eg. a timer reaching a certain value, or overflowing) and certain other events, such as an incoming I2C message.

Enabling / disabling interrupts
The "reset" interrupt cannot be disabled. However the other interrupts can be temporarily disabled by clearing the global interrupt flag.
Enable interrupts
You can enable interrupts with the function call "interrupts" or "sei" like this:
interrupts ();  // or ...
sei ();         // set interrupts flag

Disable interrupts
If you need to disable interrupts you can "clear" the global interrupt flag like this:
noInterrupts ();  // or ...
cli ();           // clear interrupts flag

Either method has the same effect, using interrupts / noInterrupts is a bit easier to remember which way around they are.
The default in the Arduino is for interrupts to be enabled. Don't disable them for long periods or things like timers won't work properly.
Why disable interrupts?
There may be time-critical pieces of code that you don't want interrupted, for example by a timer interrupt.
Also if multi-byte fields are being updated by an ISR then you may need to disable interrupts so that you get the data "atomically". Otherwise one byte may be updated by the ISR while you are reading the other one.
For example:
noInterrupts ();
long myCounter = isrCounter;  // get value set by ISR
interrupts ();

Temporarily turning off interrupts ensures that isrCounter (a counter set inside an ISR) does not change while we are obtaining its value.
Warning: if you are not sure if interrupts are already on or not, then you need to save the current state and restore it afterwards. For example, the code from the millis() function does this:
unsigned long millis()
{
  unsigned long m;
  uint8_t oldSREG = SREG;    // <--------- save status register

  // disable interrupts while we read timer0_millis or we might get an
  // inconsistent value (e.g. in the middle of a write to timer0_millis)
  cli();
  m = timer0_millis;
  SREG = oldSREG;            // <---------- restore status register including interrupt flag

  return m;
}

Note the indicated lines save the current SREG (status register) which includes the interrupt flag. After we have obtained the timer value (which is 4 bytes long) we put the status register back how it was.

Tips
Function names
The functions cli / sei and the register SREG are specific to the AVR processors. If you are using other processors such as the ARM ones the functions may be slightly different.
Disabling globally vs disabling one interrupt
If you use cli() you disable all interrupts (including timer interrupts, serial interrupts, etc.).
However if you just want to disable a particular interrupt then you should clear the interrupt-enable flag for that particular interrupt source. For example, for external interrupts, call detachInterrupt().

What is interrupt priority?
Since there are 25 interrupts (other than reset) it is possible that more than one interrupt event might occur at once, or at least, occur before the previous one is processed. Also an interrupt event might occur while interrupts are disabled.
The priority order is the sequence in which the processor checks for interrupt events. The higher up the list, the higher the priority. So, for example, an External Interrupt Request 0 (pin D2) would be serviced before External Interrupt Request 1 (pin D3).

Can interrupts occur while interrupts are disabled?
Interrupts events (that is, noticing the event) can occur at any time, and most are remembered by setting an "interrupt event" flag inside the processor. If interrupts are disabled, then that interrupt will be handled when they are enabled again, in priority order.

How do you use interrupts?

You write an ISR (interrupt service routine). This is called when the interrupt occurs.
You tell the processor when you want the interrupt to fire.

Writing an ISR
Interrupt Service Routines are functions with no arguments. Some Arduino libraries are designed to call your own functions, so you just supply an ordinary function (as in the examples above), eg.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
 flag = true;
}  // end of switchPressed

However if a library has not already provided a "hook" to an ISR you can make your own, like this:
volatile char buf [100];
volatile byte pos;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;
    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

In this case you use the "ISR" macro, and supply the name of the relevant interrupt vector (from the table earlier on). In this case the ISR is handling an SPI transfer completing. (Note, some old code uses SIGNAL instead of ISR, however SIGNAL is deprecated).
Connecting an ISR to an interrupt
For interrupts already handled by libraries, you just use the documented interface. For example:
void receiveEvent (int howMany)
 {
  while (Wire.available () > 0)
    {
    char c = Wire.receive ();
    // do something with the incoming byte
    }
}  // end of receiveEvent

void setup ()
  {
  Wire.onReceive(receiveEvent);
  }

In this case the I2C library is designed to handle incoming I2C bytes internally, and then call your supplied function at the end of the incoming data stream. In this case receiveEvent is not strictly an ISR (it has an argument) but it is called by an inbuilt ISR.
Another example is the "external pin" interrupt.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
}  // end of switchPressed

void setup ()
{
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);  // attach interrupt handler for D2
}  // end of setup

In this case the attachInterrupt function adds the function switchPressed to an internal table, and in addition configures the appropriate interrupt flags in the processor.
Configuring the processor to handle an interrupt
The next step, once you have an ISR, is to tell the processor that you want this particular condition to raise an interrupt.
As an example, for External Interrupt 0 (the D2 interrupt) you could do something like this:
EICRA &= ~3;  // clear existing flags
EICRA |= 2;   // set wanted flags (falling level interrupt)
EIMSK |= 1;   // enable it

More readable would be to use the defined names, like this:
EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
EICRA |= bit (ISC01);    // set wanted flags (falling level interrupt)
EIMSK |= bit (INT0);     // enable it

EICRA (External Interrupt Control Register A) would be set according to this table from the Atmega328 datasheet.
That defines the exact type of interrupt you want:

0: The low level of INT0 generates an interrupt request (LOW interrupt).
1: Any logical change on INT0 generates an interrupt request (CHANGE interrupt).
2: The falling edge of INT0 generates an interrupt request (FALLING interrupt).
3: The rising edge of INT0 generates an interrupt request (RISING interrupt).

EIMSK (External Interrupt Mask Register) actually enables the interrupt.
Fortunately you don't need to remember those numbers because attachInterrupt does that for you. However that is what is actually happening, and for other interrupts you may have to "manually" set interrupt flags.

Low-level ISRs vs. library ISRs
To simplify your life some common interrupt handlers are actually inside library code (for example INT0_vect and INT1_vect) and then a more user-friendly interface is provided (eg. attachInterrupt). What attachInterrupt actually does is save the address of your wanted interrupt handler into a variable, and then call that from INT0_vect / INT1_vect when needed. It also sets the appropriate register flags to call the handler when required.

Can ISRs be interrupted?
In short, no, not unless you want them to be.
When an ISR is entered, interrupts are disabled. Naturally they must have been enabled in the first place, otherwise the ISR would not be entered. However to avoid having an ISR itself be interrupted, the processor turns interrupts off.
When an ISR exits, then interrupts are enabled again. The compiler also generates code inside an ISR to save registers and status flags, so that whatever you were doing when the interrupt occurred will not be affected.
However you can turn interrupts on inside an ISR if you absolutely must, eg.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
  interrupts ();  // allow more interrupts

}  // end of switchPressed

Normally you would need a pretty good reason to do this, as another interrupt now could result in a recursive call to pinChange, with quite possibly undesirable results.

How long does it take to execute an ISR?
According to the datasheet, the minimal amount of time to service an interrupt is 4 clock cycles (to push the current program counter onto the stack) followed by the code now executing at the interrupt vector location. This normally contains a jump to where the interrupt routine really is, which is another 3 cycles. Examination of the code produced by the compiler shows that an ISR made with the "ISR" declaration can take around 2.625 µs to execute, plus whatever the code itself does. The exact amount depends on how many registers need to be saved and restored. The minimum amount would be 1.1875 µs.
The external interrupts (where you use attachInterrupt) do a bit more and take around 5.125 µs in total (running with a 16 MHz clock).

How long before the processor starts entering an ISR?
This varies somewhat. The figures quoted above are the ideal ones where the interrupt is immediately processed. A few factors may delay that:

If the processor is asleep, there are designated "wake-up" times, which could be quite a few milliseconds, while the clock is spooled back up to speed. This time would depend on fuse settings, and how deep the sleep is.
If an interrupt service routine is already executing, then further interrupts cannot be entered until it either finishes, or enables interrupts itself. This is why you should keep each interrupt service routine short, as every microsecond you spend in one, you are potentially delaying the execution of another one.
Some code turns interrupts off. For example, calling millis() briefly turns interrupts off. Therefore the time for an interrupt to be serviced would be extended by the length of time interrupts were turned off.
Interrupts can only be serviced at the end of an instruction, so if a particular instruction takes three clock cycles, and has just started, then the interrupt will be delayed at least a couple of clock cycles.
An event that turns interrupts back on (eg. returning from an interrupt service routine) is guaranteed to execute at least one more instruction. So even if an ISR ends, and your interrupt is pending, it still has to wait for one more instruction before it is serviced.
Since interrupts have a priority, a higher-priority interrupt might be serviced before the interrupt you are interested in.

Performance considerations
Interrupts can increase performance in many situations because you can get on with the "main work" of your program without having to constantly be testing to see if switches have been pressed. Having said that, the overhead of servicing an interrupt, as discussed above, would actually be more than doing a "tight loop" polling a single input port. You can barely respond to an event within, say, a microsecond. In that case you might disable interrupts (eg. timers) and just loop looking for the pin to change.

How are interrupts queued?
There are two sorts of interrupts:

Some set a flag and they are handled in priority order, even if the event that caused them has stopped. For example, a rising, falling, or changing level interrupt on pin D2.
Others are only tested if they are happening "right now". For example, a low-level interrupt on pin D2.

The ones that set a flag could be regarded as being queued, as the interrupt flag remains set until such time as the interrupt routine is entered, at which time the processor clears the flag. Of course, since there is only one flag, if the same interrupt condition occurs again before the first one is processed, it won't be serviced twice.
Something to be aware of is that these flags can be set before you attach the interrupt handler. For example, it is possible for a rising or falling level interrupt on pin D2 to be "flagged", and then as soon as you do an attachInterrupt the interrupt immediately fires, even if the event occurred an hour ago. To avoid this you can manually clear the flag. For example:
EIFR = bit (INTF0);  // clear flag for interrupt 0
EIFR = bit (INTF1);  // clear flag for interrupt 1

However the "low level" interrupts are continuously checked, so if you are not careful they will keep firing, even after the interrupt has been called. That is, the ISR will exit, and then the interrupt will immediately fire again. To avoid this, you should do a detachInterrupt immediately after you know that the interrupt fired.

Hints for writing ISRs
In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.
A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.
Remember, inside an ISR interrupts are disabled. Thus hoping that the time returned by millis() function calls will change, will lead to disappointment. It is valid to obtain the time that way, just be aware that the timer is not incrementing. And if you spend too long in the ISR then the timer may miss an overflow event, leading to the time returned by millis() becoming incorrect.
A test shows that, on a 16 MHz Atmega328 processor, a call to micros() takes 3.5625 µs. A call to millis() takes 1.9375 µs. Recording (saving) the current timer value is a reasonable thing to do in an ISR. Finding the elapsed milliseconds is faster than the elapsed microseconds (the millisecond count is just retrieved from a variable). However the microsecond count is obtained by adding the current value of the Timer 0 timer (which will keep incrementing) to a saved "Timer 0 overflow count".
Warning: Since interrupts are disabled inside an ISR, and since the latest version of the Arduino IDE uses interrupts for Serial reading and writing, and also for incrementing the counter used by "millis" and "delay" you should not attempt to use those functions inside an ISR. To put it another way:

Don't attempt to delay, eg: delay (100);
You can get the time from a call to millis, however it won't increment, so don't attempt to delay by waiting for it to increase.
Don't do serial prints (eg. Serial.println ("ISR entered"); )
Don't try to do serial reading.

Pin change interrupts
There are two ways you can detect external events on pins. The first is the special "external interrupt" pins, D2 and D3. These general discrete interrupt events, one per pin. You can get to those by using attachInterrupt for each pin. You can specify a rising, falling, changing or low-level condition for the interrupt.
However there are also "pin change" interrupts for all pins (on the Atmega328, not necessarily all pins on other processors). These act on groups of pins (D0 to D7, D8 to D13, and A0 to A5). They are also lower priority than the external event interrupts. However they are a bit more fiddly to use than the external interrupts because they are grouped into batches. So if the interrupt fires you have to work out in your own code exactly which pin caused the interrupt.
Example code:
ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here
 }  // end of PCINT0_vect

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here
 }  // end of PCINT1_vect

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }

To handle a pin change interrupt you need to:

Specify which pin in the group. This is the PCMSKn variable (where n is 0, 1 or 2 from the table below). You can have interrupts on more than one pin.
Enable the appropriate group of interrupts (0, 1 or 2)
Supply an interrupt handler as shown above

Table of pins -> pin change names / masks
D0    PCINT16 (PCMSK2 / PCIF2 / PCIE2)
D1    PCINT17 (PCMSK2 / PCIF2 / PCIE2)
D2    PCINT18 (PCMSK2 / PCIF2 / PCIE2)
D3    PCINT19 (PCMSK2 / PCIF2 / PCIE2)
D4    PCINT20 (PCMSK2 / PCIF2 / PCIE2)
D5    PCINT21 (PCMSK2 / PCIF2 / PCIE2)
D6    PCINT22 (PCMSK2 / PCIF2 / PCIE2)
D7    PCINT23 (PCMSK2 / PCIF2 / PCIE2)
D8    PCINT0  (PCMSK0 / PCIF0 / PCIE0)
D9    PCINT1  (PCMSK0 / PCIF0 / PCIE0)
D10   PCINT2  (PCMSK0 / PCIF0 / PCIE0)
D11   PCINT3  (PCMSK0 / PCIF0 / PCIE0)
D12   PCINT4  (PCMSK0 / PCIF0 / PCIE0)
D13   PCINT5  (PCMSK0 / PCIF0 / PCIE0)
A0    PCINT8  (PCMSK1 / PCIF1 / PCIE1)
A1    PCINT9  (PCMSK1 / PCIF1 / PCIE1)
A2    PCINT10 (PCMSK1 / PCIF1 / PCIE1)
A3    PCINT11 (PCMSK1 / PCIF1 / PCIE1)
A4    PCINT12 (PCMSK1 / PCIF1 / PCIE1)
A5    PCINT13 (PCMSK1 / PCIF1 / PCIE1)

Interrupt handler processing
The interrupt handler would need to work out which pin caused the interrupt if the mask specifies more than one (eg. if you wanted interrupts on D8/D9/D10). To do this you would need to store the previous state of that pin, and work out (by doing a digitalRead or similar) if this particular pin had changed.

You are probably using interrupts anyway ...
A "normal" Arduino environment already is using interrupts, even if you don't personally attempt to. The millis() and micros() function calls make use of the "timer overflow" feature. One of the internal timers (timer 0) is set up to interrupt roughly 1000 times a second, and increment an internal counter which effectively becomes the millis() counter. There is a bit more to it than that, as adjustment is made for the exact clock speed.
Also the hardware serial library uses interrupts to handle incoming and outgoing serial data. This is very useful as your program can be doing other things while the interrupts are firing, and filling up an internal buffer. Then when you check Serial.available() you can find out what, if anything, has been placed in that buffer.

Executing the next instruction after enabling interrupts
After a bit of discussion and research on the Arduino forum, we have clarified exactly what happens after you enable interrupts. There are three main ways I can think of that you can enable interrupts, which were previously not enabled:
  sei ();  // set interrupt enable flag
  SREG |= 0x80;  // set the high-order bit in the status register
  reti  ;   // assembler instruction "return from interrupt"

In all cases, the processor guarantees that the next instruction after interrupts are enabled (if they were previously disabled) will always be executed, even if an interrupt event is pending. (By "next" I mean the next one in program sequence, not necessarily the one physically following. For example, a RETI instruction jumps back to where the interrupt occurred, and then executes one more instruction).
This lets you write code like this:
sei ();
sleep_cpu ();

If not for this guarantee, the interrupt might occur before the processor slept, and then it might never be awoken.

Empty interrupts
If you merely want an interrupt to wake the processor, but not do anything in particular, you can use the EMPTY_INTERRUPT define, eg.
EMPTY_INTERRUPT (PCINT1_vect);

This simply generates a "reti" (return from interrupt) instruction. Since it doesn't try to save or restore registers this would be the fastest way to get an interrupt to wake it up.

Critical sections (atomic variable access)
There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).
Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.
First ... when do you use "volatile" variables?
A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.
volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variables contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.
Turn interrupts off while accessing a volatile variable
For example, to compare count to some number, turn interrupts off during the compare in case one byte of count has been updated by the ISR and not the other byte.
volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  noInterrupts ();    // <------ critical section
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();      // <------ end critical section
  } // end of loop

Read the data sheet!
More information about interrupts, timers, etc. can be obtained from the data sheet for the processor.
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

Further examples
Space considerations (post size limit) prevent my listing more example code. For more example code see my page about interrupts.

A very useful reference-that was an impressively  quick answer.

It was a reference question. I had the answer prepared and it would have been even faster if the answer hadn't been too long, so I had to prune it back. See the linked site for more details.

About the "sleep mode" is it efficient to make the Arduino sleep for, let's say, 500ms?

@Nick Gammon I guess turning the power on or off (with automation or not) for the CPU can be defined as an unconventional interrupt- if you wanted to do that. "I had the answer prepared "-you just took out all the magic of that moment I thought it had.

is it efficient to make the Arduino sleep for, let's say, 500ms - certainly it is. I have a project that flashes an LED every second or so, and sleeps inbetween. The much lower power consumption when asleep saves a lot of battery power.

I guess turning the power on or off (with automation or not) for the CPU can be defined as an unconventional interrupt - turning the power off and on would cause a Reset "interrupt".

Just some notes: - Mechanical bouncing should be mentioned in the Example of interrupts. - Not every interrupt source can be used to wake up CPU in most sleep modes. - You can miss interrupt if there was more than one event during processing another ISR or critical section. (in section Can interrupt occur ...). - If you need only flag without knowing how many times, you can use corresponding flag without enabling interrupt. Flag must be cleared manually by writing logic 1 (in section Hints). - Max frequency for pin change interrupts and its duty cycle (F_CPU/2 for 50:50)

I'm constrained here by the post size limit. I initially had about a 36000 byte post, which exceeded the 30000 byte limit. I trimmed it down to 29990 bytes and hit "Send" only to be informed that my post was 36000 bytes. I then deleted 6000 bytes to get it accepted. So if you want to suggest additions, you also have to suggest equivalent deletions. Sorry. :)

Yes, Something like Arduino "Documentation" from SO would be more suitable. Too bad, it's not available here.

Fantastic reference! A few comments: In Wake the processor: any interrupt can wake the CPU unless in deep sleep (sleep mode other than IDLE). In Enabling / disabling interrupts: since many flags are called “interrupt flag”, I would rather follow Atmel and use “global interrupt flag” for SREG(I). In Why disable interrupts?: replace “save/restore processor registers” → save/restore status register. Or you may want to document ATOMIC_BLOCK() instead of explicitly saving and restoring SREG... In Writing an ISR: "ISR" define → "ISR" macro.

In How long does it take to execute an ISR?: The length of the prologue and epilogue depends on how many registers the ISR needs. Minimum is 8 (prologue) and 11 (epilogue) CPU cycles. In How long before the processor starts entering an ISR?: various somewhat → varies somewhat. In Performance considerations: You may barely respond in 1 µs if there are no other interrupts enabled and no cli(). In You are probably using interrupts anyway ...: drop “in the more recent library versions”, it's been like this since 1.0-beta2 (released on August 2011).

@EdgarBonet - added most of your suggestions (I think).

@KIIV - Not every interrupt source can be used to wake up CPU in most sleep modes - which ones did you have in mind? If you need only flag without knowing how many times, you can use corresponding flag without enabling interrupt. - what is this referring to?

@NickGammon 1. For example Power-down sleep mode can be waked up only by WDT, TWI address match and by External interrupt (low level detection only). Pin change interrupts can wake the CPU only in Idle mode (External interrupts only low level detection). And so on. 2. It's referring to the second paragraph in section Hints for writing ISRs

I'm afraid that isn't true. I have an example that uses pin change interrupts to wake from power-down mode. Also as I mention on my page about interrupts Atmel have confirmed that any external interrupt will wake the processor (ie. rising/falling/change and low).

It's referring to the second paragraph in section Hints for writing ISRs - yes but there is nothing explicitly wrong about what I wrote is there? Certainly checking the flag can let you know an interrupt was signalled (as is done in micros).

Well, then it serves its purpose and I've just learned something really interesting (I just have to retest it).
And yes, there is nothing wrong about that paragraph. It's just possible to use interrupt flags directly instead of calling ISR and set another variable. (If it's possible and you don't need immediate response/action. If you have to know how many times event happened between checks, you have to use ISR and counter variable anyways)


text:
Problems reading I2C sensor when using a Xbee module
I'm developing a project where I can control a RC boat with GPS and a magnetometer. How ever, I was developing everything connected to my computer and worked pretty well. When I was going to make some test with a battery and a couple of Xbee's (PC and "Arduino"), the magnetometer signal was not updating. So, I read the first value and continued to transmit the same value (thing that never happened on computer). Has someone had the same issue before? How can I solve this? Oh, one thing. The GPS and magnetometer comes in the same module, and I'm having no problems with GPS coordinates. And even if I power de MCU with my computer and transmitting with the Xbee's it doesn't work either. Seems like a communication problem.
Hardware used:
GPS Module + Compass
ATmega1284P
UPDATE:
I want to share also the code I'm using for the I2C reading.
#include <Wire.h> //I2C Arduino Library
#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  Wire.endTransmission();
}

 void loop(){

  int x,y,z; //triple axis data

  //Tell the HMC5883L where to begin reading data
  Wire.beginTransmission(address);
  Wire.send(0x03); //select register 3, X MSB register
  Wire.endTransmission();

 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(address, 6);
  if(6<=Wire.available()){
    x = Wire.receive()<<8; //X msb
    x |= Wire.receive(); //X lsb
    z = Wire.receive()<<8; //Z msb
    z |= Wire.receive(); //Z lsb
    y = Wire.receive()<<8; //Y msb
    y |= Wire.receive(); //Y lsb
  }

  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);

}

Maybe the battery is too weak. Or you are using voltage regulators with too high voltage drop. It can be anything.

Try and solve one problem at a time.  Make a simple circuit that reads the magnetomerter and check it works on the computer.  If it does try it on the battery.
Then try and solve the Xbee problem.

@KIIV I'm using a powerbank, so the battery is not a problem. Even if I supply my MCU from the computer and make the communication wireslessly, it doesn't work.

@Matt I have already done that, with every possibilities of connections and power supplies. Seems to be a communication problem when I'm using the Xbee's.

This sounds less like a battery problem and more like a Xbee problem.  I would, as @Matt said, test 1 thing at a time.  That is, test your Xbee with something simple like a fixed message that has nothing to do with your sensor.  Then, if it is a Xbee problem, change your question and question's title ... as you are attracting the wrong type of answer.

@st2000 you're right. At the beggining I was thinking it was a battery problem but seems to be a communication problem now that I have tried every possibilities. Already changed the title. Thanks.

@AlejandroHarrisBonet It might be worth flashing the light when the value changes, just to make sure it is changing.  I would also go back to the XBee equivalent of Hello World.  If that works you could be looking at libray conflicts.

Hey @Matt, thanks for commenting. The Xbee communication as it is, doesn't have any problems at all. I can receive data. The real problem is updating the data I'm getting from the sensor. Since I told it to work as a continuous measurement mode, it doesn't update the sensor values. Maybe there is a problem when I'm trying to tell the sensor to be at this mode, because every time I reset the MCU, it changes the value but it doesn't update.

I have solved the problem by adding a delay just before I select the continuous measurement mode.
void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  delay(100);
  Wire.endTransmission();
}

try delay(1). Acording to shared experiences, that delay is needed by it can be shorter.

There are 2 possible problems:
Lack of power or libraries not supporting each other.
1 - Try powering the circuit with some USB 5V. Make sure that your other modules can support 5V. Also check your clock speed. High clock speeds with low voltages might cause your ATmega to function incorrectly.
2 - Some libraries for certain module / breakout uses software I2C which pretty much emulate I2C. They might not be compatible with another module that needs the wire library to function proprely. To debug it, test out 1 module at the time with the battery.

Hey, I'm using wire.h library and reading the sensor directly from its registers. The batteries I use for the supply is a cellphone powerbank, so pretty much is the same if I connected the MCU with my PC.

Any other libraries?

No, just wire.h, I updated the question, so you can have an idea of my issue. Thanks for commenting.


text:
how to communicate MPU-6050 ( on arduino micro) wirelessly using nrf24l01 to arduino uno?
I have an Arduino Micro and MPU-6050. I'm trying to transfer the data obtained from the MPU-6050 wirelessly to my computer using an Arduino Uno at the other end. I'm not sure how to make this happen.
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        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)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

Please add more detail to the question. Explain in a detailed way how this is all set up. What approach have you taken to solve this problem? What is it exactly that doesn't work? In your own testing, what have you ruled out and why? Does it work if the link was wired? Please add these details and more to the question.

You have a few options here for the wireless communication (~ denotes wireless):

MPU -> Arduino -> Bluetooth ~ ~ ~> PC
MPU -> Arduino -> NRF ~ ~ ~> NRF -> Arduino -> PC
MPU -> Arduino -> WiFi (ESP?) ~ ~ ~> PC

I don't think it'd be easy to directly communicate I2C over the NRF, so I'd just read the data over I2C (presumably you're using Jeff Roweburg's library?), then once you have it in an integer or byte, you can use any wireless module to send it over whatever method you prefer. I haven't touched the ESP8266 for WiFi, but I know the HC-05/06 and the NRF24L01 both have fairly simple libraries that can do a simple write command that will buffer a number of bytes and send it all out in the correct order.
edit:
This is code I used a long time ago, and it is almost definitely somebody else's. I'm dreadfully sorry I can't find the original author at the moment, else I'd happily link to their page on the NRF. You can split this up into a receive and transmit pair though, and get rid of all the serial printing stuff as that just used the NRFs to 'text' each other.
Two Way Communication:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);
const int radioNum = 0;
const byte rxAddr[6] = "00001";
const byte txAddr[6] = "00002";

String readSerial() {
    String input;
    while(Serial.available() > 0){
        input.concat((char)Serial.read());
        delay(1);     //allows the buffer to fill with each character
    }
    return input;
}

void setup()
{
  radio.begin();
  Serial.begin(9600);
  radio.setRetries(15, 15);
  if(radioNum){
    radio.openWritingPipe(rxAddr);
    radio.openReadingPipe(1, txAddr);
  }
  else{
    radio.openWritingPipe(txAddr);
    radio.openReadingPipe(1, rxAddr);
  }
  Serial.println("Enter a string of characters:");

}

void loop()
{
  radio.startListening();
  while(Serial.available()==0){
    char output[32];
    radio.read(&output, 32);
    if(output[0]){
      if(radioNum)
         Serial.print("Pong: ");
      else
         Serial.print("Ping: ");
      Serial.println(output);
    }
  }
  radio.stopListening();

  String input = readSerial();
  char text[32];
  input.toCharArray(text,32);
  radio.write(&text, 32);

  if(radioNum)
    Serial.print("Ping: ");
  else
    Serial.print("Pong: ");

  Serial.println(text);
}
}

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

Edited original answer to include some two-way communication code that I haven't tested in several months, so forgive me if it has some bugs. It requires the RF24 library

@EduardoCunha, Please add this to the question or start a new specific question. Comments are often ignored, so it is best to edit the question.

I'm not sure about the "wirelessly" context, but you can try this steps
1. Make sure you can read the mpu-6050 data
2. You can use bluetooth (HC-05 is the most common) to transfer data to your PC bluetooth directly, or to another arduino, then send it via serial usb cable to PC

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

This is just a conception plan:
Make sure you can get all the data (YPR) you need from the MPU.
Then, using whatever protocol you want, send the data under the form of something like a byte. Here is a question I aksed about a similar topic.
For more info, please comment, I'll be happy to help.

ok so I got ypr data from the mpu-6050. I posted the code. Now I want to transfer that data wirelessly using the NRF. How do I transfer the information from the mpu-6050 obtained through the NRF to another arduino?

Send it through a byte. By mapping the value from 0-99, you can send something like yypprraa where y is yaw, p is pitch, r is roll, and a is altitude.\

ok but How do I do this? I don't know how to do that. Is there some sample code I can mess with?


text:
troubleshooting - Turn on a single led in a ws2811 ledstrip with an arduino Uno with FastLed
I want to to turn on a single led in a ledstrip running on ws2811 with an Arduino Uno.
The problem is that when I try to turn just one of them on, they all three light up. The strip is a 3-wire strip, with GND, 12V and DIN. I am just running an example from the Arduino library FastLed
My code can be seen below
// Use if you want to force the software SPI subsystem to be used for some     reason (generally, you don't)
// #define FASTLED_FORCE_SOFTWARE_SPI
// Use if you want to force non-accelerated pin access (hint: you really don't, it breaks lots of things)
// #define FASTLED_FORCE_SOFTWARE_SPI
// #define FASTLED_FORCE_SOFTWARE_PINS
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 3

// Data pin that led data will be written out over
#define DATA_PIN 6

// Clock pin only needed for SPI based chipsets when not using hardware SPI
//#define CLOCK_PIN 8

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
delay(2000);
FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);

}

// your leds.
void loop() {
  leds[0] = CRGB::Red;
  leds[1] = CRGB::Black;
  leds[2] = CRGB::Black;
  FastLED.show();

}

There appears to be several versions of this chip.  Does your chip have pin 7 (SET) populated?  Also, are you building this from scratch?  (If so please post the schematic.) Is there a resistor between 12V and the VDD of the chip?

That is just the way those led strips are wired. They are sets of 3 leds connected to a single WS2811 chip. Those chips only have 3 color channels.